From 9b34a2dd8a32837a20539ff96dbefd0068dd4386 Mon Sep 17 00:00:00 2001 From: marun Date: Tue, 6 Aug 2024 14:37:25 -0700 Subject: [PATCH 01/69] [tmpnet] Fail node health check if node is not running (#3274) --- tests/fixture/tmpnet/network.go | 2 +- tests/fixture/tmpnet/node_process.go | 7 +++++-- tests/fixture/tmpnet/utils.go | 5 +---- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/fixture/tmpnet/network.go b/tests/fixture/tmpnet/network.go index afa59e653c14..695017c0620c 100644 --- a/tests/fixture/tmpnet/network.go +++ b/tests/fixture/tmpnet/network.go @@ -865,7 +865,7 @@ func waitForHealthy(ctx context.Context, w io.Writer, nodes []*Node) error { for { for node := range unhealthyNodes { healthy, err := node.IsHealthy(ctx) - if err != nil && !errors.Is(err, ErrNotRunning) { + if err != nil { return err } if !healthy { diff --git a/tests/fixture/tmpnet/node_process.go b/tests/fixture/tmpnet/node_process.go index a866cec63db9..8636d2953fdf 100644 --- a/tests/fixture/tmpnet/node_process.go +++ b/tests/fixture/tmpnet/node_process.go @@ -31,7 +31,10 @@ const ( defaultNodeInitTimeout = 10 * time.Second ) -var errNodeAlreadyRunning = errors.New("failed to start node: node is already running") +var ( + errNodeAlreadyRunning = errors.New("failed to start node: node is already running") + errNotRunning = errors.New("node is not running") +) func checkNodeHealth(ctx context.Context, uri string) (bool, error) { // Check that the node is reporting healthy @@ -194,7 +197,7 @@ func (p *NodeProcess) IsHealthy(ctx context.Context) (bool, error) { return false, fmt.Errorf("failed to determine process status: %w", err) } if proc == nil { - return false, ErrNotRunning + return false, errNotRunning } return checkNodeHealth(ctx, p.node.URI) diff --git a/tests/fixture/tmpnet/utils.go b/tests/fixture/tmpnet/utils.go index ba32ed3d4341..ea320f2a8801 100644 --- a/tests/fixture/tmpnet/utils.go +++ b/tests/fixture/tmpnet/utils.go @@ -6,7 +6,6 @@ package tmpnet import ( "context" "encoding/json" - "errors" "fmt" "time" @@ -18,8 +17,6 @@ const ( DefaultNodeTickerInterval = 50 * time.Millisecond ) -var ErrNotRunning = errors.New("not running") - // WaitForHealthy blocks until Node.IsHealthy returns true or an error (including context timeout) is observed. func WaitForHealthy(ctx context.Context, node *Node) error { if _, ok := ctx.Deadline(); !ok { @@ -30,7 +27,7 @@ func WaitForHealthy(ctx context.Context, node *Node) error { for { healthy, err := node.IsHealthy(ctx) - if err != nil && !errors.Is(err, ErrNotRunning) { + if err != nil { return fmt.Errorf("failed to wait for health of node %q: %w", node.NodeID, err) } if healthy { From 6626d2b7c1d5a108b12504a0d491f6cebd9dcb57 Mon Sep 17 00:00:00 2001 From: marun Date: Wed, 7 Aug 2024 06:45:58 -0700 Subject: [PATCH 02/69] [tmpnet] Enable network restart to simplify iteration (#3272) --- tests/e2e/README.md | 11 +++++++++++ tests/fixture/e2e/env.go | 3 +++ tests/fixture/e2e/flags.go | 11 +++++++++++ 3 files changed, 25 insertions(+) diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 0ba62d0b99f1..187623893681 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -77,6 +77,17 @@ If a network is not already running the first time the suite runs with `--reuse-network`, one will be started automatically and configured for reuse by subsequent test runs also supplying `--reuse-network`. +### Restarting temporary networks + +When iterating on a change to avalanchego and/or a VM, it may be +useful to restart a running network to ensure the network is using the +latest binary state. Supplying `--restart-network` in addition to +`--reuse-network` will ensure that all nodes are restarted before +tests are run. `--restart-network` is ignored if a network is not +running or if `--stop-network` is supplied. + +### Stopping temporary networks + To stop a network configured for reuse, invoke the test suite with the `--stop-network` argument. This will stop the network and exit immediately without executing any tests: diff --git a/tests/fixture/e2e/env.go b/tests/fixture/e2e/env.go index f6bf98ddbadb..59ad8c4a67bf 100644 --- a/tests/fixture/e2e/env.go +++ b/tests/fixture/e2e/env.go @@ -110,6 +110,9 @@ func NewTestEnvironment(tc tests.TestContext, flagVars *FlagVars, desiredNetwork tc.Outf("No network to stop\n") } os.Exit(0) + } else if network != nil && flagVars.RestartNetwork() { + // A network is only restarted if it is already running and stop was not requested + require.NoError(network.Restart(tc.DefaultContext(), tc.GetWriter())) } } diff --git a/tests/fixture/e2e/flags.go b/tests/fixture/e2e/flags.go index 4b489d5c133f..2b7fc8a3b6a8 100644 --- a/tests/fixture/e2e/flags.go +++ b/tests/fixture/e2e/flags.go @@ -19,6 +19,7 @@ type FlagVars struct { reuseNetwork bool delayNetworkShutdown bool stopNetwork bool + restartNetwork bool nodeCount int activateEtna bool } @@ -45,6 +46,10 @@ func (v *FlagVars) ReuseNetwork() bool { return v.reuseNetwork } +func (v *FlagVars) RestartNetwork() bool { + return v.restartNetwork +} + func (v *FlagVars) NetworkShutdownDelay() time.Duration { if v.delayNetworkShutdown { // Only return a non-zero value if the delay is enabled. Make sure this value takes @@ -92,6 +97,12 @@ func RegisterFlags() *FlagVars { false, "[optional] reuse an existing network. If an existing network is not already running, create a new one and leave it running for subsequent usage.", ) + flag.BoolVar( + &vars.restartNetwork, + "restart-network", + false, + "[optional] restarts an existing network. Useful for ensuring a network is running with the current state of binaries on disk. Ignored if a network is not already running or --stop-network is provided.", + ) flag.BoolVar( &vars.delayNetworkShutdown, "delay-network-shutdown", From ab504e9ad5b06f3dfa0b617d136a81b26ba10706 Mon Sep 17 00:00:00 2001 From: marun Date: Thu, 8 Aug 2024 10:19:02 -0700 Subject: [PATCH 03/69] Add StoppedTimer helper (#3280) Co-authored-by: Stephen Buttolph --- .../inbound_conn_upgrade_throttler.go | 7 +++--- .../throttling/inbound_resource_throttler.go | 8 +++---- tests/antithesis/avalanchego/main.go | 6 ++--- tests/antithesis/xsvm/main.go | 7 +++--- utils/timer/stopped_timer.go | 24 +++++++++++++++++++ 5 files changed, 35 insertions(+), 17 deletions(-) create mode 100644 utils/timer/stopped_timer.go diff --git a/network/throttling/inbound_conn_upgrade_throttler.go b/network/throttling/inbound_conn_upgrade_throttler.go index 4067d80b2b29..ace53a1fb34b 100644 --- a/network/throttling/inbound_conn_upgrade_throttler.go +++ b/network/throttling/inbound_conn_upgrade_throttler.go @@ -11,6 +11,8 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/timer/mockable" + + timerpkg "github.com/ava-labs/avalanchego/utils/timer" ) var ( @@ -131,10 +133,7 @@ func (n *inboundConnUpgradeThrottler) ShouldUpgrade(addrPort netip.AddrPort) boo } func (n *inboundConnUpgradeThrottler) Dispatch() { - timer := time.NewTimer(0) - if !timer.Stop() { - <-timer.C - } + timer := timerpkg.StoppedTimer() defer timer.Stop() for { diff --git a/network/throttling/inbound_resource_throttler.go b/network/throttling/inbound_resource_throttler.go index eb915e03232c..967af69a47d2 100644 --- a/network/throttling/inbound_resource_throttler.go +++ b/network/throttling/inbound_resource_throttler.go @@ -15,6 +15,8 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/networking/tracker" "github.com/ava-labs/avalanchego/utils/timer/mockable" + + timerpkg "github.com/ava-labs/avalanchego/utils/timer" ) const epsilon = time.Millisecond @@ -107,11 +109,7 @@ func NewSystemThrottler( timerPool: sync.Pool{ New: func() interface{} { // Satisfy invariant that timer is stopped and drained. - timer := time.NewTimer(0) - if !timer.Stop() { - <-timer.C - } - return timer + return timerpkg.StoppedTimer() }, }, }, nil diff --git a/tests/antithesis/avalanchego/main.go b/tests/antithesis/avalanchego/main.go index ae8f0bb051e8..7c68ed3fbd23 100644 --- a/tests/antithesis/avalanchego/main.go +++ b/tests/antithesis/avalanchego/main.go @@ -31,6 +31,7 @@ import ( "github.com/ava-labs/avalanchego/wallet/subnet/primary" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" + timerpkg "github.com/ava-labs/avalanchego/utils/timer" xtxs "github.com/ava-labs/avalanchego/vms/avm/txs" ptxs "github.com/ava-labs/avalanchego/vms/platformvm/txs" xbuilder "github.com/ava-labs/avalanchego/wallet/chain/x/builder" @@ -148,10 +149,7 @@ type workload struct { } func (w *workload) run(ctx context.Context) { - timer := time.NewTimer(0) - if !timer.Stop() { - <-timer.C - } + timer := timerpkg.StoppedTimer() var ( xWallet = w.wallet.X() diff --git a/tests/antithesis/xsvm/main.go b/tests/antithesis/xsvm/main.go index 9e70ebff1fbf..bb59f769127d 100644 --- a/tests/antithesis/xsvm/main.go +++ b/tests/antithesis/xsvm/main.go @@ -23,6 +23,8 @@ import ( "github.com/ava-labs/avalanchego/vms/example/xsvm/api" "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/issue/status" "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/issue/transfer" + + timerpkg "github.com/ava-labs/avalanchego/utils/timer" ) const ( @@ -118,10 +120,7 @@ type workload struct { } func (w *workload) run(ctx context.Context) { - timer := time.NewTimer(0) - if !timer.Stop() { - <-timer.C - } + timer := timerpkg.StoppedTimer() uri := w.uris[w.id%len(w.uris)] diff --git a/utils/timer/stopped_timer.go b/utils/timer/stopped_timer.go new file mode 100644 index 000000000000..1777c830e6e3 --- /dev/null +++ b/utils/timer/stopped_timer.go @@ -0,0 +1,24 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package timer + +import "time" + +// StoppedTimer returns a stopped timer so that there is no entry on +// the C channel (and there isn't one scheduled to be added). +// +// This means that after calling Reset there will be no events on the +// channel until the timer fires (at which point there will be exactly +// one event sent to the channel). +// +// It enables re-using the timer across loop iterations without +// needing to have the first loop iteration perform any == nil checks +// to initialize the first invocation. +func StoppedTimer() *time.Timer { + timer := time.NewTimer(0) + if !timer.Stop() { + <-timer.C + } + return timer +} From 9e67efe3cfe1ee4b92fbfaf05a8f166778d77c6d Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 8 Aug 2024 14:34:35 -0400 Subject: [PATCH 04/69] Fix race in timer stoppage (#3281) --- .../throttling/inbound_resource_throttler.go | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/network/throttling/inbound_resource_throttler.go b/network/throttling/inbound_resource_throttler.go index 967af69a47d2..ccc38e3bfef6 100644 --- a/network/throttling/inbound_resource_throttler.go +++ b/network/throttling/inbound_resource_throttler.go @@ -162,28 +162,21 @@ func (t *systemThrottler) Acquire(ctx context.Context, nodeID ids.NodeID) { waitDuration = t.MaxRecheckDelay } - // Reset [timer]. if timer == nil { // Note this is called at most once. t.metrics.awaitingAcquire.Inc() timer = t.timerPool.Get().(*time.Timer) - defer func() { - // Satisfy [t.timerPool] invariant. - if !timer.Stop() { - // The default ensures we don't wait forever in the case - // that the channel was already drained. - select { - case <-timer.C: - default: - } - } - t.timerPool.Put(timer) - }() + defer t.timerPool.Put(timer) } + timer.Reset(waitDuration) select { case <-ctx.Done(): + // Satisfy [t.timerPool] invariant. + if !timer.Stop() { + <-timer.C + } return case <-timer.C: } From 51969344065eacffe305550de69cca38b8ebf1f5 Mon Sep 17 00:00:00 2001 From: marun Date: Mon, 12 Aug 2024 10:27:42 -0700 Subject: [PATCH 05/69] [tmpnet] Add check for vm binaries to network and node start (#3273) --- tests/fixture/tmpnet/network.go | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/tests/fixture/tmpnet/network.go b/tests/fixture/tmpnet/network.go index 695017c0620c..61f738e3f30d 100644 --- a/tests/fixture/tmpnet/network.go +++ b/tests/fixture/tmpnet/network.go @@ -141,6 +141,9 @@ func BootstrapNewNetwork( if len(network.Nodes) == 0 { return errInsufficientNodes } + if err := checkVMBinariesExist(network.Subnets, pluginDir); err != nil { + return err + } if err := network.EnsureDefaultConfig(w, avalancheGoExecPath, pluginDir); err != nil { return err } @@ -284,7 +287,7 @@ func (n *Network) Create(rootDir string) error { n.Dir = canonicalDir // Ensure the existence of the plugin directory or nodes won't be able to start. - pluginDir, err := n.DefaultFlags.GetStringVal(config.PluginDirKey) + pluginDir, err := n.getPluginDir() if err != nil { return err } @@ -452,6 +455,16 @@ func (n *Network) Bootstrap(ctx context.Context, w io.Writer) error { // Starts the provided node after configuring it for the network. func (n *Network) StartNode(ctx context.Context, w io.Writer, node *Node) error { + // This check is duplicative for a network that is starting, but ensures + // that individual node start/restart won't fail due to missing binaries. + pluginDir, err := n.getPluginDir() + if err != nil { + return err + } + if err := checkVMBinariesExist(n.Subnets, pluginDir); err != nil { + return err + } + if err := n.EnsureNodeConfig(node); err != nil { return err } @@ -856,6 +869,10 @@ func (n *Network) GetNetworkID() uint32 { return n.NetworkID } +func (n *Network) getPluginDir() (string, error) { + return n.DefaultFlags.GetStringVal(config.PluginDirKey) +} + // Waits until the provided nodes are healthy. func waitForHealthy(ctx context.Context, w io.Writer, nodes []*Node) error { ticker := time.NewTicker(networkHealthCheckInterval) @@ -917,3 +934,16 @@ func GetReusableNetworkPathForOwner(owner string) (string, error) { } return filepath.Join(networkPath, "latest_"+owner), nil } + +func checkVMBinariesExist(subnets []*Subnet, pluginDir string) error { + errs := []error{} + for _, subnet := range subnets { + for _, chain := range subnet.Chains { + pluginPath := filepath.Join(pluginDir, chain.VMID.String()) + if _, err := os.Stat(pluginPath); err != nil { + errs = append(errs, fmt.Errorf("failed to check VM binary for subnet %q: %w", subnet.Name, err)) + } + } + } + return errors.Join(errs...) +} From b1816710a2fc7e194d6c712add5288407a1cff87 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Mon, 12 Aug 2024 13:39:19 -0400 Subject: [PATCH 06/69] Refactor P-chain Builder (#3282) --- snow/engine/snowman/engine_test.go | 18 +- utils/slice.go | 19 + wallet/chain/p/builder/builder.go | 564 ++++++++++++++++++------- wallet/chain/p/builder/builder_test.go | 172 ++++++++ 4 files changed, 593 insertions(+), 180 deletions(-) create mode 100644 utils/slice.go create mode 100644 wallet/chain/p/builder/builder_test.go diff --git a/snow/engine/snowman/engine_test.go b/snow/engine/snowman/engine_test.go index 2619dcc727b0..26eccf232ed1 100644 --- a/snow/engine/snowman/engine_test.go +++ b/snow/engine/snowman/engine_test.go @@ -28,6 +28,7 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/snowman/getter" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" ) @@ -3078,7 +3079,7 @@ func TestShouldIssueBlock(t *testing.T) { chain4Through6 = snowmantest.BuildDescendants(chain0Through3[0], 3) chain7Through10 = snowmantest.BuildDescendants(snowmantest.Genesis, 4) chain11Through11 = snowmantest.BuildDescendants(chain7Through10[1], 1) - blocks = join(chain0Through3, chain4Through6, chain7Through10, chain11Through11) + blocks = utils.Join(chain0Through3, chain4Through6, chain7Through10, chain11Through11) ) require.NoError(t, blocks[0].Accept(context.Background())) @@ -3181,18 +3182,3 @@ func TestShouldIssueBlock(t *testing.T) { }) } } - -// join the provided slices into a single slice. -// -// TODO: Use slices.Concat once the minimum go version is 1.22. -func join[T any](slices ...[]T) []T { - size := 0 - for _, s := range slices { - size += len(s) - } - newSlice := make([]T, 0, size) - for _, s := range slices { - newSlice = append(newSlice, s...) - } - return newSlice -} diff --git a/utils/slice.go b/utils/slice.go new file mode 100644 index 000000000000..c73fda241270 --- /dev/null +++ b/utils/slice.go @@ -0,0 +1,19 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package utils + +// Join merges the provided slices into a single slice. +// +// TODO: Use slices.Concat once the minimum go version is 1.22. +func Join[T any](slices ...[]T) []T { + size := 0 + for _, s := range slices { + size += len(s) + } + newSlice := make([]T, 0, size) + for _, s := range slices { + newSlice = append(newSlice, s...) + } + return newSlice +} diff --git a/wallet/chain/p/builder/builder.go b/wallet/chain/p/builder/builder.go index 97e7388a3a47..ee127ed71c22 100644 --- a/wallet/chain/p/builder/builder.go +++ b/wallet/chain/p/builder/builder.go @@ -15,6 +15,7 @@ import ( "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" @@ -324,7 +325,13 @@ func (b *builder) NewBaseTx( toStake := map[ids.ID]uint64{} ops := common.NewOptions(options) - inputs, changeOutputs, _, err := b.spend(toBurn, toStake, ops) + inputs, changeOutputs, _, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -355,7 +362,13 @@ func (b *builder) NewAddValidatorTx( avaxAssetID: vdr.Wght, } ops := common.NewOptions(options) - inputs, baseOutputs, stakeOutputs, err := b.spend(toBurn, toStake, ops) + inputs, baseOutputs, stakeOutputs, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -385,13 +398,20 @@ func (b *builder) NewAddSubnetValidatorTx( b.context.AVAXAssetID: b.context.StaticFeeConfig.AddSubnetValidatorFee, } toStake := map[ids.ID]uint64{} + ops := common.NewOptions(options) - inputs, outputs, _, err := b.spend(toBurn, toStake, ops) + subnetAuth, err := b.authorizeSubnet(vdr.Subnet, ops) if err != nil { return nil, err } - subnetAuth, err := b.authorizeSubnet(vdr.Subnet, ops) + inputs, outputs, _, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -419,13 +439,20 @@ func (b *builder) NewRemoveSubnetValidatorTx( b.context.AVAXAssetID: b.context.StaticFeeConfig.TxFee, } toStake := map[ids.ID]uint64{} + ops := common.NewOptions(options) - inputs, outputs, _, err := b.spend(toBurn, toStake, ops) + subnetAuth, err := b.authorizeSubnet(subnetID, ops) if err != nil { return nil, err } - subnetAuth, err := b.authorizeSubnet(subnetID, ops) + inputs, outputs, _, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -458,7 +485,13 @@ func (b *builder) NewAddDelegatorTx( avaxAssetID: vdr.Wght, } ops := common.NewOptions(options) - inputs, baseOutputs, stakeOutputs, err := b.spend(toBurn, toStake, ops) + inputs, baseOutputs, stakeOutputs, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -491,13 +524,20 @@ func (b *builder) NewCreateChainTx( b.context.AVAXAssetID: b.context.StaticFeeConfig.CreateBlockchainTxFee, } toStake := map[ids.ID]uint64{} + ops := common.NewOptions(options) - inputs, outputs, _, err := b.spend(toBurn, toStake, ops) + subnetAuth, err := b.authorizeSubnet(subnetID, ops) if err != nil { return nil, err } - subnetAuth, err := b.authorizeSubnet(subnetID, ops) + inputs, outputs, _, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -530,7 +570,13 @@ func (b *builder) NewCreateSubnetTx( } toStake := map[ids.ID]uint64{} ops := common.NewOptions(options) - inputs, outputs, _, err := b.spend(toBurn, toStake, ops) + inputs, outputs, _, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -558,13 +604,20 @@ func (b *builder) NewTransferSubnetOwnershipTx( b.context.AVAXAssetID: b.context.StaticFeeConfig.TxFee, } toStake := map[ids.ID]uint64{} + ops := common.NewOptions(options) - inputs, outputs, _, err := b.spend(toBurn, toStake, ops) + subnetAuth, err := b.authorizeSubnet(subnetID, ops) if err != nil { return nil, err } - subnetAuth, err := b.authorizeSubnet(subnetID, ops) + inputs, outputs, _, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -645,29 +698,12 @@ func (b *builder) NewImportTx( ) } - var ( - inputs []*avax.TransferableInput - outputs = make([]*avax.TransferableOutput, 0, len(importedAmounts)) - importedAVAX = importedAmounts[avaxAssetID] - ) - if importedAVAX > txFee { - importedAmounts[avaxAssetID] -= txFee - } else { - if importedAVAX < txFee { // imported amount goes toward paying tx fee - toBurn := map[ids.ID]uint64{ - avaxAssetID: txFee - importedAVAX, - } - toStake := map[ids.ID]uint64{} - var err error - inputs, outputs, _, err = b.spend(toBurn, toStake, ops) - if err != nil { - return nil, fmt.Errorf("couldn't generate tx inputs/outputs: %w", err) - } + outputs := make([]*avax.TransferableOutput, 0, len(importedAmounts)) + for assetID, amount := range importedAmounts { + if assetID == avaxAssetID { + continue } - delete(importedAmounts, avaxAssetID) - } - for assetID, amount := range importedAmounts { outputs = append(outputs, &avax.TransferableOutput{ Asset: avax.Asset{ID: assetID}, Out: &secp256k1fx.TransferOutput{ @@ -677,6 +713,29 @@ func (b *builder) NewImportTx( }) } + var ( + toBurn = map[ids.ID]uint64{} + toStake = map[ids.ID]uint64{} + excessAVAX uint64 + ) + if importedAVAX := importedAmounts[avaxAssetID]; importedAVAX < txFee { + toBurn[avaxAssetID] = txFee - importedAVAX + } else { + excessAVAX = importedAVAX - txFee + } + + inputs, changeOutputs, _, err := b.spend( + toBurn, + toStake, + excessAVAX, + to, + ops, + ) + if err != nil { + return nil, fmt.Errorf("couldn't generate tx inputs/outputs: %w", err) + } + outputs = append(outputs, changeOutputs...) + avax.SortTransferableOutputs(outputs, txs.Codec) // sort imported outputs tx := &txs.ImportTx{ BaseTx: txs.BaseTx{BaseTx: avax.BaseTx{ @@ -711,7 +770,13 @@ func (b *builder) NewExportTx( toStake := map[ids.ID]uint64{} ops := common.NewOptions(options) - inputs, changeOutputs, _, err := b.spend(toBurn, toStake, ops) + inputs, changeOutputs, _, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -753,13 +818,20 @@ func (b *builder) NewTransformSubnetTx( assetID: maxSupply - initialSupply, } toStake := map[ids.ID]uint64{} + ops := common.NewOptions(options) - inputs, outputs, _, err := b.spend(toBurn, toStake, ops) + subnetAuth, err := b.authorizeSubnet(subnetID, ops) if err != nil { return nil, err } - subnetAuth, err := b.authorizeSubnet(subnetID, ops) + inputs, outputs, _, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -811,7 +883,13 @@ func (b *builder) NewAddPermissionlessValidatorTx( assetID: vdr.Wght, } ops := common.NewOptions(options) - inputs, baseOutputs, stakeOutputs, err := b.spend(toBurn, toStake, ops) + inputs, baseOutputs, stakeOutputs, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -854,7 +932,13 @@ func (b *builder) NewAddPermissionlessDelegatorTx( assetID: vdr.Wght, } ops := common.NewOptions(options) - inputs, baseOutputs, stakeOutputs, err := b.spend(toBurn, toStake, ops) + inputs, baseOutputs, stakeOutputs, err := b.spend( + toBurn, + toStake, + 0, + nil, + ops, + ) if err != nil { return nil, err } @@ -926,18 +1010,25 @@ func (b *builder) getBalance( // spend takes in the requested burn amounts and the requested stake amounts. // -// - [amountsToBurn] maps assetID to the amount of the asset to spend without +// - [toBurn] maps assetID to the amount of the asset to spend without // producing an output. This is typically used for fees. However, it can // also be used to consume some of an asset that will be produced in // separate outputs, such as ExportedOutputs. Only unlocked UTXOs are able // to be burned here. -// - [amountsToStake] maps assetID to the amount of the asset to spend and -// place into the staked outputs. First locked UTXOs are attempted to be -// used for these funds, and then unlocked UTXOs will be attempted to be -// used. There is no preferential ordering on the unlock times. +// - [toStake] maps assetID to the amount of the asset to spend and place into +// the staked outputs. First locked UTXOs are attempted to be used for these +// funds, and then unlocked UTXOs will be attempted to be used. There is no +// preferential ordering on the unlock times. +// - [excessAVAX] contains the amount of extra AVAX that spend can produce in +// the change outputs in addition to the consumed and not burned AVAX. +// - [ownerOverride] optionally specifies the output owners to use for the +// unlocked AVAX change output if no additional AVAX was needed to be +// burned. If this value is nil, the default change owner is used. func (b *builder) spend( - amountsToBurn map[ids.ID]uint64, - amountsToStake map[ids.ID]uint64, + toBurn map[ids.ID]uint64, + toStake map[ids.ID]uint64, + excessAVAX uint64, + ownerOverride *secp256k1fx.OutputOwners, options *common.Options, ) ( inputs []*avax.TransferableInput, @@ -961,41 +1052,32 @@ func (b *builder) spend( Threshold: 1, Addrs: []ids.ShortID{addr}, }) + if ownerOverride == nil { + ownerOverride = changeOwner + } - // Initialize the return values with empty slices to preserve backward - // compatibility of the json representation of transactions with no - // inputs or outputs. - inputs = make([]*avax.TransferableInput, 0) - changeOutputs = make([]*avax.TransferableOutput, 0) - stakeOutputs = make([]*avax.TransferableOutput, 0) - - // Iterate over the locked UTXOs - for _, utxo := range utxos { - assetID := utxo.AssetID() - remainingAmountToStake := amountsToStake[assetID] + s := spendHelper{ + toBurn: toBurn, + toStake: toStake, - // If we have staked enough of the asset, then we have no need burn - // more. - if remainingAmountToStake == 0 { - continue - } + // Initialize the return values with empty slices to preserve backward + // compatibility of the json representation of transactions with no + // inputs or outputs. + inputs: make([]*avax.TransferableInput, 0), + changeOutputs: make([]*avax.TransferableOutput, 0), + stakeOutputs: make([]*avax.TransferableOutput, 0), + } - outIntf := utxo.Out - lockedOut, ok := outIntf.(*stakeable.LockOut) - if !ok { - // This output isn't locked, so it will be handled during the next - // iteration of the UTXO set - continue - } - if minIssuanceTime >= lockedOut.Locktime { - // This output isn't locked, so it will be handled during the next - // iteration of the UTXO set + utxosByLocktime := splitByLocktime(utxos, minIssuanceTime) + for _, utxo := range utxosByLocktime.locked { + assetID := utxo.AssetID() + if !s.shouldConsumeLockedAsset(assetID) { continue } - out, ok := lockedOut.TransferableOut.(*secp256k1fx.TransferOutput) - if !ok { - return nil, nil, nil, ErrUnknownOutputType + out, locktime, err := unwrapOutput(utxo.Out) + if err != nil { + return nil, nil, nil, err } inputSigIndices, ok := common.MatchOwners(&out.OutputOwners, addrs, minIssuanceTime) @@ -1004,11 +1086,11 @@ func (b *builder) spend( continue } - inputs = append(inputs, &avax.TransferableInput{ + s.addInput(&avax.TransferableInput{ UTXOID: utxo.UTXOID, Asset: utxo.Asset, In: &stakeable.LockIn{ - Locktime: lockedOut.Locktime, + Locktime: locktime, TransferableIn: &secp256k1fx.TransferInput{ Amt: out.Amt, Input: secp256k1fx.Input{ @@ -1018,46 +1100,42 @@ func (b *builder) spend( }, }) - // Stake any value that should be staked - amountToStake := min( - remainingAmountToStake, // Amount we still need to stake - out.Amt, // Amount available to stake - ) - - // Add the output to the staked outputs - stakeOutputs = append(stakeOutputs, &avax.TransferableOutput{ + excess := s.consumeLockedAsset(assetID, out.Amt) + s.addStakedOutput(&avax.TransferableOutput{ Asset: utxo.Asset, Out: &stakeable.LockOut{ - Locktime: lockedOut.Locktime, + Locktime: locktime, TransferableOut: &secp256k1fx.TransferOutput{ - Amt: amountToStake, + Amt: out.Amt - excess, OutputOwners: out.OutputOwners, }, }, }) - amountsToStake[assetID] -= amountToStake - if remainingAmount := out.Amt - amountToStake; remainingAmount > 0 { - // This input had extra value, so some of it must be returned - changeOutputs = append(changeOutputs, &avax.TransferableOutput{ - Asset: utxo.Asset, - Out: &stakeable.LockOut{ - Locktime: lockedOut.Locktime, - TransferableOut: &secp256k1fx.TransferOutput{ - Amt: remainingAmount, - OutputOwners: out.OutputOwners, - }, - }, - }) + if excess == 0 { + continue } + + // This input had extra value, so some of it must be returned + s.addChangeOutput(&avax.TransferableOutput{ + Asset: utxo.Asset, + Out: &stakeable.LockOut{ + Locktime: locktime, + TransferableOut: &secp256k1fx.TransferOutput{ + Amt: excess, + OutputOwners: out.OutputOwners, + }, + }, + }) } - for assetID, amount := range amountsToStake { + // Add all the remaining stake amounts assuming unlocked UTXOs. + for assetID, amount := range s.toStake { if amount == 0 { continue } - stakeOutputs = append(stakeOutputs, &avax.TransferableOutput{ + s.addStakedOutput(&avax.TransferableOutput{ Asset: avax.Asset{ ID: assetID, }, @@ -1068,31 +1146,61 @@ func (b *builder) spend( }) } - // Iterate over the unlocked UTXOs - for _, utxo := range utxos { + // AVAX is handled last to account for fees. + utxosByAVAXAssetID := splitByAssetID(utxosByLocktime.unlocked, b.context.AVAXAssetID) + for _, utxo := range utxosByAVAXAssetID.other { assetID := utxo.AssetID() - remainingAmountToStake := amountsToStake[assetID] - remainingAmountToBurn := amountsToBurn[assetID] - - // If we have consumed enough of the asset, then we have no need burn - // more. - if remainingAmountToStake == 0 && remainingAmountToBurn == 0 { + if !s.shouldConsumeAsset(assetID) { continue } - outIntf := utxo.Out - if lockedOut, ok := outIntf.(*stakeable.LockOut); ok { - if lockedOut.Locktime > minIssuanceTime { - // This output is currently locked, so this output can't be - // burned. - continue - } - outIntf = lockedOut.TransferableOut + out, _, err := unwrapOutput(utxo.Out) + if err != nil { + return nil, nil, nil, err } - out, ok := outIntf.(*secp256k1fx.TransferOutput) + inputSigIndices, ok := common.MatchOwners(&out.OutputOwners, addrs, minIssuanceTime) if !ok { - return nil, nil, nil, ErrUnknownOutputType + // We couldn't spend this UTXO, so we skip to the next one + continue + } + + s.addInput(&avax.TransferableInput{ + UTXOID: utxo.UTXOID, + Asset: utxo.Asset, + In: &secp256k1fx.TransferInput{ + Amt: out.Amt, + Input: secp256k1fx.Input{ + SigIndices: inputSigIndices, + }, + }, + }) + + excess := s.consumeAsset(assetID, out.Amt) + if excess == 0 { + continue + } + + // This input had extra value, so some of it must be returned + s.addChangeOutput(&avax.TransferableOutput{ + Asset: utxo.Asset, + Out: &secp256k1fx.TransferOutput{ + Amt: excess, + OutputOwners: *changeOwner, + }, + }) + } + + for _, utxo := range utxosByAVAXAssetID.requested { + // If we have consumed enough of the asset, then we have no need burn + // more. + if !s.shouldConsumeAsset(b.context.AVAXAssetID) { + break + } + + out, _, err := unwrapOutput(utxo.Out) + if err != nil { + return nil, nil, nil, err } inputSigIndices, ok := common.MatchOwners(&out.OutputOwners, addrs, minIssuanceTime) @@ -1101,7 +1209,7 @@ func (b *builder) spend( continue } - inputs = append(inputs, &avax.TransferableInput{ + s.addInput(&avax.TransferableInput{ UTXOID: utxo.UTXOID, Asset: utxo.Asset, In: &secp256k1fx.TransferInput{ @@ -1112,57 +1220,38 @@ func (b *builder) spend( }, }) - // Burn any value that should be burned - amountToBurn := min( - remainingAmountToBurn, // Amount we still need to burn - out.Amt, // Amount available to burn - ) - amountsToBurn[assetID] -= amountToBurn - - amountAvailableToStake := out.Amt - amountToBurn - // Burn any value that should be burned - amountToStake := min( - remainingAmountToStake, // Amount we still need to stake - amountAvailableToStake, // Amount available to stake - ) - amountsToStake[assetID] -= amountToStake - if remainingAmount := amountAvailableToStake - amountToStake; remainingAmount > 0 { - // This input had extra value, so some of it must be returned - changeOutputs = append(changeOutputs, &avax.TransferableOutput{ - Asset: utxo.Asset, - Out: &secp256k1fx.TransferOutput{ - Amt: remainingAmount, - OutputOwners: *changeOwner, - }, - }) + excess := s.consumeAsset(b.context.AVAXAssetID, out.Amt) + excessAVAX, err = math.Add(excessAVAX, excess) + if err != nil { + return nil, nil, nil, err } + + // If we need to consume additional AVAX, we should be returning the + // change to the change address. + ownerOverride = changeOwner } - for assetID, amount := range amountsToStake { - if amount != 0 { - return nil, nil, nil, fmt.Errorf( - "%w: provided UTXOs need %d more units of asset %q to stake", - ErrInsufficientFunds, - amount, - assetID, - ) - } + if err := s.verifyAssetsConsumed(); err != nil { + return nil, nil, nil, err } - for assetID, amount := range amountsToBurn { - if amount != 0 { - return nil, nil, nil, fmt.Errorf( - "%w: provided UTXOs need %d more units of asset %q", - ErrInsufficientFunds, - amount, - assetID, - ) + + if excessAVAX > 0 { + newOutput := &avax.TransferableOutput{ + Asset: avax.Asset{ + ID: b.context.AVAXAssetID, + }, + Out: &secp256k1fx.TransferOutput{ + Amt: excessAVAX, + OutputOwners: *ownerOverride, + }, } + s.changeOutputs = append(s.changeOutputs, newOutput) } - utils.Sort(inputs) // sort inputs - avax.SortTransferableOutputs(changeOutputs, txs.Codec) // sort the change outputs - avax.SortTransferableOutputs(stakeOutputs, txs.Codec) // sort stake outputs - return inputs, changeOutputs, stakeOutputs, nil + utils.Sort(s.inputs) // sort inputs + avax.SortTransferableOutputs(s.changeOutputs, txs.Codec) // sort the change outputs + avax.SortTransferableOutputs(s.stakeOutputs, txs.Codec) // sort stake outputs + return s.inputs, s.changeOutputs, s.stakeOutputs, nil } func (b *builder) authorizeSubnet(subnetID ids.ID, options *common.Options) (*secp256k1fx.Input, error) { @@ -1200,3 +1289,150 @@ func (b *builder) initCtx(tx txs.UnsignedTx) error { tx.InitCtx(ctx) return nil } + +type spendHelper struct { + toBurn map[ids.ID]uint64 + toStake map[ids.ID]uint64 + + inputs []*avax.TransferableInput + changeOutputs []*avax.TransferableOutput + stakeOutputs []*avax.TransferableOutput +} + +func (s *spendHelper) addInput(input *avax.TransferableInput) { + s.inputs = append(s.inputs, input) +} + +func (s *spendHelper) addChangeOutput(output *avax.TransferableOutput) { + s.changeOutputs = append(s.changeOutputs, output) +} + +func (s *spendHelper) addStakedOutput(output *avax.TransferableOutput) { + s.stakeOutputs = append(s.stakeOutputs, output) +} + +func (s *spendHelper) shouldConsumeLockedAsset(assetID ids.ID) bool { + return s.toStake[assetID] != 0 +} + +func (s *spendHelper) shouldConsumeAsset(assetID ids.ID) bool { + return s.toBurn[assetID] != 0 || s.shouldConsumeLockedAsset(assetID) +} + +func (s *spendHelper) consumeLockedAsset(assetID ids.ID, amount uint64) uint64 { + // Stake any value that should be staked + toStake := min( + s.toStake[assetID], // Amount we still need to stake + amount, // Amount available to stake + ) + s.toStake[assetID] -= toStake + return amount - toStake +} + +func (s *spendHelper) consumeAsset(assetID ids.ID, amount uint64) uint64 { + // Burn any value that should be burned + toBurn := min( + s.toBurn[assetID], // Amount we still need to burn + amount, // Amount available to burn + ) + s.toBurn[assetID] -= toBurn + + // Stake any remaining value that should be staked + return s.consumeLockedAsset(assetID, amount-toBurn) +} + +func (s *spendHelper) verifyAssetsConsumed() error { + for assetID, amount := range s.toStake { + if amount == 0 { + continue + } + + return fmt.Errorf( + "%w: provided UTXOs need %d more units of asset %q to stake", + ErrInsufficientFunds, + amount, + assetID, + ) + } + for assetID, amount := range s.toBurn { + if amount == 0 { + continue + } + + return fmt.Errorf( + "%w: provided UTXOs need %d more units of asset %q", + ErrInsufficientFunds, + amount, + assetID, + ) + } + return nil +} + +type utxosByLocktime struct { + unlocked []*avax.UTXO + locked []*avax.UTXO +} + +// splitByLocktime separates the provided UTXOs into two slices: +// 1. UTXOs that are unlocked with the provided issuance time +// 2. UTXOs that are locked with the provided issuance time +func splitByLocktime(utxos []*avax.UTXO, minIssuanceTime uint64) utxosByLocktime { + split := utxosByLocktime{ + unlocked: make([]*avax.UTXO, 0, len(utxos)), + locked: make([]*avax.UTXO, 0, len(utxos)), + } + for _, utxo := range utxos { + if lockedOut, ok := utxo.Out.(*stakeable.LockOut); ok && minIssuanceTime < lockedOut.Locktime { + split.locked = append(split.locked, utxo) + } else { + split.unlocked = append(split.unlocked, utxo) + } + } + return split +} + +type utxosByAssetID struct { + requested []*avax.UTXO + other []*avax.UTXO +} + +// splitByAssetID separates the provided UTXOs into two slices: +// 1. UTXOs with the provided assetID +// 2. UTXOs with a different assetID +func splitByAssetID(utxos []*avax.UTXO, assetID ids.ID) utxosByAssetID { + split := utxosByAssetID{ + requested: make([]*avax.UTXO, 0, len(utxos)), + other: make([]*avax.UTXO, 0, len(utxos)), + } + for _, utxo := range utxos { + if utxo.AssetID() == assetID { + split.requested = append(split.requested, utxo) + } else { + split.other = append(split.other, utxo) + } + } + return split +} + +// unwrapOutput returns the *secp256k1fx.TransferOutput that was, potentially, +// wrapped by a *stakeable.LockOut. +// +// If the output was stakeable and locked, the locktime is returned. Otherwise, +// the locktime returned will be 0. +// +// If the output is not a, potentially wrapped, *secp256k1fx.TransferOutput, an +// error is returned. +func unwrapOutput(output verify.State) (*secp256k1fx.TransferOutput, uint64, error) { + var locktime uint64 + if lockedOut, ok := output.(*stakeable.LockOut); ok { + output = lockedOut.TransferableOut + locktime = lockedOut.Locktime + } + + unwrappedOutput, ok := output.(*secp256k1fx.TransferOutput) + if !ok { + return nil, 0, ErrUnknownOutputType + } + return unwrappedOutput, locktime, nil +} diff --git a/wallet/chain/p/builder/builder_test.go b/wallet/chain/p/builder/builder_test.go new file mode 100644 index 000000000000..a6f82af81299 --- /dev/null +++ b/wallet/chain/p/builder/builder_test.go @@ -0,0 +1,172 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package builder + +import ( + "math/rand" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils" + "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/secp256k1fx" +) + +func generateUTXOs(random *rand.Rand, assetID ids.ID, locktime uint64) []*avax.UTXO { + utxos := make([]*avax.UTXO, random.Intn(10)) + for i := range utxos { + var output avax.TransferableOut = &secp256k1fx.TransferOutput{ + Amt: random.Uint64(), + OutputOwners: secp256k1fx.OutputOwners{ + Locktime: random.Uint64(), + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + }, + } + if locktime != 0 { + output = &stakeable.LockOut{ + Locktime: locktime, + TransferableOut: output, + } + } + utxos[i] = &avax.UTXO{ + UTXOID: avax.UTXOID{ + TxID: ids.GenerateTestID(), + OutputIndex: random.Uint32(), + }, + Asset: avax.Asset{ + ID: assetID, + }, + Out: output, + } + } + return utxos +} + +func TestSplitByLocktime(t *testing.T) { + seed := time.Now().UnixNano() + t.Logf("Seed: %d", seed) + random := rand.New(rand.NewSource(seed)) // #nosec G404 + + var ( + require = require.New(t) + + unlockedTime uint64 = 100 + expectedUnlocked = utils.Join( + generateUTXOs(random, ids.GenerateTestID(), 0), + generateUTXOs(random, ids.GenerateTestID(), unlockedTime-1), + generateUTXOs(random, ids.GenerateTestID(), unlockedTime), + ) + expectedLocked = utils.Join( + generateUTXOs(random, ids.GenerateTestID(), unlockedTime+100), + generateUTXOs(random, ids.GenerateTestID(), unlockedTime+1), + ) + utxos = utils.Join( + expectedUnlocked, + expectedLocked, + ) + ) + random.Shuffle(len(utxos), func(i, j int) { + utxos[i], utxos[j] = utxos[j], utxos[i] + }) + + utxosByLocktime := splitByLocktime(utxos, unlockedTime) + require.ElementsMatch(expectedUnlocked, utxosByLocktime.unlocked) + require.ElementsMatch(expectedLocked, utxosByLocktime.locked) +} + +func TestByAssetID(t *testing.T) { + seed := time.Now().UnixNano() + t.Logf("Seed: %d", seed) + random := rand.New(rand.NewSource(seed)) // #nosec G404 + + var ( + require = require.New(t) + + assetID = ids.GenerateTestID() + expectedRequested = generateUTXOs(random, assetID, random.Uint64()) + expectedOther = generateUTXOs(random, ids.GenerateTestID(), random.Uint64()) + utxos = utils.Join( + expectedRequested, + expectedOther, + ) + ) + random.Shuffle(len(utxos), func(i, j int) { + utxos[i], utxos[j] = utxos[j], utxos[i] + }) + + utxosByAssetID := splitByAssetID(utxos, assetID) + require.ElementsMatch(expectedRequested, utxosByAssetID.requested) + require.ElementsMatch(expectedOther, utxosByAssetID.other) +} + +func TestUnwrapOutput(t *testing.T) { + normalOutput := &secp256k1fx.TransferOutput{ + Amt: 123, + OutputOwners: secp256k1fx.OutputOwners{ + Locktime: 456, + Threshold: 1, + Addrs: []ids.ShortID{ids.ShortEmpty}, + }, + } + + tests := []struct { + name string + output verify.State + expectedOutput *secp256k1fx.TransferOutput + expectedLocktime uint64 + expectedErr error + }{ + { + name: "normal output", + output: normalOutput, + expectedOutput: normalOutput, + expectedLocktime: 0, + expectedErr: nil, + }, + { + name: "locked output", + output: &stakeable.LockOut{ + Locktime: 789, + TransferableOut: normalOutput, + }, + expectedOutput: normalOutput, + expectedLocktime: 789, + expectedErr: nil, + }, + { + name: "locked output with no locktime", + output: &stakeable.LockOut{ + Locktime: 0, + TransferableOut: normalOutput, + }, + expectedOutput: normalOutput, + expectedLocktime: 0, + expectedErr: nil, + }, + { + name: "invalid output", + output: nil, + expectedOutput: nil, + expectedLocktime: 0, + expectedErr: ErrUnknownOutputType, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + output, locktime, err := unwrapOutput(test.output) + require.ErrorIs(err, test.expectedErr) + require.Equal(test.expectedOutput, output) + require.Equal(test.expectedLocktime, locktime) + }) + } +} From a303bd7f7a5d2d2ea33936423247f409afbd2a00 Mon Sep 17 00:00:00 2001 From: drawdrop Date: Tue, 13 Aug 2024 07:00:50 +0800 Subject: [PATCH 07/69] chore: fix some comments (#3289) --- proto/p2p/p2p.proto | 2 +- proto/pb/p2p/p2p.pb.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/proto/p2p/p2p.proto b/proto/p2p/p2p.proto index 53c0c84de303..221a037f524f 100644 --- a/proto/p2p/p2p.proto +++ b/proto/p2p/p2p.proto @@ -193,7 +193,7 @@ message StateSummaryFrontier { // GetAcceptedStateSummary requests a set of state summaries at a set of // block heights message GetAcceptedStateSummary { - // Chain bein requested from + // Chain being requested from bytes chain_id = 1; // Unique identifier for this request uint32 request_id = 2; diff --git a/proto/pb/p2p/p2p.pb.go b/proto/pb/p2p/p2p.pb.go index bd55ad703546..5ca017be18bf 100644 --- a/proto/pb/p2p/p2p.pb.go +++ b/proto/pb/p2p/p2p.pb.go @@ -1272,7 +1272,7 @@ type GetAcceptedStateSummary struct { sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields - // Chain bein requested from + // Chain being requested from ChainId []byte `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` // Unique identifier for this request RequestId uint32 `protobuf:"varint,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` From d729e5c7ef9f008c3e89cd7131148ad3acda2e34 Mon Sep 17 00:00:00 2001 From: aaronbuchwald Date: Mon, 12 Aug 2024 20:26:18 -0400 Subject: [PATCH 08/69] Update write path of tmpnet subnet config (#3290) --- tests/fixture/tmpnet/subnet.go | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/tests/fixture/tmpnet/subnet.go b/tests/fixture/tmpnet/subnet.go index cbff01585e20..bb48c5260e21 100644 --- a/tests/fixture/tmpnet/subnet.go +++ b/tests/fixture/tmpnet/subnet.go @@ -10,6 +10,7 @@ import ( "io" "os" "path/filepath" + "strings" "time" "github.com/ava-labs/avalanchego/ids" @@ -25,7 +26,10 @@ import ( "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) -const defaultSubnetDirName = "subnets" +const ( + defaultSubnetDirName = "subnets" + jsonFileSuffix = ".json" +) type Chain struct { // Set statically @@ -209,7 +213,7 @@ func (s *Subnet) Write(subnetDir string, chainDir string) error { if err := os.MkdirAll(subnetDir, perms.ReadWriteExecute); err != nil { return fmt.Errorf("failed to create subnet dir: %w", err) } - tmpnetConfigPath := filepath.Join(subnetDir, s.Name+".json") + tmpnetConfigPath := filepath.Join(subnetDir, s.Name+jsonFileSuffix) // Since subnets are expected to be serialized for the first time // without their chains having been created (i.e. chains will have @@ -249,13 +253,8 @@ func (s *Subnet) Write(subnetDir string, chainDir string) error { return fmt.Errorf("failed to marshal avalanchego subnet config %s: %w", s.Name, err) } - avgoConfigDir := filepath.Join(subnetDir, s.SubnetID.String()) - if err := os.MkdirAll(avgoConfigDir, perms.ReadWriteExecute); err != nil { - return fmt.Errorf("failed to create avalanchego subnet config dir: %w", err) - } - - avgoConfigPath := filepath.Join(avgoConfigDir, defaultConfigFilename) - if err := os.WriteFile(avgoConfigPath, bytes, perms.ReadWrite); err != nil { + subnetConfigPath := filepath.Join(subnetDir, s.SubnetID.String()+jsonFileSuffix) + if err := os.WriteFile(subnetConfigPath, bytes, perms.ReadWrite); err != nil { return fmt.Errorf("failed to write avalanchego subnet config %s: %w", s.Name, err) } } @@ -351,12 +350,19 @@ func readSubnets(subnetDir string) ([]*Subnet, error) { // Looking only for files continue } - if filepath.Ext(entry.Name()) != ".json" { + fileName := entry.Name() + if filepath.Ext(fileName) != jsonFileSuffix { // Subnet files should have a .json extension continue } + fileNameWithoutSuffix := strings.TrimSuffix(fileName, jsonFileSuffix) + // Skip actual subnet config files, which are named [subnetID].json + if _, err := ids.FromString(fileNameWithoutSuffix); err == nil { + // Skip files that are named by their SubnetID + continue + } - subnetPath := filepath.Join(subnetDir, entry.Name()) + subnetPath := filepath.Join(subnetDir, fileName) bytes, err := os.ReadFile(subnetPath) if err != nil { return nil, fmt.Errorf("failed to read subnet file %s: %w", subnetPath, err) From 6cbc66926a394032a4e4afa4957884e635323857 Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Tue, 13 Aug 2024 19:28:56 +0300 Subject: [PATCH 09/69] add network upgrades to chain ctx (#3283) --- chains/manager.go | 11 +- proto/pb/vm/vm.pb.go | 1701 ++++++++++++++++++++--------------- proto/vm/vm.proto | 19 + snow/context.go | 12 +- snow/snowtest/context.go | 12 +- vms/rpcchainvm/vm_client.go | 46 +- vms/rpcchainvm/vm_server.go | 96 +- 7 files changed, 1140 insertions(+), 757 deletions(-) diff --git a/chains/manager.go b/chains/manager.go index 0b6ae14bd6b1..2fdd3c0b73f9 100644 --- a/chains/manager.go +++ b/chains/manager.go @@ -505,11 +505,12 @@ func (m *manager) buildChain(chainParams ChainParameters, sb subnets.Subnet) (*c ctx := &snow.ConsensusContext{ Context: &snow.Context{ - NetworkID: m.NetworkID, - SubnetID: chainParams.SubnetID, - ChainID: chainParams.ID, - NodeID: m.NodeID, - PublicKey: bls.PublicFromSecretKey(m.StakingBLSKey), + NetworkID: m.NetworkID, + SubnetID: chainParams.SubnetID, + ChainID: chainParams.ID, + NodeID: m.NodeID, + PublicKey: bls.PublicFromSecretKey(m.StakingBLSKey), + NetworkUpgrades: m.Upgrades, XChainID: m.XChainID, CChainID: m.CChainID, diff --git a/proto/pb/vm/vm.pb.go b/proto/pb/vm/vm.pb.go index 60d5f15d44fc..829b6fba5144 100644 --- a/proto/pb/vm/vm.pb.go +++ b/proto/pb/vm/vm.pb.go @@ -177,7 +177,7 @@ func (x StateSummaryAcceptResponse_Mode) Number() protoreflect.EnumNumber { // Deprecated: Use StateSummaryAcceptResponse_Mode.Descriptor instead. func (StateSummaryAcceptResponse_Mode) EnumDescriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{43, 0} + return file_vm_vm_proto_rawDescGZIP(), []int{44, 0} } type InitializeRequest struct { @@ -204,6 +204,8 @@ type InitializeRequest struct { // the messenger, keystore, shared memory, blockchain alias, // subnet alias, and appSender services ServerAddr string `protobuf:"bytes,14,opt,name=server_addr,json=serverAddr,proto3" json:"server_addr,omitempty"` + // network_upgrades_bytes is the json encoded network upgrades + NetworkUpgrades *NetworkUpgrades `protobuf:"bytes,15,opt,name=network_upgrades,json=networkUpgrades,proto3" json:"network_upgrades,omitempty"` } func (x *InitializeRequest) Reset() { @@ -336,6 +338,164 @@ func (x *InitializeRequest) GetServerAddr() string { return "" } +func (x *InitializeRequest) GetNetworkUpgrades() *NetworkUpgrades { + if x != nil { + return x.NetworkUpgrades + } + return nil +} + +type NetworkUpgrades struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ApricotPhase_1Time *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=apricot_phase_1_time,json=apricotPhase1Time,proto3" json:"apricot_phase_1_time,omitempty"` + ApricotPhase_2Time *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=apricot_phase_2_time,json=apricotPhase2Time,proto3" json:"apricot_phase_2_time,omitempty"` + ApricotPhase_3Time *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=apricot_phase_3_time,json=apricotPhase3Time,proto3" json:"apricot_phase_3_time,omitempty"` + ApricotPhase_4Time *timestamppb.Timestamp `protobuf:"bytes,4,opt,name=apricot_phase_4_time,json=apricotPhase4Time,proto3" json:"apricot_phase_4_time,omitempty"` + ApricotPhase_4MinPChainHeight uint64 `protobuf:"varint,5,opt,name=apricot_phase_4_min_p_chain_height,json=apricotPhase4MinPChainHeight,proto3" json:"apricot_phase_4_min_p_chain_height,omitempty"` + ApricotPhase_5Time *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=apricot_phase_5_time,json=apricotPhase5Time,proto3" json:"apricot_phase_5_time,omitempty"` + ApricotPhasePre_6Time *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=apricot_phase_pre_6_time,json=apricotPhasePre6Time,proto3" json:"apricot_phase_pre_6_time,omitempty"` + ApricotPhase_6Time *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=apricot_phase_6_time,json=apricotPhase6Time,proto3" json:"apricot_phase_6_time,omitempty"` + ApricotPhasePost_6Time *timestamppb.Timestamp `protobuf:"bytes,9,opt,name=apricot_phase_post_6_time,json=apricotPhasePost6Time,proto3" json:"apricot_phase_post_6_time,omitempty"` + BanffTime *timestamppb.Timestamp `protobuf:"bytes,10,opt,name=banff_time,json=banffTime,proto3" json:"banff_time,omitempty"` + CortinaTime *timestamppb.Timestamp `protobuf:"bytes,11,opt,name=cortina_time,json=cortinaTime,proto3" json:"cortina_time,omitempty"` + CortinaXChainStopVertexId []byte `protobuf:"bytes,12,opt,name=cortina_x_chain_stop_vertex_id,json=cortinaXChainStopVertexId,proto3" json:"cortina_x_chain_stop_vertex_id,omitempty"` + DurangoTime *timestamppb.Timestamp `protobuf:"bytes,13,opt,name=durango_time,json=durangoTime,proto3" json:"durango_time,omitempty"` + EtnaTime *timestamppb.Timestamp `protobuf:"bytes,14,opt,name=etna_time,json=etnaTime,proto3" json:"etna_time,omitempty"` +} + +func (x *NetworkUpgrades) Reset() { + *x = NetworkUpgrades{} + if protoimpl.UnsafeEnabled { + mi := &file_vm_vm_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *NetworkUpgrades) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*NetworkUpgrades) ProtoMessage() {} + +func (x *NetworkUpgrades) ProtoReflect() protoreflect.Message { + mi := &file_vm_vm_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use NetworkUpgrades.ProtoReflect.Descriptor instead. +func (*NetworkUpgrades) Descriptor() ([]byte, []int) { + return file_vm_vm_proto_rawDescGZIP(), []int{1} +} + +func (x *NetworkUpgrades) GetApricotPhase_1Time() *timestamppb.Timestamp { + if x != nil { + return x.ApricotPhase_1Time + } + return nil +} + +func (x *NetworkUpgrades) GetApricotPhase_2Time() *timestamppb.Timestamp { + if x != nil { + return x.ApricotPhase_2Time + } + return nil +} + +func (x *NetworkUpgrades) GetApricotPhase_3Time() *timestamppb.Timestamp { + if x != nil { + return x.ApricotPhase_3Time + } + return nil +} + +func (x *NetworkUpgrades) GetApricotPhase_4Time() *timestamppb.Timestamp { + if x != nil { + return x.ApricotPhase_4Time + } + return nil +} + +func (x *NetworkUpgrades) GetApricotPhase_4MinPChainHeight() uint64 { + if x != nil { + return x.ApricotPhase_4MinPChainHeight + } + return 0 +} + +func (x *NetworkUpgrades) GetApricotPhase_5Time() *timestamppb.Timestamp { + if x != nil { + return x.ApricotPhase_5Time + } + return nil +} + +func (x *NetworkUpgrades) GetApricotPhasePre_6Time() *timestamppb.Timestamp { + if x != nil { + return x.ApricotPhasePre_6Time + } + return nil +} + +func (x *NetworkUpgrades) GetApricotPhase_6Time() *timestamppb.Timestamp { + if x != nil { + return x.ApricotPhase_6Time + } + return nil +} + +func (x *NetworkUpgrades) GetApricotPhasePost_6Time() *timestamppb.Timestamp { + if x != nil { + return x.ApricotPhasePost_6Time + } + return nil +} + +func (x *NetworkUpgrades) GetBanffTime() *timestamppb.Timestamp { + if x != nil { + return x.BanffTime + } + return nil +} + +func (x *NetworkUpgrades) GetCortinaTime() *timestamppb.Timestamp { + if x != nil { + return x.CortinaTime + } + return nil +} + +func (x *NetworkUpgrades) GetCortinaXChainStopVertexId() []byte { + if x != nil { + return x.CortinaXChainStopVertexId + } + return nil +} + +func (x *NetworkUpgrades) GetDurangoTime() *timestamppb.Timestamp { + if x != nil { + return x.DurangoTime + } + return nil +} + +func (x *NetworkUpgrades) GetEtnaTime() *timestamppb.Timestamp { + if x != nil { + return x.EtnaTime + } + return nil +} + type InitializeResponse struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -351,7 +511,7 @@ type InitializeResponse struct { func (x *InitializeResponse) Reset() { *x = InitializeResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[1] + mi := &file_vm_vm_proto_msgTypes[2] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -364,7 +524,7 @@ func (x *InitializeResponse) String() string { func (*InitializeResponse) ProtoMessage() {} func (x *InitializeResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[1] + mi := &file_vm_vm_proto_msgTypes[2] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -377,7 +537,7 @@ func (x *InitializeResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use InitializeResponse.ProtoReflect.Descriptor instead. func (*InitializeResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{1} + return file_vm_vm_proto_rawDescGZIP(), []int{2} } func (x *InitializeResponse) GetLastAcceptedId() []byte { @@ -426,7 +586,7 @@ type SetStateRequest struct { func (x *SetStateRequest) Reset() { *x = SetStateRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[2] + mi := &file_vm_vm_proto_msgTypes[3] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -439,7 +599,7 @@ func (x *SetStateRequest) String() string { func (*SetStateRequest) ProtoMessage() {} func (x *SetStateRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[2] + mi := &file_vm_vm_proto_msgTypes[3] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -452,7 +612,7 @@ func (x *SetStateRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SetStateRequest.ProtoReflect.Descriptor instead. func (*SetStateRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{2} + return file_vm_vm_proto_rawDescGZIP(), []int{3} } func (x *SetStateRequest) GetState() State { @@ -477,7 +637,7 @@ type SetStateResponse struct { func (x *SetStateResponse) Reset() { *x = SetStateResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[3] + mi := &file_vm_vm_proto_msgTypes[4] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -490,7 +650,7 @@ func (x *SetStateResponse) String() string { func (*SetStateResponse) ProtoMessage() {} func (x *SetStateResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[3] + mi := &file_vm_vm_proto_msgTypes[4] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -503,7 +663,7 @@ func (x *SetStateResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SetStateResponse.ProtoReflect.Descriptor instead. func (*SetStateResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{3} + return file_vm_vm_proto_rawDescGZIP(), []int{4} } func (x *SetStateResponse) GetLastAcceptedId() []byte { @@ -552,7 +712,7 @@ type CreateHandlersResponse struct { func (x *CreateHandlersResponse) Reset() { *x = CreateHandlersResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[4] + mi := &file_vm_vm_proto_msgTypes[5] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -565,7 +725,7 @@ func (x *CreateHandlersResponse) String() string { func (*CreateHandlersResponse) ProtoMessage() {} func (x *CreateHandlersResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[4] + mi := &file_vm_vm_proto_msgTypes[5] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -578,7 +738,7 @@ func (x *CreateHandlersResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateHandlersResponse.ProtoReflect.Descriptor instead. func (*CreateHandlersResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{4} + return file_vm_vm_proto_rawDescGZIP(), []int{5} } func (x *CreateHandlersResponse) GetHandlers() []*Handler { @@ -602,7 +762,7 @@ type Handler struct { func (x *Handler) Reset() { *x = Handler{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[5] + mi := &file_vm_vm_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -615,7 +775,7 @@ func (x *Handler) String() string { func (*Handler) ProtoMessage() {} func (x *Handler) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[5] + mi := &file_vm_vm_proto_msgTypes[6] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -628,7 +788,7 @@ func (x *Handler) ProtoReflect() protoreflect.Message { // Deprecated: Use Handler.ProtoReflect.Descriptor instead. func (*Handler) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{5} + return file_vm_vm_proto_rawDescGZIP(), []int{6} } func (x *Handler) GetPrefix() string { @@ -656,7 +816,7 @@ type BuildBlockRequest struct { func (x *BuildBlockRequest) Reset() { *x = BuildBlockRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[6] + mi := &file_vm_vm_proto_msgTypes[7] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -669,7 +829,7 @@ func (x *BuildBlockRequest) String() string { func (*BuildBlockRequest) ProtoMessage() {} func (x *BuildBlockRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[6] + mi := &file_vm_vm_proto_msgTypes[7] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -682,7 +842,7 @@ func (x *BuildBlockRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BuildBlockRequest.ProtoReflect.Descriptor instead. func (*BuildBlockRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{6} + return file_vm_vm_proto_rawDescGZIP(), []int{7} } func (x *BuildBlockRequest) GetPChainHeight() uint64 { @@ -709,7 +869,7 @@ type BuildBlockResponse struct { func (x *BuildBlockResponse) Reset() { *x = BuildBlockResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[7] + mi := &file_vm_vm_proto_msgTypes[8] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -722,7 +882,7 @@ func (x *BuildBlockResponse) String() string { func (*BuildBlockResponse) ProtoMessage() {} func (x *BuildBlockResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[7] + mi := &file_vm_vm_proto_msgTypes[8] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -735,7 +895,7 @@ func (x *BuildBlockResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BuildBlockResponse.ProtoReflect.Descriptor instead. func (*BuildBlockResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{7} + return file_vm_vm_proto_rawDescGZIP(), []int{8} } func (x *BuildBlockResponse) GetId() []byte { @@ -791,7 +951,7 @@ type ParseBlockRequest struct { func (x *ParseBlockRequest) Reset() { *x = ParseBlockRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[8] + mi := &file_vm_vm_proto_msgTypes[9] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -804,7 +964,7 @@ func (x *ParseBlockRequest) String() string { func (*ParseBlockRequest) ProtoMessage() {} func (x *ParseBlockRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[8] + mi := &file_vm_vm_proto_msgTypes[9] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -817,7 +977,7 @@ func (x *ParseBlockRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ParseBlockRequest.ProtoReflect.Descriptor instead. func (*ParseBlockRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{8} + return file_vm_vm_proto_rawDescGZIP(), []int{9} } func (x *ParseBlockRequest) GetBytes() []byte { @@ -842,7 +1002,7 @@ type ParseBlockResponse struct { func (x *ParseBlockResponse) Reset() { *x = ParseBlockResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[9] + mi := &file_vm_vm_proto_msgTypes[10] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -855,7 +1015,7 @@ func (x *ParseBlockResponse) String() string { func (*ParseBlockResponse) ProtoMessage() {} func (x *ParseBlockResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[9] + mi := &file_vm_vm_proto_msgTypes[10] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -868,7 +1028,7 @@ func (x *ParseBlockResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ParseBlockResponse.ProtoReflect.Descriptor instead. func (*ParseBlockResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{9} + return file_vm_vm_proto_rawDescGZIP(), []int{10} } func (x *ParseBlockResponse) GetId() []byte { @@ -917,7 +1077,7 @@ type GetBlockRequest struct { func (x *GetBlockRequest) Reset() { *x = GetBlockRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[10] + mi := &file_vm_vm_proto_msgTypes[11] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -930,7 +1090,7 @@ func (x *GetBlockRequest) String() string { func (*GetBlockRequest) ProtoMessage() {} func (x *GetBlockRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[10] + mi := &file_vm_vm_proto_msgTypes[11] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -943,7 +1103,7 @@ func (x *GetBlockRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetBlockRequest.ProtoReflect.Descriptor instead. func (*GetBlockRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{10} + return file_vm_vm_proto_rawDescGZIP(), []int{11} } func (x *GetBlockRequest) GetId() []byte { @@ -970,7 +1130,7 @@ type GetBlockResponse struct { func (x *GetBlockResponse) Reset() { *x = GetBlockResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[11] + mi := &file_vm_vm_proto_msgTypes[12] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -983,7 +1143,7 @@ func (x *GetBlockResponse) String() string { func (*GetBlockResponse) ProtoMessage() {} func (x *GetBlockResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[11] + mi := &file_vm_vm_proto_msgTypes[12] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -996,7 +1156,7 @@ func (x *GetBlockResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetBlockResponse.ProtoReflect.Descriptor instead. func (*GetBlockResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{11} + return file_vm_vm_proto_rawDescGZIP(), []int{12} } func (x *GetBlockResponse) GetParentId() []byte { @@ -1052,7 +1212,7 @@ type SetPreferenceRequest struct { func (x *SetPreferenceRequest) Reset() { *x = SetPreferenceRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[12] + mi := &file_vm_vm_proto_msgTypes[13] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1065,7 +1225,7 @@ func (x *SetPreferenceRequest) String() string { func (*SetPreferenceRequest) ProtoMessage() {} func (x *SetPreferenceRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[12] + mi := &file_vm_vm_proto_msgTypes[13] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1078,7 +1238,7 @@ func (x *SetPreferenceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SetPreferenceRequest.ProtoReflect.Descriptor instead. func (*SetPreferenceRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{12} + return file_vm_vm_proto_rawDescGZIP(), []int{13} } func (x *SetPreferenceRequest) GetId() []byte { @@ -1102,7 +1262,7 @@ type BlockVerifyRequest struct { func (x *BlockVerifyRequest) Reset() { *x = BlockVerifyRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[13] + mi := &file_vm_vm_proto_msgTypes[14] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1115,7 +1275,7 @@ func (x *BlockVerifyRequest) String() string { func (*BlockVerifyRequest) ProtoMessage() {} func (x *BlockVerifyRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[13] + mi := &file_vm_vm_proto_msgTypes[14] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1128,7 +1288,7 @@ func (x *BlockVerifyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BlockVerifyRequest.ProtoReflect.Descriptor instead. func (*BlockVerifyRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{13} + return file_vm_vm_proto_rawDescGZIP(), []int{14} } func (x *BlockVerifyRequest) GetBytes() []byte { @@ -1156,7 +1316,7 @@ type BlockVerifyResponse struct { func (x *BlockVerifyResponse) Reset() { *x = BlockVerifyResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[14] + mi := &file_vm_vm_proto_msgTypes[15] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1169,7 +1329,7 @@ func (x *BlockVerifyResponse) String() string { func (*BlockVerifyResponse) ProtoMessage() {} func (x *BlockVerifyResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[14] + mi := &file_vm_vm_proto_msgTypes[15] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1182,7 +1342,7 @@ func (x *BlockVerifyResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BlockVerifyResponse.ProtoReflect.Descriptor instead. func (*BlockVerifyResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{14} + return file_vm_vm_proto_rawDescGZIP(), []int{15} } func (x *BlockVerifyResponse) GetTimestamp() *timestamppb.Timestamp { @@ -1203,7 +1363,7 @@ type BlockAcceptRequest struct { func (x *BlockAcceptRequest) Reset() { *x = BlockAcceptRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[15] + mi := &file_vm_vm_proto_msgTypes[16] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1216,7 +1376,7 @@ func (x *BlockAcceptRequest) String() string { func (*BlockAcceptRequest) ProtoMessage() {} func (x *BlockAcceptRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[15] + mi := &file_vm_vm_proto_msgTypes[16] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1229,7 +1389,7 @@ func (x *BlockAcceptRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BlockAcceptRequest.ProtoReflect.Descriptor instead. func (*BlockAcceptRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{15} + return file_vm_vm_proto_rawDescGZIP(), []int{16} } func (x *BlockAcceptRequest) GetId() []byte { @@ -1250,7 +1410,7 @@ type BlockRejectRequest struct { func (x *BlockRejectRequest) Reset() { *x = BlockRejectRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[16] + mi := &file_vm_vm_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1263,7 +1423,7 @@ func (x *BlockRejectRequest) String() string { func (*BlockRejectRequest) ProtoMessage() {} func (x *BlockRejectRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[16] + mi := &file_vm_vm_proto_msgTypes[17] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1276,7 +1436,7 @@ func (x *BlockRejectRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BlockRejectRequest.ProtoReflect.Descriptor instead. func (*BlockRejectRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{16} + return file_vm_vm_proto_rawDescGZIP(), []int{17} } func (x *BlockRejectRequest) GetId() []byte { @@ -1297,7 +1457,7 @@ type HealthResponse struct { func (x *HealthResponse) Reset() { *x = HealthResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[17] + mi := &file_vm_vm_proto_msgTypes[18] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1310,7 +1470,7 @@ func (x *HealthResponse) String() string { func (*HealthResponse) ProtoMessage() {} func (x *HealthResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[17] + mi := &file_vm_vm_proto_msgTypes[18] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1323,7 +1483,7 @@ func (x *HealthResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use HealthResponse.ProtoReflect.Descriptor instead. func (*HealthResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{17} + return file_vm_vm_proto_rawDescGZIP(), []int{18} } func (x *HealthResponse) GetDetails() []byte { @@ -1344,7 +1504,7 @@ type VersionResponse struct { func (x *VersionResponse) Reset() { *x = VersionResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[18] + mi := &file_vm_vm_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1357,7 +1517,7 @@ func (x *VersionResponse) String() string { func (*VersionResponse) ProtoMessage() {} func (x *VersionResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[18] + mi := &file_vm_vm_proto_msgTypes[19] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1370,7 +1530,7 @@ func (x *VersionResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use VersionResponse.ProtoReflect.Descriptor instead. func (*VersionResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{18} + return file_vm_vm_proto_rawDescGZIP(), []int{19} } func (x *VersionResponse) GetVersion() string { @@ -1398,7 +1558,7 @@ type AppRequestMsg struct { func (x *AppRequestMsg) Reset() { *x = AppRequestMsg{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[19] + mi := &file_vm_vm_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1411,7 +1571,7 @@ func (x *AppRequestMsg) String() string { func (*AppRequestMsg) ProtoMessage() {} func (x *AppRequestMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[19] + mi := &file_vm_vm_proto_msgTypes[20] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1424,7 +1584,7 @@ func (x *AppRequestMsg) ProtoReflect() protoreflect.Message { // Deprecated: Use AppRequestMsg.ProtoReflect.Descriptor instead. func (*AppRequestMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{19} + return file_vm_vm_proto_rawDescGZIP(), []int{20} } func (x *AppRequestMsg) GetNodeId() []byte { @@ -1473,7 +1633,7 @@ type AppRequestFailedMsg struct { func (x *AppRequestFailedMsg) Reset() { *x = AppRequestFailedMsg{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[20] + mi := &file_vm_vm_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1486,7 +1646,7 @@ func (x *AppRequestFailedMsg) String() string { func (*AppRequestFailedMsg) ProtoMessage() {} func (x *AppRequestFailedMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[20] + mi := &file_vm_vm_proto_msgTypes[21] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1499,7 +1659,7 @@ func (x *AppRequestFailedMsg) ProtoReflect() protoreflect.Message { // Deprecated: Use AppRequestFailedMsg.ProtoReflect.Descriptor instead. func (*AppRequestFailedMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{20} + return file_vm_vm_proto_rawDescGZIP(), []int{21} } func (x *AppRequestFailedMsg) GetNodeId() []byte { @@ -1546,7 +1706,7 @@ type AppResponseMsg struct { func (x *AppResponseMsg) Reset() { *x = AppResponseMsg{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[21] + mi := &file_vm_vm_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1559,7 +1719,7 @@ func (x *AppResponseMsg) String() string { func (*AppResponseMsg) ProtoMessage() {} func (x *AppResponseMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[21] + mi := &file_vm_vm_proto_msgTypes[22] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1572,7 +1732,7 @@ func (x *AppResponseMsg) ProtoReflect() protoreflect.Message { // Deprecated: Use AppResponseMsg.ProtoReflect.Descriptor instead. func (*AppResponseMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{21} + return file_vm_vm_proto_rawDescGZIP(), []int{22} } func (x *AppResponseMsg) GetNodeId() []byte { @@ -1610,7 +1770,7 @@ type AppGossipMsg struct { func (x *AppGossipMsg) Reset() { *x = AppGossipMsg{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[22] + mi := &file_vm_vm_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1623,7 +1783,7 @@ func (x *AppGossipMsg) String() string { func (*AppGossipMsg) ProtoMessage() {} func (x *AppGossipMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[22] + mi := &file_vm_vm_proto_msgTypes[23] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1636,7 +1796,7 @@ func (x *AppGossipMsg) ProtoReflect() protoreflect.Message { // Deprecated: Use AppGossipMsg.ProtoReflect.Descriptor instead. func (*AppGossipMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{22} + return file_vm_vm_proto_rawDescGZIP(), []int{23} } func (x *AppGossipMsg) GetNodeId() []byte { @@ -1671,7 +1831,7 @@ type CrossChainAppRequestMsg struct { func (x *CrossChainAppRequestMsg) Reset() { *x = CrossChainAppRequestMsg{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[23] + mi := &file_vm_vm_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1684,7 +1844,7 @@ func (x *CrossChainAppRequestMsg) String() string { func (*CrossChainAppRequestMsg) ProtoMessage() {} func (x *CrossChainAppRequestMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[23] + mi := &file_vm_vm_proto_msgTypes[24] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1697,7 +1857,7 @@ func (x *CrossChainAppRequestMsg) ProtoReflect() protoreflect.Message { // Deprecated: Use CrossChainAppRequestMsg.ProtoReflect.Descriptor instead. func (*CrossChainAppRequestMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{23} + return file_vm_vm_proto_rawDescGZIP(), []int{24} } func (x *CrossChainAppRequestMsg) GetChainId() []byte { @@ -1746,7 +1906,7 @@ type CrossChainAppRequestFailedMsg struct { func (x *CrossChainAppRequestFailedMsg) Reset() { *x = CrossChainAppRequestFailedMsg{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[24] + mi := &file_vm_vm_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1759,7 +1919,7 @@ func (x *CrossChainAppRequestFailedMsg) String() string { func (*CrossChainAppRequestFailedMsg) ProtoMessage() {} func (x *CrossChainAppRequestFailedMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[24] + mi := &file_vm_vm_proto_msgTypes[25] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1772,7 +1932,7 @@ func (x *CrossChainAppRequestFailedMsg) ProtoReflect() protoreflect.Message { // Deprecated: Use CrossChainAppRequestFailedMsg.ProtoReflect.Descriptor instead. func (*CrossChainAppRequestFailedMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{24} + return file_vm_vm_proto_rawDescGZIP(), []int{25} } func (x *CrossChainAppRequestFailedMsg) GetChainId() []byte { @@ -1819,7 +1979,7 @@ type CrossChainAppResponseMsg struct { func (x *CrossChainAppResponseMsg) Reset() { *x = CrossChainAppResponseMsg{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[25] + mi := &file_vm_vm_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1832,7 +1992,7 @@ func (x *CrossChainAppResponseMsg) String() string { func (*CrossChainAppResponseMsg) ProtoMessage() {} func (x *CrossChainAppResponseMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[25] + mi := &file_vm_vm_proto_msgTypes[26] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1845,7 +2005,7 @@ func (x *CrossChainAppResponseMsg) ProtoReflect() protoreflect.Message { // Deprecated: Use CrossChainAppResponseMsg.ProtoReflect.Descriptor instead. func (*CrossChainAppResponseMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{25} + return file_vm_vm_proto_rawDescGZIP(), []int{26} } func (x *CrossChainAppResponseMsg) GetChainId() []byte { @@ -1886,7 +2046,7 @@ type ConnectedRequest struct { func (x *ConnectedRequest) Reset() { *x = ConnectedRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[26] + mi := &file_vm_vm_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1899,7 +2059,7 @@ func (x *ConnectedRequest) String() string { func (*ConnectedRequest) ProtoMessage() {} func (x *ConnectedRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[26] + mi := &file_vm_vm_proto_msgTypes[27] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1912,7 +2072,7 @@ func (x *ConnectedRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ConnectedRequest.ProtoReflect.Descriptor instead. func (*ConnectedRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{26} + return file_vm_vm_proto_rawDescGZIP(), []int{27} } func (x *ConnectedRequest) GetNodeId() []byte { @@ -1961,7 +2121,7 @@ type DisconnectedRequest struct { func (x *DisconnectedRequest) Reset() { *x = DisconnectedRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[27] + mi := &file_vm_vm_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1974,7 +2134,7 @@ func (x *DisconnectedRequest) String() string { func (*DisconnectedRequest) ProtoMessage() {} func (x *DisconnectedRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[27] + mi := &file_vm_vm_proto_msgTypes[28] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1987,7 +2147,7 @@ func (x *DisconnectedRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DisconnectedRequest.ProtoReflect.Descriptor instead. func (*DisconnectedRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{27} + return file_vm_vm_proto_rawDescGZIP(), []int{28} } func (x *DisconnectedRequest) GetNodeId() []byte { @@ -2011,7 +2171,7 @@ type GetAncestorsRequest struct { func (x *GetAncestorsRequest) Reset() { *x = GetAncestorsRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[28] + mi := &file_vm_vm_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2024,7 +2184,7 @@ func (x *GetAncestorsRequest) String() string { func (*GetAncestorsRequest) ProtoMessage() {} func (x *GetAncestorsRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[28] + mi := &file_vm_vm_proto_msgTypes[29] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2037,7 +2197,7 @@ func (x *GetAncestorsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetAncestorsRequest.ProtoReflect.Descriptor instead. func (*GetAncestorsRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{28} + return file_vm_vm_proto_rawDescGZIP(), []int{29} } func (x *GetAncestorsRequest) GetBlkId() []byte { @@ -2079,7 +2239,7 @@ type GetAncestorsResponse struct { func (x *GetAncestorsResponse) Reset() { *x = GetAncestorsResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[29] + mi := &file_vm_vm_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2092,7 +2252,7 @@ func (x *GetAncestorsResponse) String() string { func (*GetAncestorsResponse) ProtoMessage() {} func (x *GetAncestorsResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[29] + mi := &file_vm_vm_proto_msgTypes[30] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2105,7 +2265,7 @@ func (x *GetAncestorsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetAncestorsResponse.ProtoReflect.Descriptor instead. func (*GetAncestorsResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{29} + return file_vm_vm_proto_rawDescGZIP(), []int{30} } func (x *GetAncestorsResponse) GetBlksBytes() [][]byte { @@ -2126,7 +2286,7 @@ type BatchedParseBlockRequest struct { func (x *BatchedParseBlockRequest) Reset() { *x = BatchedParseBlockRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[30] + mi := &file_vm_vm_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2139,7 +2299,7 @@ func (x *BatchedParseBlockRequest) String() string { func (*BatchedParseBlockRequest) ProtoMessage() {} func (x *BatchedParseBlockRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[30] + mi := &file_vm_vm_proto_msgTypes[31] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2152,7 +2312,7 @@ func (x *BatchedParseBlockRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BatchedParseBlockRequest.ProtoReflect.Descriptor instead. func (*BatchedParseBlockRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{30} + return file_vm_vm_proto_rawDescGZIP(), []int{31} } func (x *BatchedParseBlockRequest) GetRequest() [][]byte { @@ -2173,7 +2333,7 @@ type BatchedParseBlockResponse struct { func (x *BatchedParseBlockResponse) Reset() { *x = BatchedParseBlockResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[31] + mi := &file_vm_vm_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2186,7 +2346,7 @@ func (x *BatchedParseBlockResponse) String() string { func (*BatchedParseBlockResponse) ProtoMessage() {} func (x *BatchedParseBlockResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[31] + mi := &file_vm_vm_proto_msgTypes[32] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2199,7 +2359,7 @@ func (x *BatchedParseBlockResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BatchedParseBlockResponse.ProtoReflect.Descriptor instead. func (*BatchedParseBlockResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{31} + return file_vm_vm_proto_rawDescGZIP(), []int{32} } func (x *BatchedParseBlockResponse) GetResponse() []*ParseBlockResponse { @@ -2220,7 +2380,7 @@ type GetBlockIDAtHeightRequest struct { func (x *GetBlockIDAtHeightRequest) Reset() { *x = GetBlockIDAtHeightRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[32] + mi := &file_vm_vm_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2233,7 +2393,7 @@ func (x *GetBlockIDAtHeightRequest) String() string { func (*GetBlockIDAtHeightRequest) ProtoMessage() {} func (x *GetBlockIDAtHeightRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[32] + mi := &file_vm_vm_proto_msgTypes[33] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2246,7 +2406,7 @@ func (x *GetBlockIDAtHeightRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetBlockIDAtHeightRequest.ProtoReflect.Descriptor instead. func (*GetBlockIDAtHeightRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{32} + return file_vm_vm_proto_rawDescGZIP(), []int{33} } func (x *GetBlockIDAtHeightRequest) GetHeight() uint64 { @@ -2268,7 +2428,7 @@ type GetBlockIDAtHeightResponse struct { func (x *GetBlockIDAtHeightResponse) Reset() { *x = GetBlockIDAtHeightResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[33] + mi := &file_vm_vm_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2281,7 +2441,7 @@ func (x *GetBlockIDAtHeightResponse) String() string { func (*GetBlockIDAtHeightResponse) ProtoMessage() {} func (x *GetBlockIDAtHeightResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[33] + mi := &file_vm_vm_proto_msgTypes[34] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2294,7 +2454,7 @@ func (x *GetBlockIDAtHeightResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetBlockIDAtHeightResponse.ProtoReflect.Descriptor instead. func (*GetBlockIDAtHeightResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{33} + return file_vm_vm_proto_rawDescGZIP(), []int{34} } func (x *GetBlockIDAtHeightResponse) GetBlkId() []byte { @@ -2322,7 +2482,7 @@ type GatherResponse struct { func (x *GatherResponse) Reset() { *x = GatherResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[34] + mi := &file_vm_vm_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2335,7 +2495,7 @@ func (x *GatherResponse) String() string { func (*GatherResponse) ProtoMessage() {} func (x *GatherResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[34] + mi := &file_vm_vm_proto_msgTypes[35] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2348,7 +2508,7 @@ func (x *GatherResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GatherResponse.ProtoReflect.Descriptor instead. func (*GatherResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{34} + return file_vm_vm_proto_rawDescGZIP(), []int{35} } func (x *GatherResponse) GetMetricFamilies() []*_go.MetricFamily { @@ -2370,7 +2530,7 @@ type StateSyncEnabledResponse struct { func (x *StateSyncEnabledResponse) Reset() { *x = StateSyncEnabledResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[35] + mi := &file_vm_vm_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2383,7 +2543,7 @@ func (x *StateSyncEnabledResponse) String() string { func (*StateSyncEnabledResponse) ProtoMessage() {} func (x *StateSyncEnabledResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[35] + mi := &file_vm_vm_proto_msgTypes[36] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2396,7 +2556,7 @@ func (x *StateSyncEnabledResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use StateSyncEnabledResponse.ProtoReflect.Descriptor instead. func (*StateSyncEnabledResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{35} + return file_vm_vm_proto_rawDescGZIP(), []int{36} } func (x *StateSyncEnabledResponse) GetEnabled() bool { @@ -2427,7 +2587,7 @@ type GetOngoingSyncStateSummaryResponse struct { func (x *GetOngoingSyncStateSummaryResponse) Reset() { *x = GetOngoingSyncStateSummaryResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[36] + mi := &file_vm_vm_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2440,7 +2600,7 @@ func (x *GetOngoingSyncStateSummaryResponse) String() string { func (*GetOngoingSyncStateSummaryResponse) ProtoMessage() {} func (x *GetOngoingSyncStateSummaryResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[36] + mi := &file_vm_vm_proto_msgTypes[37] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2453,7 +2613,7 @@ func (x *GetOngoingSyncStateSummaryResponse) ProtoReflect() protoreflect.Message // Deprecated: Use GetOngoingSyncStateSummaryResponse.ProtoReflect.Descriptor instead. func (*GetOngoingSyncStateSummaryResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{36} + return file_vm_vm_proto_rawDescGZIP(), []int{37} } func (x *GetOngoingSyncStateSummaryResponse) GetId() []byte { @@ -2498,7 +2658,7 @@ type GetLastStateSummaryResponse struct { func (x *GetLastStateSummaryResponse) Reset() { *x = GetLastStateSummaryResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[37] + mi := &file_vm_vm_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2511,7 +2671,7 @@ func (x *GetLastStateSummaryResponse) String() string { func (*GetLastStateSummaryResponse) ProtoMessage() {} func (x *GetLastStateSummaryResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[37] + mi := &file_vm_vm_proto_msgTypes[38] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2524,7 +2684,7 @@ func (x *GetLastStateSummaryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetLastStateSummaryResponse.ProtoReflect.Descriptor instead. func (*GetLastStateSummaryResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{37} + return file_vm_vm_proto_rawDescGZIP(), []int{38} } func (x *GetLastStateSummaryResponse) GetId() []byte { @@ -2566,7 +2726,7 @@ type ParseStateSummaryRequest struct { func (x *ParseStateSummaryRequest) Reset() { *x = ParseStateSummaryRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[38] + mi := &file_vm_vm_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2579,7 +2739,7 @@ func (x *ParseStateSummaryRequest) String() string { func (*ParseStateSummaryRequest) ProtoMessage() {} func (x *ParseStateSummaryRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[38] + mi := &file_vm_vm_proto_msgTypes[39] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2592,7 +2752,7 @@ func (x *ParseStateSummaryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ParseStateSummaryRequest.ProtoReflect.Descriptor instead. func (*ParseStateSummaryRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{38} + return file_vm_vm_proto_rawDescGZIP(), []int{39} } func (x *ParseStateSummaryRequest) GetBytes() []byte { @@ -2615,7 +2775,7 @@ type ParseStateSummaryResponse struct { func (x *ParseStateSummaryResponse) Reset() { *x = ParseStateSummaryResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[39] + mi := &file_vm_vm_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2628,7 +2788,7 @@ func (x *ParseStateSummaryResponse) String() string { func (*ParseStateSummaryResponse) ProtoMessage() {} func (x *ParseStateSummaryResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[39] + mi := &file_vm_vm_proto_msgTypes[40] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2641,7 +2801,7 @@ func (x *ParseStateSummaryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ParseStateSummaryResponse.ProtoReflect.Descriptor instead. func (*ParseStateSummaryResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{39} + return file_vm_vm_proto_rawDescGZIP(), []int{40} } func (x *ParseStateSummaryResponse) GetId() []byte { @@ -2676,7 +2836,7 @@ type GetStateSummaryRequest struct { func (x *GetStateSummaryRequest) Reset() { *x = GetStateSummaryRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[40] + mi := &file_vm_vm_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2689,7 +2849,7 @@ func (x *GetStateSummaryRequest) String() string { func (*GetStateSummaryRequest) ProtoMessage() {} func (x *GetStateSummaryRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[40] + mi := &file_vm_vm_proto_msgTypes[41] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2702,7 +2862,7 @@ func (x *GetStateSummaryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetStateSummaryRequest.ProtoReflect.Descriptor instead. func (*GetStateSummaryRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{40} + return file_vm_vm_proto_rawDescGZIP(), []int{41} } func (x *GetStateSummaryRequest) GetHeight() uint64 { @@ -2725,7 +2885,7 @@ type GetStateSummaryResponse struct { func (x *GetStateSummaryResponse) Reset() { *x = GetStateSummaryResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[41] + mi := &file_vm_vm_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2738,7 +2898,7 @@ func (x *GetStateSummaryResponse) String() string { func (*GetStateSummaryResponse) ProtoMessage() {} func (x *GetStateSummaryResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[41] + mi := &file_vm_vm_proto_msgTypes[42] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2751,7 +2911,7 @@ func (x *GetStateSummaryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetStateSummaryResponse.ProtoReflect.Descriptor instead. func (*GetStateSummaryResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{41} + return file_vm_vm_proto_rawDescGZIP(), []int{42} } func (x *GetStateSummaryResponse) GetId() []byte { @@ -2786,7 +2946,7 @@ type StateSummaryAcceptRequest struct { func (x *StateSummaryAcceptRequest) Reset() { *x = StateSummaryAcceptRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[42] + mi := &file_vm_vm_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2799,7 +2959,7 @@ func (x *StateSummaryAcceptRequest) String() string { func (*StateSummaryAcceptRequest) ProtoMessage() {} func (x *StateSummaryAcceptRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[42] + mi := &file_vm_vm_proto_msgTypes[43] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2812,7 +2972,7 @@ func (x *StateSummaryAcceptRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use StateSummaryAcceptRequest.ProtoReflect.Descriptor instead. func (*StateSummaryAcceptRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{42} + return file_vm_vm_proto_rawDescGZIP(), []int{43} } func (x *StateSummaryAcceptRequest) GetBytes() []byte { @@ -2834,7 +2994,7 @@ type StateSummaryAcceptResponse struct { func (x *StateSummaryAcceptResponse) Reset() { *x = StateSummaryAcceptResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[43] + mi := &file_vm_vm_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2847,7 +3007,7 @@ func (x *StateSummaryAcceptResponse) String() string { func (*StateSummaryAcceptResponse) ProtoMessage() {} func (x *StateSummaryAcceptResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[43] + mi := &file_vm_vm_proto_msgTypes[44] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2860,7 +3020,7 @@ func (x *StateSummaryAcceptResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use StateSummaryAcceptResponse.ProtoReflect.Descriptor instead. func (*StateSummaryAcceptResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{43} + return file_vm_vm_proto_rawDescGZIP(), []int{44} } func (x *StateSummaryAcceptResponse) GetMode() StateSummaryAcceptResponse_Mode { @@ -2887,7 +3047,7 @@ var file_vm_vm_proto_rawDesc = []byte{ 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x22, 0x69, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2f, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x73, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x22, 0xdc, 0x03, 0x0a, 0x11, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, + 0x6f, 0x74, 0x6f, 0x22, 0x9c, 0x04, 0x0a, 0x11, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1d, 0x0a, 0x0a, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x73, 0x75, 0x62, 0x6e, @@ -2917,435 +3077,504 @@ var file_vm_vm_proto_rawDesc = []byte{ 0x01, 0x28, 0x09, 0x52, 0x0c, 0x64, 0x62, 0x53, 0x65, 0x72, 0x76, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x41, 0x64, - 0x64, 0x72, 0x22, 0xdd, 0x01, 0x0a, 0x12, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, - 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x10, 0x6c, 0x61, 0x73, - 0x74, 0x5f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, - 0x64, 0x49, 0x64, 0x12, 0x35, 0x0a, 0x17, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x61, 0x63, 0x63, 0x65, - 0x70, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x14, 0x6c, 0x61, 0x73, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, - 0x65, 0x64, 0x50, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, - 0x69, 0x67, 0x68, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, - 0x68, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, - 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, - 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, + 0x64, 0x72, 0x12, 0x3e, 0x0a, 0x10, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x75, 0x70, + 0x67, 0x72, 0x61, 0x64, 0x65, 0x73, 0x18, 0x0f, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e, 0x76, + 0x6d, 0x2e, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x55, 0x70, 0x67, 0x72, 0x61, 0x64, 0x65, + 0x73, 0x52, 0x0f, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x55, 0x70, 0x67, 0x72, 0x61, 0x64, + 0x65, 0x73, 0x22, 0x88, 0x08, 0x0a, 0x0f, 0x4e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x55, 0x70, + 0x67, 0x72, 0x61, 0x64, 0x65, 0x73, 0x12, 0x4b, 0x0a, 0x14, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, + 0x74, 0x5f, 0x70, 0x68, 0x61, 0x73, 0x65, 0x5f, 0x31, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, + 0x52, 0x11, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x50, 0x68, 0x61, 0x73, 0x65, 0x31, 0x54, + 0x69, 0x6d, 0x65, 0x12, 0x4b, 0x0a, 0x14, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x5f, 0x70, + 0x68, 0x61, 0x73, 0x65, 0x5f, 0x32, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x11, 0x61, + 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x50, 0x68, 0x61, 0x73, 0x65, 0x32, 0x54, 0x69, 0x6d, 0x65, + 0x12, 0x4b, 0x0a, 0x14, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x5f, 0x70, 0x68, 0x61, 0x73, + 0x65, 0x5f, 0x33, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x11, 0x61, 0x70, 0x72, 0x69, + 0x63, 0x6f, 0x74, 0x50, 0x68, 0x61, 0x73, 0x65, 0x33, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x4b, 0x0a, + 0x14, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x5f, 0x70, 0x68, 0x61, 0x73, 0x65, 0x5f, 0x34, + 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, - 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, - 0x6d, 0x70, 0x22, 0x32, 0x0a, 0x0f, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1f, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, - 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x22, 0xdb, 0x01, 0x0a, 0x10, 0x53, 0x65, 0x74, 0x53, 0x74, - 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x10, 0x6c, - 0x61, 0x73, 0x74, 0x5f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x5f, 0x69, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, - 0x74, 0x65, 0x64, 0x49, 0x64, 0x12, 0x35, 0x0a, 0x17, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x61, 0x63, - 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x14, 0x6c, 0x61, 0x73, 0x74, 0x41, 0x63, 0x63, 0x65, - 0x70, 0x74, 0x65, 0x64, 0x50, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, - 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, - 0x69, 0x67, 0x68, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, - 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, - 0x74, 0x61, 0x6d, 0x70, 0x22, 0x41, 0x0a, 0x16, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, 0x61, - 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x27, - 0x0a, 0x08, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, - 0x32, 0x0b, 0x2e, 0x76, 0x6d, 0x2e, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x52, 0x08, 0x68, - 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x22, 0x42, 0x0a, 0x07, 0x48, 0x61, 0x6e, 0x64, 0x6c, - 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x06, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x65, - 0x72, 0x76, 0x65, 0x72, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x0a, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x22, 0x51, 0x0a, 0x11, 0x42, - 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x12, 0x29, 0x0a, 0x0e, 0x70, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, - 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x48, 0x00, 0x52, 0x0c, 0x70, 0x43, 0x68, 0x61, - 0x69, 0x6e, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x88, 0x01, 0x01, 0x42, 0x11, 0x0a, 0x0f, 0x5f, - 0x70, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0xd9, - 0x01, 0x0a, 0x12, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, - 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, - 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, - 0x68, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, - 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x05, 0x20, + 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x11, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, + 0x50, 0x68, 0x61, 0x73, 0x65, 0x34, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x48, 0x0a, 0x22, 0x61, 0x70, + 0x72, 0x69, 0x63, 0x6f, 0x74, 0x5f, 0x70, 0x68, 0x61, 0x73, 0x65, 0x5f, 0x34, 0x5f, 0x6d, 0x69, + 0x6e, 0x5f, 0x70, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x04, 0x52, 0x1c, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x50, + 0x68, 0x61, 0x73, 0x65, 0x34, 0x4d, 0x69, 0x6e, 0x50, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x48, 0x65, + 0x69, 0x67, 0x68, 0x74, 0x12, 0x4b, 0x0a, 0x14, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x5f, + 0x70, 0x68, 0x61, 0x73, 0x65, 0x5f, 0x35, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, + 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x11, + 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x50, 0x68, 0x61, 0x73, 0x65, 0x35, 0x54, 0x69, 0x6d, + 0x65, 0x12, 0x52, 0x0a, 0x18, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x5f, 0x70, 0x68, 0x61, + 0x73, 0x65, 0x5f, 0x70, 0x72, 0x65, 0x5f, 0x36, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x07, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, + 0x14, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x50, 0x68, 0x61, 0x73, 0x65, 0x50, 0x72, 0x65, + 0x36, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x4b, 0x0a, 0x14, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, + 0x5f, 0x70, 0x68, 0x61, 0x73, 0x65, 0x5f, 0x36, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x08, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, - 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x2e, 0x0a, 0x13, 0x76, 0x65, - 0x72, 0x69, 0x66, 0x79, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, - 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, 0x57, - 0x69, 0x74, 0x68, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x22, 0x29, 0x0a, 0x11, 0x50, 0x61, - 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, - 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, - 0x62, 0x79, 0x74, 0x65, 0x73, 0x22, 0xc3, 0x01, 0x0a, 0x12, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, - 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, - 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x1b, 0x0a, 0x09, + 0x11, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x50, 0x68, 0x61, 0x73, 0x65, 0x36, 0x54, 0x69, + 0x6d, 0x65, 0x12, 0x54, 0x0a, 0x19, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x5f, 0x70, 0x68, + 0x61, 0x73, 0x65, 0x5f, 0x70, 0x6f, 0x73, 0x74, 0x5f, 0x36, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, + 0x09, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, + 0x70, 0x52, 0x15, 0x61, 0x70, 0x72, 0x69, 0x63, 0x6f, 0x74, 0x50, 0x68, 0x61, 0x73, 0x65, 0x50, + 0x6f, 0x73, 0x74, 0x36, 0x54, 0x69, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x0a, 0x62, 0x61, 0x6e, 0x66, + 0x66, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0a, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x62, 0x61, 0x6e, 0x66, 0x66, 0x54, + 0x69, 0x6d, 0x65, 0x12, 0x3d, 0x0a, 0x0c, 0x63, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x61, 0x5f, 0x74, + 0x69, 0x6d, 0x65, 0x18, 0x0b, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0b, 0x63, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x61, 0x54, 0x69, + 0x6d, 0x65, 0x12, 0x41, 0x0a, 0x1e, 0x63, 0x6f, 0x72, 0x74, 0x69, 0x6e, 0x61, 0x5f, 0x78, 0x5f, + 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x73, 0x74, 0x6f, 0x70, 0x5f, 0x76, 0x65, 0x72, 0x74, 0x65, + 0x78, 0x5f, 0x69, 0x64, 0x18, 0x0c, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x19, 0x63, 0x6f, 0x72, 0x74, + 0x69, 0x6e, 0x61, 0x58, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x53, 0x74, 0x6f, 0x70, 0x56, 0x65, 0x72, + 0x74, 0x65, 0x78, 0x49, 0x64, 0x12, 0x3d, 0x0a, 0x0c, 0x64, 0x75, 0x72, 0x61, 0x6e, 0x67, 0x6f, + 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x0d, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, + 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x0b, 0x64, 0x75, 0x72, 0x61, 0x6e, 0x67, 0x6f, + 0x54, 0x69, 0x6d, 0x65, 0x12, 0x37, 0x0a, 0x09, 0x65, 0x74, 0x6e, 0x61, 0x5f, 0x74, 0x69, 0x6d, + 0x65, 0x18, 0x0e, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, + 0x61, 0x6d, 0x70, 0x52, 0x08, 0x65, 0x74, 0x6e, 0x61, 0x54, 0x69, 0x6d, 0x65, 0x22, 0xdd, 0x01, + 0x0a, 0x12, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x61, 0x63, 0x63, + 0x65, 0x70, 0x74, 0x65, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0e, + 0x6c, 0x61, 0x73, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x49, 0x64, 0x12, 0x35, + 0x0a, 0x17, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x08, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, - 0x67, 0x68, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, - 0x74, 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x05, + 0x14, 0x6c, 0x61, 0x73, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x50, 0x61, 0x72, + 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x14, 0x0a, + 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, + 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, + 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x22, 0x32, 0x0a, + 0x0f, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x1f, 0x0a, 0x05, 0x73, 0x74, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, + 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x05, 0x73, 0x74, 0x61, 0x74, + 0x65, 0x22, 0xdb, 0x01, 0x0a, 0x10, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x28, 0x0a, 0x10, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x61, + 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, + 0x52, 0x0e, 0x6c, 0x61, 0x73, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x49, 0x64, + 0x12, 0x35, 0x0a, 0x17, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, + 0x64, 0x5f, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0c, 0x52, 0x14, 0x6c, 0x61, 0x73, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x50, + 0x61, 0x72, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, + 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, + 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, + 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, + 0x6d, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, + 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x22, + 0x41, 0x0a, 0x16, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, + 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x27, 0x0a, 0x08, 0x68, 0x61, 0x6e, + 0x64, 0x6c, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x76, 0x6d, + 0x2e, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x52, 0x08, 0x68, 0x61, 0x6e, 0x64, 0x6c, 0x65, + 0x72, 0x73, 0x22, 0x42, 0x0a, 0x07, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x12, 0x16, 0x0a, + 0x06, 0x70, 0x72, 0x65, 0x66, 0x69, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x70, + 0x72, 0x65, 0x66, 0x69, 0x78, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x5f, + 0x61, 0x64, 0x64, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x73, 0x65, 0x72, 0x76, + 0x65, 0x72, 0x41, 0x64, 0x64, 0x72, 0x22, 0x51, 0x0a, 0x11, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x42, + 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x29, 0x0a, 0x0e, 0x70, + 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x04, 0x48, 0x00, 0x52, 0x0c, 0x70, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x48, 0x65, 0x69, + 0x67, 0x68, 0x74, 0x88, 0x01, 0x01, 0x42, 0x11, 0x0a, 0x0f, 0x5f, 0x70, 0x5f, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0xd9, 0x01, 0x0a, 0x12, 0x42, 0x75, + 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x0c, 0x52, 0x08, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x14, 0x0a, + 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, + 0x74, 0x65, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x38, 0x0a, 0x09, 0x74, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, + 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x2e, 0x0a, 0x13, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, 0x5f, + 0x77, 0x69, 0x74, 0x68, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x18, 0x06, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x11, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, 0x57, 0x69, 0x74, 0x68, 0x43, 0x6f, + 0x6e, 0x74, 0x65, 0x78, 0x74, 0x22, 0x29, 0x0a, 0x11, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, + 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, + 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, + 0x22, 0xc3, 0x01, 0x0a, 0x12, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x72, 0x65, 0x6e, + 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x70, 0x61, 0x72, 0x65, + 0x6e, 0x74, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x04, + 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x38, 0x0a, 0x09, + 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, + 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, + 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x2e, 0x0a, 0x13, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, + 0x5f, 0x77, 0x69, 0x74, 0x68, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x18, 0x06, 0x20, + 0x01, 0x28, 0x08, 0x52, 0x11, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, 0x57, 0x69, 0x74, 0x68, 0x43, + 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x22, 0x21, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x22, 0xe4, 0x01, 0x0a, 0x10, 0x47, 0x65, + 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1b, + 0x0a, 0x09, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0c, 0x52, 0x08, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x62, + 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, + 0x73, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, + 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, 0x6d, + 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, + 0x61, 0x6d, 0x70, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, + 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, + 0x12, 0x2e, 0x0a, 0x13, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x5f, + 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x76, + 0x65, 0x72, 0x69, 0x66, 0x79, 0x57, 0x69, 0x74, 0x68, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, + 0x22, 0x26, 0x0a, 0x14, 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, + 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x22, 0x68, 0x0a, 0x12, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, + 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, + 0x79, 0x74, 0x65, 0x73, 0x12, 0x29, 0x0a, 0x0e, 0x70, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, + 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x48, 0x00, 0x52, 0x0c, + 0x70, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x88, 0x01, 0x01, 0x42, + 0x11, 0x0a, 0x0f, 0x5f, 0x70, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x22, 0x4f, 0x0a, 0x13, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, + 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, 0x6d, + 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, + 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, + 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, + 0x61, 0x6d, 0x70, 0x22, 0x24, 0x0a, 0x12, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x41, 0x63, 0x63, 0x65, + 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x22, 0x24, 0x0a, 0x12, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, + 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x22, + 0x2a, 0x0a, 0x0e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x12, 0x18, 0x0a, 0x07, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0c, 0x52, 0x07, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x22, 0x2b, 0x0a, 0x0f, 0x56, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, + 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x99, 0x01, 0x0a, 0x0d, 0x41, 0x70, 0x70, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, + 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, + 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, + 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x49, 0x64, 0x12, 0x36, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, - 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x2e, 0x0a, 0x13, 0x76, - 0x65, 0x72, 0x69, 0x66, 0x79, 0x5f, 0x77, 0x69, 0x74, 0x68, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, - 0x78, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x08, 0x52, 0x11, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, - 0x57, 0x69, 0x74, 0x68, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x22, 0x21, 0x0a, 0x0f, 0x47, - 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, - 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x22, 0xe4, - 0x01, 0x0a, 0x10, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x70, 0x61, 0x72, 0x65, 0x6e, 0x74, 0x49, 0x64, - 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x38, - 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x05, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, - 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, - 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, - 0x52, 0x03, 0x65, 0x72, 0x72, 0x12, 0x2e, 0x0a, 0x13, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, 0x5f, - 0x77, 0x69, 0x74, 0x68, 0x5f, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x78, 0x74, 0x18, 0x07, 0x20, 0x01, - 0x28, 0x08, 0x52, 0x11, 0x76, 0x65, 0x72, 0x69, 0x66, 0x79, 0x57, 0x69, 0x74, 0x68, 0x43, 0x6f, - 0x6e, 0x74, 0x65, 0x78, 0x74, 0x22, 0x26, 0x0a, 0x14, 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, - 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, - 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x22, 0x68, 0x0a, - 0x12, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x29, 0x0a, 0x0e, 0x70, 0x5f, 0x63, - 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x04, 0x48, 0x00, 0x52, 0x0c, 0x70, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x48, 0x65, 0x69, 0x67, 0x68, - 0x74, 0x88, 0x01, 0x01, 0x42, 0x11, 0x0a, 0x0f, 0x5f, 0x70, 0x5f, 0x63, 0x68, 0x61, 0x69, 0x6e, - 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x4f, 0x0a, 0x13, 0x42, 0x6c, 0x6f, 0x63, 0x6b, - 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x38, - 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x72, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x22, 0x91, 0x01, 0x0a, 0x13, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x4d, 0x73, 0x67, 0x12, 0x17, 0x0a, 0x07, + 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, + 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x63, 0x6f, + 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x11, 0x52, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, + 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, + 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, + 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x64, 0x0a, 0x0e, 0x41, 0x70, 0x70, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, + 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, + 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, + 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x39, + 0x0a, 0x0c, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x4d, 0x73, 0x67, 0x12, 0x17, + 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22, 0xa5, 0x01, 0x0a, 0x17, 0x43, 0x72, + 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, + 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, + 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, + 0x36, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, - 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x22, 0x24, 0x0a, 0x12, 0x42, 0x6c, 0x6f, 0x63, - 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, - 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x22, 0x24, - 0x0a, 0x12, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x02, 0x69, 0x64, 0x22, 0x2a, 0x0a, 0x0e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, - 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, - 0x22, 0x2b, 0x0a, 0x0f, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x99, 0x01, - 0x0a, 0x0d, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x12, - 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x36, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, - 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, - 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, - 0x18, 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x91, 0x01, 0x0a, 0x13, 0x41, 0x70, - 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x4d, 0x73, - 0x67, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, - 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x72, 0x72, - 0x6f, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x11, 0x52, 0x09, 0x65, - 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, - 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x64, 0x0a, - 0x0e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x12, - 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, + 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x08, 0x64, + 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x22, 0x9d, 0x01, 0x0a, 0x1d, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, + 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, + 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, + 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, + 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x11, 0x52, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, + 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, + 0x65, 0x22, 0x70, 0x0a, 0x18, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, + 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, + 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x22, 0x39, 0x0a, 0x0c, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, - 0x4d, 0x73, 0x67, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x10, 0x0a, 0x03, - 0x6d, 0x73, 0x67, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22, 0xa5, - 0x01, 0x0a, 0x17, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, - 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, - 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x49, 0x64, 0x12, 0x36, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, - 0x6d, 0x70, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x18, 0x0a, 0x07, - 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x72, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x9d, 0x01, 0x0a, 0x1d, 0x43, 0x72, 0x6f, 0x73, 0x73, - 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, - 0x61, 0x69, 0x6c, 0x65, 0x64, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, - 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, - 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, - 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x11, 0x52, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, - 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, - 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, - 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x70, 0x0a, 0x18, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, - 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, - 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, - 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, - 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, - 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, - 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x81, 0x01, 0x0a, 0x10, 0x43, 0x6f, 0x6e, - 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, - 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, - 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x61, - 0x6a, 0x6f, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, - 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, - 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x22, 0x2e, 0x0a, 0x13, - 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x22, 0xb3, 0x01, 0x0a, - 0x13, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x12, 0x15, 0x0a, 0x06, 0x62, 0x6c, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x6c, 0x6b, 0x49, 0x64, 0x12, 0x24, 0x0a, 0x0e, 0x6d, - 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x05, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x4e, 0x75, - 0x6d, 0x12, 0x26, 0x0a, 0x0f, 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x5f, - 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0d, 0x6d, 0x61, 0x78, 0x42, - 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x6d, 0x61, 0x78, - 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x69, 0x76, 0x61, 0x6c, - 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x15, 0x6d, 0x61, 0x78, - 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x52, 0x65, 0x74, 0x72, 0x69, 0x76, 0x61, 0x6c, 0x54, 0x69, - 0x6d, 0x65, 0x22, 0x35, 0x0a, 0x14, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, - 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, - 0x6b, 0x73, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, - 0x62, 0x6c, 0x6b, 0x73, 0x42, 0x79, 0x74, 0x65, 0x73, 0x22, 0x34, 0x0a, 0x18, 0x42, 0x61, 0x74, - 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, - 0x4f, 0x0a, 0x19, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, - 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x08, - 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, - 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x22, 0x33, 0x0a, 0x19, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, - 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, - 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, - 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x50, 0x0a, 0x1a, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, - 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x15, 0x0a, 0x06, 0x62, 0x6c, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x6c, 0x6b, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, - 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, - 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x5d, 0x0a, 0x0e, 0x47, 0x61, 0x74, 0x68, 0x65, - 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x0f, 0x6d, 0x65, 0x74, - 0x72, 0x69, 0x63, 0x5f, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, - 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, - 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, - 0x46, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x52, 0x0e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x46, 0x61, - 0x6d, 0x69, 0x6c, 0x69, 0x65, 0x73, 0x22, 0x51, 0x0a, 0x18, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, - 0x79, 0x6e, 0x63, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x1b, 0x0a, 0x03, - 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, - 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x7f, 0x0a, 0x22, 0x47, 0x65, 0x74, - 0x4f, 0x6e, 0x67, 0x6f, 0x69, 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, 0x65, - 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, - 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, - 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, 0x0a, - 0x03, 0x65, 0x72, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, - 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x78, 0x0a, 0x1b, 0x47, 0x65, - 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, - 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, - 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, - 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x04, + 0x6e, 0x73, 0x65, 0x22, 0x81, 0x01, 0x0a, 0x10, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, + 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, + 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, + 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x18, 0x03, + 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x6d, + 0x69, 0x6e, 0x6f, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6d, 0x69, 0x6e, 0x6f, + 0x72, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, + 0x52, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x22, 0x2e, 0x0a, 0x13, 0x44, 0x69, 0x73, 0x63, 0x6f, + 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, + 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x22, 0xb3, 0x01, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x41, + 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, + 0x15, 0x0a, 0x06, 0x62, 0x6c, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x05, 0x62, 0x6c, 0x6b, 0x49, 0x64, 0x12, 0x24, 0x0a, 0x0e, 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, + 0x6f, 0x63, 0x6b, 0x73, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, + 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x4e, 0x75, 0x6d, 0x12, 0x26, 0x0a, 0x0f, + 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0d, 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, + 0x53, 0x69, 0x7a, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, + 0x6b, 0x73, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x69, 0x76, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, + 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x15, 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, + 0x73, 0x52, 0x65, 0x74, 0x72, 0x69, 0x76, 0x61, 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x35, 0x0a, + 0x14, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6b, 0x73, 0x5f, 0x62, 0x79, + 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, 0x62, 0x6c, 0x6b, 0x73, 0x42, + 0x79, 0x74, 0x65, 0x73, 0x22, 0x34, 0x0a, 0x18, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, + 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x01, 0x20, 0x03, 0x28, + 0x0c, 0x52, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x4f, 0x0a, 0x19, 0x42, 0x61, + 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x50, + 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x33, 0x0a, 0x19, 0x47, + 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, + 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, + 0x22, 0x50, 0x0a, 0x1a, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, + 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x15, + 0x0a, 0x06, 0x62, 0x6c, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, + 0x62, 0x6c, 0x6b, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, + 0x72, 0x72, 0x22, 0x5d, 0x0a, 0x0e, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x0f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x5f, 0x66, + 0x61, 0x6d, 0x69, 0x6c, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, + 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, + 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x46, 0x61, 0x6d, 0x69, 0x6c, + 0x79, 0x52, 0x0e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x46, 0x61, 0x6d, 0x69, 0x6c, 0x69, 0x65, + 0x73, 0x22, 0x51, 0x0a, 0x18, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, 0x6e, 0x63, 0x45, 0x6e, + 0x61, 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, + 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, + 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, - 0x03, 0x65, 0x72, 0x72, 0x22, 0x30, 0x0a, 0x18, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x03, 0x65, 0x72, 0x72, 0x22, 0x7f, 0x0a, 0x22, 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, + 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, + 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, + 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, + 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, + 0x68, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, + 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, + 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x78, 0x0a, 0x1b, 0x47, 0x65, 0x74, 0x4c, 0x61, 0x73, 0x74, + 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, + 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x14, 0x0a, 0x05, + 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, + 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, + 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, + 0x30, 0x0a, 0x18, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, + 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, + 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, + 0x73, 0x22, 0x60, 0x0a, 0x19, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, + 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, + 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, + 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, + 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, + 0x65, 0x72, 0x72, 0x22, 0x30, 0x0a, 0x16, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, + 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, + 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, + 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x5c, 0x0a, 0x17, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, + 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, + 0x65, 0x72, 0x72, 0x22, 0x31, 0x0a, 0x19, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, + 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x22, 0x60, 0x0a, 0x19, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, - 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x1b, 0x0a, 0x03, 0x65, - 0x72, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, - 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x30, 0x0a, 0x16, 0x47, 0x65, 0x74, 0x53, - 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x5c, 0x0a, 0x17, 0x47, 0x65, - 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, 0x65, - 0x72, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, - 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x31, 0x0a, 0x19, 0x53, 0x74, 0x61, 0x74, - 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x22, 0xc5, 0x01, 0x0a, 0x1a, - 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, - 0x70, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x04, 0x6d, 0x6f, - 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x23, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, - 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x6d, - 0x6f, 0x64, 0x65, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, - 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, - 0x22, 0x51, 0x0a, 0x04, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x14, 0x0a, 0x10, 0x4d, 0x4f, 0x44, 0x45, - 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x10, - 0x0a, 0x0c, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x53, 0x4b, 0x49, 0x50, 0x50, 0x45, 0x44, 0x10, 0x01, - 0x12, 0x0f, 0x0a, 0x0b, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x49, 0x43, 0x10, - 0x02, 0x12, 0x10, 0x0a, 0x0c, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x44, 0x59, 0x4e, 0x41, 0x4d, 0x49, - 0x43, 0x10, 0x03, 0x2a, 0x65, 0x0a, 0x05, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x15, 0x0a, 0x11, - 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, - 0x44, 0x10, 0x00, 0x12, 0x17, 0x0a, 0x13, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x54, 0x41, - 0x54, 0x45, 0x5f, 0x53, 0x59, 0x4e, 0x43, 0x49, 0x4e, 0x47, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, - 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x42, 0x4f, 0x4f, 0x54, 0x53, 0x54, 0x52, 0x41, 0x50, 0x50, - 0x49, 0x4e, 0x47, 0x10, 0x02, 0x12, 0x13, 0x0a, 0x0f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x4e, - 0x4f, 0x52, 0x4d, 0x41, 0x4c, 0x5f, 0x4f, 0x50, 0x10, 0x03, 0x2a, 0x6b, 0x0a, 0x05, 0x45, 0x72, - 0x72, 0x6f, 0x72, 0x12, 0x15, 0x0a, 0x11, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x55, 0x4e, 0x53, - 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x45, 0x52, - 0x52, 0x4f, 0x52, 0x5f, 0x43, 0x4c, 0x4f, 0x53, 0x45, 0x44, 0x10, 0x01, 0x12, 0x13, 0x0a, 0x0f, - 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x46, 0x4f, 0x55, 0x4e, 0x44, 0x10, - 0x02, 0x12, 0x24, 0x0a, 0x20, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, - 0x5f, 0x53, 0x59, 0x4e, 0x43, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x49, 0x4d, 0x50, 0x4c, 0x45, 0x4d, - 0x45, 0x4e, 0x54, 0x45, 0x44, 0x10, 0x03, 0x32, 0x86, 0x11, 0x0a, 0x02, 0x56, 0x4d, 0x12, 0x3b, - 0x0a, 0x0a, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x12, 0x15, 0x2e, 0x76, - 0x6d, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, - 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x53, - 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, - 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x76, - 0x6d, 0x2e, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x3a, 0x0a, 0x08, 0x53, 0x68, 0x75, 0x74, 0x64, 0x6f, 0x77, 0x6e, 0x12, 0x16, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x44, - 0x0a, 0x0e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, - 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, - 0x65, 0x61, 0x74, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, - 0x64, 0x12, 0x14, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, + 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x22, 0xc5, 0x01, 0x0a, 0x1a, 0x53, 0x74, 0x61, 0x74, 0x65, + 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0e, 0x32, 0x23, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, + 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x2e, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x12, 0x1b, + 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, + 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x51, 0x0a, 0x04, 0x4d, + 0x6f, 0x64, 0x65, 0x12, 0x14, 0x0a, 0x10, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, + 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x4d, 0x4f, 0x44, + 0x45, 0x5f, 0x53, 0x4b, 0x49, 0x50, 0x50, 0x45, 0x44, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x4d, + 0x4f, 0x44, 0x45, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x49, 0x43, 0x10, 0x02, 0x12, 0x10, 0x0a, 0x0c, + 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x44, 0x59, 0x4e, 0x41, 0x4d, 0x49, 0x43, 0x10, 0x03, 0x2a, 0x65, + 0x0a, 0x05, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x45, + 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x17, + 0x0a, 0x13, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x59, + 0x4e, 0x43, 0x49, 0x4e, 0x47, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x53, 0x54, 0x41, 0x54, 0x45, + 0x5f, 0x42, 0x4f, 0x4f, 0x54, 0x53, 0x54, 0x52, 0x41, 0x50, 0x50, 0x49, 0x4e, 0x47, 0x10, 0x02, + 0x12, 0x13, 0x0a, 0x0f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x4e, 0x4f, 0x52, 0x4d, 0x41, 0x4c, + 0x5f, 0x4f, 0x50, 0x10, 0x03, 0x2a, 0x6b, 0x0a, 0x05, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x15, + 0x0a, 0x11, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, + 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x43, + 0x4c, 0x4f, 0x53, 0x45, 0x44, 0x10, 0x01, 0x12, 0x13, 0x0a, 0x0f, 0x45, 0x52, 0x52, 0x4f, 0x52, + 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x46, 0x4f, 0x55, 0x4e, 0x44, 0x10, 0x02, 0x12, 0x24, 0x0a, 0x20, + 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x59, 0x4e, 0x43, + 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x49, 0x4d, 0x50, 0x4c, 0x45, 0x4d, 0x45, 0x4e, 0x54, 0x45, 0x44, + 0x10, 0x03, 0x32, 0x86, 0x11, 0x0a, 0x02, 0x56, 0x4d, 0x12, 0x3b, 0x0a, 0x0a, 0x49, 0x6e, 0x69, + 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x12, 0x15, 0x2e, 0x76, 0x6d, 0x2e, 0x49, 0x6e, 0x69, + 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, + 0x2e, 0x76, 0x6d, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, + 0x74, 0x65, 0x12, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, + 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3a, 0x0a, + 0x08, 0x53, 0x68, 0x75, 0x74, 0x64, 0x6f, 0x77, 0x6e, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, + 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x44, 0x0a, 0x0e, 0x43, 0x72, 0x65, + 0x61, 0x74, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x12, 0x16, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, + 0x70, 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, + 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, + 0x39, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x14, 0x2e, 0x76, + 0x6d, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3f, 0x0a, 0x0c, 0x44, 0x69, + 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, + 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3b, 0x0a, 0x0a, 0x42, + 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x15, 0x2e, 0x76, 0x6d, 0x2e, 0x42, + 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3b, 0x0a, 0x0a, 0x50, 0x61, 0x72, 0x73, + 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x15, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, + 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, + 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x12, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, + 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x41, 0x0a, 0x0d, + 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x18, 0x2e, + 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, - 0x3f, 0x0a, 0x0c, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, - 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, - 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, - 0x12, 0x3b, 0x0a, 0x0a, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x15, - 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x75, 0x69, 0x6c, 0x64, - 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3b, 0x0a, - 0x0a, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x15, 0x2e, 0x76, 0x6d, - 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, - 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x47, 0x65, - 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, - 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x76, 0x6d, - 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x12, 0x41, 0x0a, 0x0d, 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, - 0x63, 0x65, 0x12, 0x18, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, 0x65, - 0x72, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, - 0x6d, 0x70, 0x74, 0x79, 0x12, 0x34, 0x0a, 0x06, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x12, 0x16, + 0x34, 0x0a, 0x06, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, + 0x79, 0x1a, 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, + 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x56, 0x65, + 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, + 0x0a, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x11, 0x2e, 0x76, 0x6d, + 0x2e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x48, 0x65, 0x61, 0x6c, - 0x74, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x56, 0x65, - 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x13, 0x2e, - 0x76, 0x6d, 0x2e, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x37, 0x0a, 0x0a, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x12, 0x11, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x43, 0x0a, 0x10, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, + 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x43, 0x0a, 0x10, 0x41, - 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x12, - 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, - 0x61, 0x69, 0x6c, 0x65, 0x64, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x39, 0x0a, 0x0b, 0x41, + 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x2e, 0x76, 0x6d, 0x2e, + 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x1a, 0x16, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x35, 0x0a, 0x09, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, + 0x73, 0x69, 0x70, 0x12, 0x10, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, + 0x69, 0x70, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x34, 0x0a, + 0x06, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, + 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x14, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, + 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x2e, 0x76, 0x6d, + 0x2e, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, - 0x12, 0x39, 0x0a, 0x0b, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x35, 0x0a, 0x09, 0x41, - 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x12, 0x10, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, - 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, - 0x74, 0x79, 0x12, 0x34, 0x0a, 0x06, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, 0x12, 0x16, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, - 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x14, 0x43, 0x72, 0x6f, 0x73, - 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x12, 0x1b, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, - 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, - 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, - 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x57, 0x0a, 0x1a, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, - 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, - 0x6c, 0x65, 0x64, 0x12, 0x21, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, - 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, - 0x6c, 0x65, 0x64, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x4d, - 0x0a, 0x15, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x6f, + 0x12, 0x57, 0x0a, 0x1a, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, + 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x12, 0x21, + 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, + 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x4d, 0x73, + 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x4d, 0x0a, 0x15, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x41, 0x0a, - 0x0c, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x17, 0x2e, - 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x18, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x41, - 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x50, 0x0a, 0x11, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, - 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, - 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, - 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x53, 0x0a, 0x12, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, - 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x1d, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, - 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1e, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, - 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x48, 0x0a, 0x10, 0x53, 0x74, 0x61, 0x74, 0x65, - 0x53, 0x79, 0x6e, 0x63, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x16, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, - 0x70, 0x74, 0x79, 0x1a, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, - 0x6e, 0x63, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x12, 0x5c, 0x0a, 0x1a, 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, 0x6e, 0x67, 0x53, - 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, + 0x73, 0x65, 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, + 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, + 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x41, 0x0a, 0x0c, 0x47, 0x65, 0x74, 0x41, + 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, + 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x1a, 0x18, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, + 0x6f, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x11, 0x42, + 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, + 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, + 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, + 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, + 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x53, 0x0a, + 0x12, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, + 0x67, 0x68, 0x74, 0x12, 0x1d, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x1e, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, + 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x48, 0x0a, 0x10, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, 0x6e, 0x63, 0x45, + 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1c, + 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, 0x6e, 0x63, 0x45, 0x6e, 0x61, + 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5c, 0x0a, 0x1a, + 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, + 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, + 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, + 0x74, 0x79, 0x1a, 0x26, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, + 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, + 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4e, 0x0a, 0x13, 0x47, 0x65, + 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, + 0x79, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1f, 0x2e, 0x76, 0x6d, 0x2e, 0x47, + 0x65, 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, + 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x11, 0x50, 0x61, + 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, + 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, + 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, + 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, + 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4a, 0x0a, 0x0f, + 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, + 0x1a, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, + 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1b, 0x2e, 0x76, 0x6d, + 0x2e, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, + 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x26, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, - 0x4f, 0x6e, 0x67, 0x6f, 0x69, 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, 0x65, - 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x4e, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, - 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1f, - 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, - 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x50, 0x0a, 0x11, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, - 0x6d, 0x61, 0x72, 0x79, 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, - 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x12, 0x4a, 0x0a, 0x0f, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, - 0x6d, 0x61, 0x72, 0x79, 0x12, 0x1a, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x1b, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, - 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, 0x0a, - 0x0b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x12, 0x16, 0x2e, 0x76, - 0x6d, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x1a, 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, - 0x65, 0x72, 0x69, 0x66, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, - 0x0b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x12, 0x16, 0x2e, 0x76, - 0x6d, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3d, 0x0a, 0x0b, - 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x16, 0x2e, 0x76, 0x6d, - 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x53, 0x0a, 0x12, 0x53, - 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, - 0x74, 0x12, 0x1d, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, - 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x1e, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, - 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x42, 0x2d, 0x5a, 0x2b, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, - 0x76, 0x61, 0x2d, 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x61, 0x76, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x68, - 0x65, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x70, 0x62, 0x2f, 0x76, 0x6d, 0x62, - 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3d, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, + 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, + 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, + 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x53, 0x0a, 0x12, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, + 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x12, 0x1d, 0x2e, 0x76, + 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, + 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1e, 0x2e, 0x76, 0x6d, + 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, + 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x2d, 0x5a, 0x2b, 0x67, + 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x76, 0x61, 0x2d, 0x6c, 0x61, + 0x62, 0x73, 0x2f, 0x61, 0x76, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x68, 0x65, 0x67, 0x6f, 0x2f, 0x70, + 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x70, 0x62, 0x2f, 0x76, 0x6d, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x33, } var ( @@ -3361,150 +3590,164 @@ func file_vm_vm_proto_rawDescGZIP() []byte { } var file_vm_vm_proto_enumTypes = make([]protoimpl.EnumInfo, 3) -var file_vm_vm_proto_msgTypes = make([]protoimpl.MessageInfo, 44) +var file_vm_vm_proto_msgTypes = make([]protoimpl.MessageInfo, 45) var file_vm_vm_proto_goTypes = []interface{}{ (State)(0), // 0: vm.State (Error)(0), // 1: vm.Error (StateSummaryAcceptResponse_Mode)(0), // 2: vm.StateSummaryAcceptResponse.Mode (*InitializeRequest)(nil), // 3: vm.InitializeRequest - (*InitializeResponse)(nil), // 4: vm.InitializeResponse - (*SetStateRequest)(nil), // 5: vm.SetStateRequest - (*SetStateResponse)(nil), // 6: vm.SetStateResponse - (*CreateHandlersResponse)(nil), // 7: vm.CreateHandlersResponse - (*Handler)(nil), // 8: vm.Handler - (*BuildBlockRequest)(nil), // 9: vm.BuildBlockRequest - (*BuildBlockResponse)(nil), // 10: vm.BuildBlockResponse - (*ParseBlockRequest)(nil), // 11: vm.ParseBlockRequest - (*ParseBlockResponse)(nil), // 12: vm.ParseBlockResponse - (*GetBlockRequest)(nil), // 13: vm.GetBlockRequest - (*GetBlockResponse)(nil), // 14: vm.GetBlockResponse - (*SetPreferenceRequest)(nil), // 15: vm.SetPreferenceRequest - (*BlockVerifyRequest)(nil), // 16: vm.BlockVerifyRequest - (*BlockVerifyResponse)(nil), // 17: vm.BlockVerifyResponse - (*BlockAcceptRequest)(nil), // 18: vm.BlockAcceptRequest - (*BlockRejectRequest)(nil), // 19: vm.BlockRejectRequest - (*HealthResponse)(nil), // 20: vm.HealthResponse - (*VersionResponse)(nil), // 21: vm.VersionResponse - (*AppRequestMsg)(nil), // 22: vm.AppRequestMsg - (*AppRequestFailedMsg)(nil), // 23: vm.AppRequestFailedMsg - (*AppResponseMsg)(nil), // 24: vm.AppResponseMsg - (*AppGossipMsg)(nil), // 25: vm.AppGossipMsg - (*CrossChainAppRequestMsg)(nil), // 26: vm.CrossChainAppRequestMsg - (*CrossChainAppRequestFailedMsg)(nil), // 27: vm.CrossChainAppRequestFailedMsg - (*CrossChainAppResponseMsg)(nil), // 28: vm.CrossChainAppResponseMsg - (*ConnectedRequest)(nil), // 29: vm.ConnectedRequest - (*DisconnectedRequest)(nil), // 30: vm.DisconnectedRequest - (*GetAncestorsRequest)(nil), // 31: vm.GetAncestorsRequest - (*GetAncestorsResponse)(nil), // 32: vm.GetAncestorsResponse - (*BatchedParseBlockRequest)(nil), // 33: vm.BatchedParseBlockRequest - (*BatchedParseBlockResponse)(nil), // 34: vm.BatchedParseBlockResponse - (*GetBlockIDAtHeightRequest)(nil), // 35: vm.GetBlockIDAtHeightRequest - (*GetBlockIDAtHeightResponse)(nil), // 36: vm.GetBlockIDAtHeightResponse - (*GatherResponse)(nil), // 37: vm.GatherResponse - (*StateSyncEnabledResponse)(nil), // 38: vm.StateSyncEnabledResponse - (*GetOngoingSyncStateSummaryResponse)(nil), // 39: vm.GetOngoingSyncStateSummaryResponse - (*GetLastStateSummaryResponse)(nil), // 40: vm.GetLastStateSummaryResponse - (*ParseStateSummaryRequest)(nil), // 41: vm.ParseStateSummaryRequest - (*ParseStateSummaryResponse)(nil), // 42: vm.ParseStateSummaryResponse - (*GetStateSummaryRequest)(nil), // 43: vm.GetStateSummaryRequest - (*GetStateSummaryResponse)(nil), // 44: vm.GetStateSummaryResponse - (*StateSummaryAcceptRequest)(nil), // 45: vm.StateSummaryAcceptRequest - (*StateSummaryAcceptResponse)(nil), // 46: vm.StateSummaryAcceptResponse - (*timestamppb.Timestamp)(nil), // 47: google.protobuf.Timestamp - (*_go.MetricFamily)(nil), // 48: io.prometheus.client.MetricFamily - (*emptypb.Empty)(nil), // 49: google.protobuf.Empty + (*NetworkUpgrades)(nil), // 4: vm.NetworkUpgrades + (*InitializeResponse)(nil), // 5: vm.InitializeResponse + (*SetStateRequest)(nil), // 6: vm.SetStateRequest + (*SetStateResponse)(nil), // 7: vm.SetStateResponse + (*CreateHandlersResponse)(nil), // 8: vm.CreateHandlersResponse + (*Handler)(nil), // 9: vm.Handler + (*BuildBlockRequest)(nil), // 10: vm.BuildBlockRequest + (*BuildBlockResponse)(nil), // 11: vm.BuildBlockResponse + (*ParseBlockRequest)(nil), // 12: vm.ParseBlockRequest + (*ParseBlockResponse)(nil), // 13: vm.ParseBlockResponse + (*GetBlockRequest)(nil), // 14: vm.GetBlockRequest + (*GetBlockResponse)(nil), // 15: vm.GetBlockResponse + (*SetPreferenceRequest)(nil), // 16: vm.SetPreferenceRequest + (*BlockVerifyRequest)(nil), // 17: vm.BlockVerifyRequest + (*BlockVerifyResponse)(nil), // 18: vm.BlockVerifyResponse + (*BlockAcceptRequest)(nil), // 19: vm.BlockAcceptRequest + (*BlockRejectRequest)(nil), // 20: vm.BlockRejectRequest + (*HealthResponse)(nil), // 21: vm.HealthResponse + (*VersionResponse)(nil), // 22: vm.VersionResponse + (*AppRequestMsg)(nil), // 23: vm.AppRequestMsg + (*AppRequestFailedMsg)(nil), // 24: vm.AppRequestFailedMsg + (*AppResponseMsg)(nil), // 25: vm.AppResponseMsg + (*AppGossipMsg)(nil), // 26: vm.AppGossipMsg + (*CrossChainAppRequestMsg)(nil), // 27: vm.CrossChainAppRequestMsg + (*CrossChainAppRequestFailedMsg)(nil), // 28: vm.CrossChainAppRequestFailedMsg + (*CrossChainAppResponseMsg)(nil), // 29: vm.CrossChainAppResponseMsg + (*ConnectedRequest)(nil), // 30: vm.ConnectedRequest + (*DisconnectedRequest)(nil), // 31: vm.DisconnectedRequest + (*GetAncestorsRequest)(nil), // 32: vm.GetAncestorsRequest + (*GetAncestorsResponse)(nil), // 33: vm.GetAncestorsResponse + (*BatchedParseBlockRequest)(nil), // 34: vm.BatchedParseBlockRequest + (*BatchedParseBlockResponse)(nil), // 35: vm.BatchedParseBlockResponse + (*GetBlockIDAtHeightRequest)(nil), // 36: vm.GetBlockIDAtHeightRequest + (*GetBlockIDAtHeightResponse)(nil), // 37: vm.GetBlockIDAtHeightResponse + (*GatherResponse)(nil), // 38: vm.GatherResponse + (*StateSyncEnabledResponse)(nil), // 39: vm.StateSyncEnabledResponse + (*GetOngoingSyncStateSummaryResponse)(nil), // 40: vm.GetOngoingSyncStateSummaryResponse + (*GetLastStateSummaryResponse)(nil), // 41: vm.GetLastStateSummaryResponse + (*ParseStateSummaryRequest)(nil), // 42: vm.ParseStateSummaryRequest + (*ParseStateSummaryResponse)(nil), // 43: vm.ParseStateSummaryResponse + (*GetStateSummaryRequest)(nil), // 44: vm.GetStateSummaryRequest + (*GetStateSummaryResponse)(nil), // 45: vm.GetStateSummaryResponse + (*StateSummaryAcceptRequest)(nil), // 46: vm.StateSummaryAcceptRequest + (*StateSummaryAcceptResponse)(nil), // 47: vm.StateSummaryAcceptResponse + (*timestamppb.Timestamp)(nil), // 48: google.protobuf.Timestamp + (*_go.MetricFamily)(nil), // 49: io.prometheus.client.MetricFamily + (*emptypb.Empty)(nil), // 50: google.protobuf.Empty } var file_vm_vm_proto_depIdxs = []int32{ - 47, // 0: vm.InitializeResponse.timestamp:type_name -> google.protobuf.Timestamp - 0, // 1: vm.SetStateRequest.state:type_name -> vm.State - 47, // 2: vm.SetStateResponse.timestamp:type_name -> google.protobuf.Timestamp - 8, // 3: vm.CreateHandlersResponse.handlers:type_name -> vm.Handler - 47, // 4: vm.BuildBlockResponse.timestamp:type_name -> google.protobuf.Timestamp - 47, // 5: vm.ParseBlockResponse.timestamp:type_name -> google.protobuf.Timestamp - 47, // 6: vm.GetBlockResponse.timestamp:type_name -> google.protobuf.Timestamp - 1, // 7: vm.GetBlockResponse.err:type_name -> vm.Error - 47, // 8: vm.BlockVerifyResponse.timestamp:type_name -> google.protobuf.Timestamp - 47, // 9: vm.AppRequestMsg.deadline:type_name -> google.protobuf.Timestamp - 47, // 10: vm.CrossChainAppRequestMsg.deadline:type_name -> google.protobuf.Timestamp - 12, // 11: vm.BatchedParseBlockResponse.response:type_name -> vm.ParseBlockResponse - 1, // 12: vm.GetBlockIDAtHeightResponse.err:type_name -> vm.Error - 48, // 13: vm.GatherResponse.metric_families:type_name -> io.prometheus.client.MetricFamily - 1, // 14: vm.StateSyncEnabledResponse.err:type_name -> vm.Error - 1, // 15: vm.GetOngoingSyncStateSummaryResponse.err:type_name -> vm.Error - 1, // 16: vm.GetLastStateSummaryResponse.err:type_name -> vm.Error - 1, // 17: vm.ParseStateSummaryResponse.err:type_name -> vm.Error - 1, // 18: vm.GetStateSummaryResponse.err:type_name -> vm.Error - 2, // 19: vm.StateSummaryAcceptResponse.mode:type_name -> vm.StateSummaryAcceptResponse.Mode - 1, // 20: vm.StateSummaryAcceptResponse.err:type_name -> vm.Error - 3, // 21: vm.VM.Initialize:input_type -> vm.InitializeRequest - 5, // 22: vm.VM.SetState:input_type -> vm.SetStateRequest - 49, // 23: vm.VM.Shutdown:input_type -> google.protobuf.Empty - 49, // 24: vm.VM.CreateHandlers:input_type -> google.protobuf.Empty - 29, // 25: vm.VM.Connected:input_type -> vm.ConnectedRequest - 30, // 26: vm.VM.Disconnected:input_type -> vm.DisconnectedRequest - 9, // 27: vm.VM.BuildBlock:input_type -> vm.BuildBlockRequest - 11, // 28: vm.VM.ParseBlock:input_type -> vm.ParseBlockRequest - 13, // 29: vm.VM.GetBlock:input_type -> vm.GetBlockRequest - 15, // 30: vm.VM.SetPreference:input_type -> vm.SetPreferenceRequest - 49, // 31: vm.VM.Health:input_type -> google.protobuf.Empty - 49, // 32: vm.VM.Version:input_type -> google.protobuf.Empty - 22, // 33: vm.VM.AppRequest:input_type -> vm.AppRequestMsg - 23, // 34: vm.VM.AppRequestFailed:input_type -> vm.AppRequestFailedMsg - 24, // 35: vm.VM.AppResponse:input_type -> vm.AppResponseMsg - 25, // 36: vm.VM.AppGossip:input_type -> vm.AppGossipMsg - 49, // 37: vm.VM.Gather:input_type -> google.protobuf.Empty - 26, // 38: vm.VM.CrossChainAppRequest:input_type -> vm.CrossChainAppRequestMsg - 27, // 39: vm.VM.CrossChainAppRequestFailed:input_type -> vm.CrossChainAppRequestFailedMsg - 28, // 40: vm.VM.CrossChainAppResponse:input_type -> vm.CrossChainAppResponseMsg - 31, // 41: vm.VM.GetAncestors:input_type -> vm.GetAncestorsRequest - 33, // 42: vm.VM.BatchedParseBlock:input_type -> vm.BatchedParseBlockRequest - 35, // 43: vm.VM.GetBlockIDAtHeight:input_type -> vm.GetBlockIDAtHeightRequest - 49, // 44: vm.VM.StateSyncEnabled:input_type -> google.protobuf.Empty - 49, // 45: vm.VM.GetOngoingSyncStateSummary:input_type -> google.protobuf.Empty - 49, // 46: vm.VM.GetLastStateSummary:input_type -> google.protobuf.Empty - 41, // 47: vm.VM.ParseStateSummary:input_type -> vm.ParseStateSummaryRequest - 43, // 48: vm.VM.GetStateSummary:input_type -> vm.GetStateSummaryRequest - 16, // 49: vm.VM.BlockVerify:input_type -> vm.BlockVerifyRequest - 18, // 50: vm.VM.BlockAccept:input_type -> vm.BlockAcceptRequest - 19, // 51: vm.VM.BlockReject:input_type -> vm.BlockRejectRequest - 45, // 52: vm.VM.StateSummaryAccept:input_type -> vm.StateSummaryAcceptRequest - 4, // 53: vm.VM.Initialize:output_type -> vm.InitializeResponse - 6, // 54: vm.VM.SetState:output_type -> vm.SetStateResponse - 49, // 55: vm.VM.Shutdown:output_type -> google.protobuf.Empty - 7, // 56: vm.VM.CreateHandlers:output_type -> vm.CreateHandlersResponse - 49, // 57: vm.VM.Connected:output_type -> google.protobuf.Empty - 49, // 58: vm.VM.Disconnected:output_type -> google.protobuf.Empty - 10, // 59: vm.VM.BuildBlock:output_type -> vm.BuildBlockResponse - 12, // 60: vm.VM.ParseBlock:output_type -> vm.ParseBlockResponse - 14, // 61: vm.VM.GetBlock:output_type -> vm.GetBlockResponse - 49, // 62: vm.VM.SetPreference:output_type -> google.protobuf.Empty - 20, // 63: vm.VM.Health:output_type -> vm.HealthResponse - 21, // 64: vm.VM.Version:output_type -> vm.VersionResponse - 49, // 65: vm.VM.AppRequest:output_type -> google.protobuf.Empty - 49, // 66: vm.VM.AppRequestFailed:output_type -> google.protobuf.Empty - 49, // 67: vm.VM.AppResponse:output_type -> google.protobuf.Empty - 49, // 68: vm.VM.AppGossip:output_type -> google.protobuf.Empty - 37, // 69: vm.VM.Gather:output_type -> vm.GatherResponse - 49, // 70: vm.VM.CrossChainAppRequest:output_type -> google.protobuf.Empty - 49, // 71: vm.VM.CrossChainAppRequestFailed:output_type -> google.protobuf.Empty - 49, // 72: vm.VM.CrossChainAppResponse:output_type -> google.protobuf.Empty - 32, // 73: vm.VM.GetAncestors:output_type -> vm.GetAncestorsResponse - 34, // 74: vm.VM.BatchedParseBlock:output_type -> vm.BatchedParseBlockResponse - 36, // 75: vm.VM.GetBlockIDAtHeight:output_type -> vm.GetBlockIDAtHeightResponse - 38, // 76: vm.VM.StateSyncEnabled:output_type -> vm.StateSyncEnabledResponse - 39, // 77: vm.VM.GetOngoingSyncStateSummary:output_type -> vm.GetOngoingSyncStateSummaryResponse - 40, // 78: vm.VM.GetLastStateSummary:output_type -> vm.GetLastStateSummaryResponse - 42, // 79: vm.VM.ParseStateSummary:output_type -> vm.ParseStateSummaryResponse - 44, // 80: vm.VM.GetStateSummary:output_type -> vm.GetStateSummaryResponse - 17, // 81: vm.VM.BlockVerify:output_type -> vm.BlockVerifyResponse - 49, // 82: vm.VM.BlockAccept:output_type -> google.protobuf.Empty - 49, // 83: vm.VM.BlockReject:output_type -> google.protobuf.Empty - 46, // 84: vm.VM.StateSummaryAccept:output_type -> vm.StateSummaryAcceptResponse - 53, // [53:85] is the sub-list for method output_type - 21, // [21:53] is the sub-list for method input_type - 21, // [21:21] is the sub-list for extension type_name - 21, // [21:21] is the sub-list for extension extendee - 0, // [0:21] is the sub-list for field type_name + 4, // 0: vm.InitializeRequest.network_upgrades:type_name -> vm.NetworkUpgrades + 48, // 1: vm.NetworkUpgrades.apricot_phase_1_time:type_name -> google.protobuf.Timestamp + 48, // 2: vm.NetworkUpgrades.apricot_phase_2_time:type_name -> google.protobuf.Timestamp + 48, // 3: vm.NetworkUpgrades.apricot_phase_3_time:type_name -> google.protobuf.Timestamp + 48, // 4: vm.NetworkUpgrades.apricot_phase_4_time:type_name -> google.protobuf.Timestamp + 48, // 5: vm.NetworkUpgrades.apricot_phase_5_time:type_name -> google.protobuf.Timestamp + 48, // 6: vm.NetworkUpgrades.apricot_phase_pre_6_time:type_name -> google.protobuf.Timestamp + 48, // 7: vm.NetworkUpgrades.apricot_phase_6_time:type_name -> google.protobuf.Timestamp + 48, // 8: vm.NetworkUpgrades.apricot_phase_post_6_time:type_name -> google.protobuf.Timestamp + 48, // 9: vm.NetworkUpgrades.banff_time:type_name -> google.protobuf.Timestamp + 48, // 10: vm.NetworkUpgrades.cortina_time:type_name -> google.protobuf.Timestamp + 48, // 11: vm.NetworkUpgrades.durango_time:type_name -> google.protobuf.Timestamp + 48, // 12: vm.NetworkUpgrades.etna_time:type_name -> google.protobuf.Timestamp + 48, // 13: vm.InitializeResponse.timestamp:type_name -> google.protobuf.Timestamp + 0, // 14: vm.SetStateRequest.state:type_name -> vm.State + 48, // 15: vm.SetStateResponse.timestamp:type_name -> google.protobuf.Timestamp + 9, // 16: vm.CreateHandlersResponse.handlers:type_name -> vm.Handler + 48, // 17: vm.BuildBlockResponse.timestamp:type_name -> google.protobuf.Timestamp + 48, // 18: vm.ParseBlockResponse.timestamp:type_name -> google.protobuf.Timestamp + 48, // 19: vm.GetBlockResponse.timestamp:type_name -> google.protobuf.Timestamp + 1, // 20: vm.GetBlockResponse.err:type_name -> vm.Error + 48, // 21: vm.BlockVerifyResponse.timestamp:type_name -> google.protobuf.Timestamp + 48, // 22: vm.AppRequestMsg.deadline:type_name -> google.protobuf.Timestamp + 48, // 23: vm.CrossChainAppRequestMsg.deadline:type_name -> google.protobuf.Timestamp + 13, // 24: vm.BatchedParseBlockResponse.response:type_name -> vm.ParseBlockResponse + 1, // 25: vm.GetBlockIDAtHeightResponse.err:type_name -> vm.Error + 49, // 26: vm.GatherResponse.metric_families:type_name -> io.prometheus.client.MetricFamily + 1, // 27: vm.StateSyncEnabledResponse.err:type_name -> vm.Error + 1, // 28: vm.GetOngoingSyncStateSummaryResponse.err:type_name -> vm.Error + 1, // 29: vm.GetLastStateSummaryResponse.err:type_name -> vm.Error + 1, // 30: vm.ParseStateSummaryResponse.err:type_name -> vm.Error + 1, // 31: vm.GetStateSummaryResponse.err:type_name -> vm.Error + 2, // 32: vm.StateSummaryAcceptResponse.mode:type_name -> vm.StateSummaryAcceptResponse.Mode + 1, // 33: vm.StateSummaryAcceptResponse.err:type_name -> vm.Error + 3, // 34: vm.VM.Initialize:input_type -> vm.InitializeRequest + 6, // 35: vm.VM.SetState:input_type -> vm.SetStateRequest + 50, // 36: vm.VM.Shutdown:input_type -> google.protobuf.Empty + 50, // 37: vm.VM.CreateHandlers:input_type -> google.protobuf.Empty + 30, // 38: vm.VM.Connected:input_type -> vm.ConnectedRequest + 31, // 39: vm.VM.Disconnected:input_type -> vm.DisconnectedRequest + 10, // 40: vm.VM.BuildBlock:input_type -> vm.BuildBlockRequest + 12, // 41: vm.VM.ParseBlock:input_type -> vm.ParseBlockRequest + 14, // 42: vm.VM.GetBlock:input_type -> vm.GetBlockRequest + 16, // 43: vm.VM.SetPreference:input_type -> vm.SetPreferenceRequest + 50, // 44: vm.VM.Health:input_type -> google.protobuf.Empty + 50, // 45: vm.VM.Version:input_type -> google.protobuf.Empty + 23, // 46: vm.VM.AppRequest:input_type -> vm.AppRequestMsg + 24, // 47: vm.VM.AppRequestFailed:input_type -> vm.AppRequestFailedMsg + 25, // 48: vm.VM.AppResponse:input_type -> vm.AppResponseMsg + 26, // 49: vm.VM.AppGossip:input_type -> vm.AppGossipMsg + 50, // 50: vm.VM.Gather:input_type -> google.protobuf.Empty + 27, // 51: vm.VM.CrossChainAppRequest:input_type -> vm.CrossChainAppRequestMsg + 28, // 52: vm.VM.CrossChainAppRequestFailed:input_type -> vm.CrossChainAppRequestFailedMsg + 29, // 53: vm.VM.CrossChainAppResponse:input_type -> vm.CrossChainAppResponseMsg + 32, // 54: vm.VM.GetAncestors:input_type -> vm.GetAncestorsRequest + 34, // 55: vm.VM.BatchedParseBlock:input_type -> vm.BatchedParseBlockRequest + 36, // 56: vm.VM.GetBlockIDAtHeight:input_type -> vm.GetBlockIDAtHeightRequest + 50, // 57: vm.VM.StateSyncEnabled:input_type -> google.protobuf.Empty + 50, // 58: vm.VM.GetOngoingSyncStateSummary:input_type -> google.protobuf.Empty + 50, // 59: vm.VM.GetLastStateSummary:input_type -> google.protobuf.Empty + 42, // 60: vm.VM.ParseStateSummary:input_type -> vm.ParseStateSummaryRequest + 44, // 61: vm.VM.GetStateSummary:input_type -> vm.GetStateSummaryRequest + 17, // 62: vm.VM.BlockVerify:input_type -> vm.BlockVerifyRequest + 19, // 63: vm.VM.BlockAccept:input_type -> vm.BlockAcceptRequest + 20, // 64: vm.VM.BlockReject:input_type -> vm.BlockRejectRequest + 46, // 65: vm.VM.StateSummaryAccept:input_type -> vm.StateSummaryAcceptRequest + 5, // 66: vm.VM.Initialize:output_type -> vm.InitializeResponse + 7, // 67: vm.VM.SetState:output_type -> vm.SetStateResponse + 50, // 68: vm.VM.Shutdown:output_type -> google.protobuf.Empty + 8, // 69: vm.VM.CreateHandlers:output_type -> vm.CreateHandlersResponse + 50, // 70: vm.VM.Connected:output_type -> google.protobuf.Empty + 50, // 71: vm.VM.Disconnected:output_type -> google.protobuf.Empty + 11, // 72: vm.VM.BuildBlock:output_type -> vm.BuildBlockResponse + 13, // 73: vm.VM.ParseBlock:output_type -> vm.ParseBlockResponse + 15, // 74: vm.VM.GetBlock:output_type -> vm.GetBlockResponse + 50, // 75: vm.VM.SetPreference:output_type -> google.protobuf.Empty + 21, // 76: vm.VM.Health:output_type -> vm.HealthResponse + 22, // 77: vm.VM.Version:output_type -> vm.VersionResponse + 50, // 78: vm.VM.AppRequest:output_type -> google.protobuf.Empty + 50, // 79: vm.VM.AppRequestFailed:output_type -> google.protobuf.Empty + 50, // 80: vm.VM.AppResponse:output_type -> google.protobuf.Empty + 50, // 81: vm.VM.AppGossip:output_type -> google.protobuf.Empty + 38, // 82: vm.VM.Gather:output_type -> vm.GatherResponse + 50, // 83: vm.VM.CrossChainAppRequest:output_type -> google.protobuf.Empty + 50, // 84: vm.VM.CrossChainAppRequestFailed:output_type -> google.protobuf.Empty + 50, // 85: vm.VM.CrossChainAppResponse:output_type -> google.protobuf.Empty + 33, // 86: vm.VM.GetAncestors:output_type -> vm.GetAncestorsResponse + 35, // 87: vm.VM.BatchedParseBlock:output_type -> vm.BatchedParseBlockResponse + 37, // 88: vm.VM.GetBlockIDAtHeight:output_type -> vm.GetBlockIDAtHeightResponse + 39, // 89: vm.VM.StateSyncEnabled:output_type -> vm.StateSyncEnabledResponse + 40, // 90: vm.VM.GetOngoingSyncStateSummary:output_type -> vm.GetOngoingSyncStateSummaryResponse + 41, // 91: vm.VM.GetLastStateSummary:output_type -> vm.GetLastStateSummaryResponse + 43, // 92: vm.VM.ParseStateSummary:output_type -> vm.ParseStateSummaryResponse + 45, // 93: vm.VM.GetStateSummary:output_type -> vm.GetStateSummaryResponse + 18, // 94: vm.VM.BlockVerify:output_type -> vm.BlockVerifyResponse + 50, // 95: vm.VM.BlockAccept:output_type -> google.protobuf.Empty + 50, // 96: vm.VM.BlockReject:output_type -> google.protobuf.Empty + 47, // 97: vm.VM.StateSummaryAccept:output_type -> vm.StateSummaryAcceptResponse + 66, // [66:98] is the sub-list for method output_type + 34, // [34:66] is the sub-list for method input_type + 34, // [34:34] is the sub-list for extension type_name + 34, // [34:34] is the sub-list for extension extendee + 0, // [0:34] is the sub-list for field type_name } func init() { file_vm_vm_proto_init() } @@ -3526,7 +3769,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*InitializeResponse); i { + switch v := v.(*NetworkUpgrades); i { case 0: return &v.state case 1: @@ -3538,7 +3781,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SetStateRequest); i { + switch v := v.(*InitializeResponse); i { case 0: return &v.state case 1: @@ -3550,7 +3793,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SetStateResponse); i { + switch v := v.(*SetStateRequest); i { case 0: return &v.state case 1: @@ -3562,7 +3805,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CreateHandlersResponse); i { + switch v := v.(*SetStateResponse); i { case 0: return &v.state case 1: @@ -3574,7 +3817,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*Handler); i { + switch v := v.(*CreateHandlersResponse); i { case 0: return &v.state case 1: @@ -3586,7 +3829,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BuildBlockRequest); i { + switch v := v.(*Handler); i { case 0: return &v.state case 1: @@ -3598,7 +3841,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BuildBlockResponse); i { + switch v := v.(*BuildBlockRequest); i { case 0: return &v.state case 1: @@ -3610,7 +3853,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ParseBlockRequest); i { + switch v := v.(*BuildBlockResponse); i { case 0: return &v.state case 1: @@ -3622,7 +3865,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ParseBlockResponse); i { + switch v := v.(*ParseBlockRequest); i { case 0: return &v.state case 1: @@ -3634,7 +3877,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetBlockRequest); i { + switch v := v.(*ParseBlockResponse); i { case 0: return &v.state case 1: @@ -3646,7 +3889,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetBlockResponse); i { + switch v := v.(*GetBlockRequest); i { case 0: return &v.state case 1: @@ -3658,7 +3901,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SetPreferenceRequest); i { + switch v := v.(*GetBlockResponse); i { case 0: return &v.state case 1: @@ -3670,7 +3913,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[13].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BlockVerifyRequest); i { + switch v := v.(*SetPreferenceRequest); i { case 0: return &v.state case 1: @@ -3682,7 +3925,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[14].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BlockVerifyResponse); i { + switch v := v.(*BlockVerifyRequest); i { case 0: return &v.state case 1: @@ -3694,7 +3937,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[15].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BlockAcceptRequest); i { + switch v := v.(*BlockVerifyResponse); i { case 0: return &v.state case 1: @@ -3706,7 +3949,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[16].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BlockRejectRequest); i { + switch v := v.(*BlockAcceptRequest); i { case 0: return &v.state case 1: @@ -3718,7 +3961,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[17].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*HealthResponse); i { + switch v := v.(*BlockRejectRequest); i { case 0: return &v.state case 1: @@ -3730,7 +3973,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[18].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*VersionResponse); i { + switch v := v.(*HealthResponse); i { case 0: return &v.state case 1: @@ -3742,7 +3985,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[19].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AppRequestMsg); i { + switch v := v.(*VersionResponse); i { case 0: return &v.state case 1: @@ -3754,7 +3997,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[20].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AppRequestFailedMsg); i { + switch v := v.(*AppRequestMsg); i { case 0: return &v.state case 1: @@ -3766,7 +4009,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[21].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AppResponseMsg); i { + switch v := v.(*AppRequestFailedMsg); i { case 0: return &v.state case 1: @@ -3778,7 +4021,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[22].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*AppGossipMsg); i { + switch v := v.(*AppResponseMsg); i { case 0: return &v.state case 1: @@ -3790,7 +4033,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[23].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CrossChainAppRequestMsg); i { + switch v := v.(*AppGossipMsg); i { case 0: return &v.state case 1: @@ -3802,7 +4045,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CrossChainAppRequestFailedMsg); i { + switch v := v.(*CrossChainAppRequestMsg); i { case 0: return &v.state case 1: @@ -3814,7 +4057,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CrossChainAppResponseMsg); i { + switch v := v.(*CrossChainAppRequestFailedMsg); i { case 0: return &v.state case 1: @@ -3826,7 +4069,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ConnectedRequest); i { + switch v := v.(*CrossChainAppResponseMsg); i { case 0: return &v.state case 1: @@ -3838,7 +4081,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*DisconnectedRequest); i { + switch v := v.(*ConnectedRequest); i { case 0: return &v.state case 1: @@ -3850,7 +4093,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetAncestorsRequest); i { + switch v := v.(*DisconnectedRequest); i { case 0: return &v.state case 1: @@ -3862,7 +4105,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetAncestorsResponse); i { + switch v := v.(*GetAncestorsRequest); i { case 0: return &v.state case 1: @@ -3874,7 +4117,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BatchedParseBlockRequest); i { + switch v := v.(*GetAncestorsResponse); i { case 0: return &v.state case 1: @@ -3886,7 +4129,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*BatchedParseBlockResponse); i { + switch v := v.(*BatchedParseBlockRequest); i { case 0: return &v.state case 1: @@ -3898,7 +4141,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetBlockIDAtHeightRequest); i { + switch v := v.(*BatchedParseBlockResponse); i { case 0: return &v.state case 1: @@ -3910,7 +4153,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[33].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetBlockIDAtHeightResponse); i { + switch v := v.(*GetBlockIDAtHeightRequest); i { case 0: return &v.state case 1: @@ -3922,7 +4165,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GatherResponse); i { + switch v := v.(*GetBlockIDAtHeightResponse); i { case 0: return &v.state case 1: @@ -3934,7 +4177,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[35].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*StateSyncEnabledResponse); i { + switch v := v.(*GatherResponse); i { case 0: return &v.state case 1: @@ -3946,7 +4189,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[36].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetOngoingSyncStateSummaryResponse); i { + switch v := v.(*StateSyncEnabledResponse); i { case 0: return &v.state case 1: @@ -3958,7 +4201,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[37].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetLastStateSummaryResponse); i { + switch v := v.(*GetOngoingSyncStateSummaryResponse); i { case 0: return &v.state case 1: @@ -3970,7 +4213,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[38].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ParseStateSummaryRequest); i { + switch v := v.(*GetLastStateSummaryResponse); i { case 0: return &v.state case 1: @@ -3982,7 +4225,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[39].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*ParseStateSummaryResponse); i { + switch v := v.(*ParseStateSummaryRequest); i { case 0: return &v.state case 1: @@ -3994,7 +4237,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[40].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetStateSummaryRequest); i { + switch v := v.(*ParseStateSummaryResponse); i { case 0: return &v.state case 1: @@ -4006,7 +4249,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[41].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*GetStateSummaryResponse); i { + switch v := v.(*GetStateSummaryRequest); i { case 0: return &v.state case 1: @@ -4018,7 +4261,7 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[42].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*StateSummaryAcceptRequest); i { + switch v := v.(*GetStateSummaryResponse); i { case 0: return &v.state case 1: @@ -4030,6 +4273,18 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[43].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*StateSummaryAcceptRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_vm_vm_proto_msgTypes[44].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StateSummaryAcceptResponse); i { case 0: return &v.state @@ -4042,15 +4297,15 @@ func file_vm_vm_proto_init() { } } } - file_vm_vm_proto_msgTypes[6].OneofWrappers = []interface{}{} - file_vm_vm_proto_msgTypes[13].OneofWrappers = []interface{}{} + file_vm_vm_proto_msgTypes[7].OneofWrappers = []interface{}{} + file_vm_vm_proto_msgTypes[14].OneofWrappers = []interface{}{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_vm_vm_proto_rawDesc, NumEnums: 3, - NumMessages: 44, + NumMessages: 45, NumExtensions: 0, NumServices: 1, }, diff --git a/proto/vm/vm.proto b/proto/vm/vm.proto index 11dd0429c8d6..8386bf572bfa 100644 --- a/proto/vm/vm.proto +++ b/proto/vm/vm.proto @@ -116,6 +116,25 @@ message InitializeRequest { // the messenger, keystore, shared memory, blockchain alias, // subnet alias, and appSender services string server_addr = 14; + // network_upgrades_bytes is the json encoded network upgrades + NetworkUpgrades network_upgrades = 15; +} + +message NetworkUpgrades { + google.protobuf.Timestamp apricot_phase_1_time = 1; + google.protobuf.Timestamp apricot_phase_2_time = 2; + google.protobuf.Timestamp apricot_phase_3_time = 3; + google.protobuf.Timestamp apricot_phase_4_time = 4; + uint64 apricot_phase_4_min_p_chain_height = 5; + google.protobuf.Timestamp apricot_phase_5_time = 6; + google.protobuf.Timestamp apricot_phase_pre_6_time = 7; + google.protobuf.Timestamp apricot_phase_6_time = 8; + google.protobuf.Timestamp apricot_phase_post_6_time = 9; + google.protobuf.Timestamp banff_time = 10; + google.protobuf.Timestamp cortina_time = 11; + bytes cortina_x_chain_stop_vertex_id = 12; + google.protobuf.Timestamp durango_time = 13; + google.protobuf.Timestamp etna_time = 14; } message InitializeResponse { diff --git a/snow/context.go b/snow/context.go index 26fc67f213a8..2b0f896363c9 100644 --- a/snow/context.go +++ b/snow/context.go @@ -13,6 +13,7 @@ import ( "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/logging" @@ -31,11 +32,12 @@ type ContextInitializable interface { // [ChainID] is the ID of the chain this context exists within. // [NodeID] is the ID of this node type Context struct { - NetworkID uint32 - SubnetID ids.ID - ChainID ids.ID - NodeID ids.NodeID - PublicKey *bls.PublicKey + NetworkID uint32 + SubnetID ids.ID + ChainID ids.ID + NodeID ids.NodeID + PublicKey *bls.PublicKey + NetworkUpgrades upgrade.Config XChainID ids.ID CChainID ids.ID diff --git a/snow/snowtest/context.go b/snow/snowtest/context.go index 779636520376..734c120e556d 100644 --- a/snow/snowtest/context.go +++ b/snow/snowtest/context.go @@ -15,6 +15,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/validators/validatorstest" + "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/logging" @@ -78,11 +79,12 @@ func Context(tb testing.TB, chainID ids.ID) *snow.Context { } return &snow.Context{ - NetworkID: constants.UnitTestID, - SubnetID: constants.PrimaryNetworkID, - ChainID: chainID, - NodeID: ids.EmptyNodeID, - PublicKey: publicKey, + NetworkID: constants.UnitTestID, + SubnetID: constants.PrimaryNetworkID, + ChainID: chainID, + NodeID: ids.EmptyNodeID, + PublicKey: publicKey, + NetworkUpgrades: upgrade.Default, XChainID: XChainID, CChainID: CChainID, diff --git a/vms/rpcchainvm/vm_client.go b/vms/rpcchainvm/vm_client.go index c820f63ce4b9..1c4d491ce4d3 100644 --- a/vms/rpcchainvm/vm_client.go +++ b/vms/rpcchainvm/vm_client.go @@ -191,21 +191,39 @@ func (vm *VMClient) Initialize( zap.String("address", serverAddr), ) + networkUpgrades := &vmpb.NetworkUpgrades{ + ApricotPhase_1Time: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.ApricotPhase1Time), + ApricotPhase_2Time: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.ApricotPhase2Time), + ApricotPhase_3Time: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.ApricotPhase3Time), + ApricotPhase_4Time: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.ApricotPhase4Time), + ApricotPhase_4MinPChainHeight: chainCtx.NetworkUpgrades.ApricotPhase4MinPChainHeight, + ApricotPhase_5Time: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.ApricotPhase5Time), + ApricotPhasePre_6Time: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.ApricotPhasePre6Time), + ApricotPhase_6Time: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.ApricotPhase6Time), + ApricotPhasePost_6Time: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.ApricotPhasePost6Time), + BanffTime: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.BanffTime), + CortinaTime: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.CortinaTime), + CortinaXChainStopVertexId: chainCtx.NetworkUpgrades.CortinaXChainStopVertexID[:], + DurangoTime: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.DurangoTime), + EtnaTime: grpcutils.TimestampFromTime(chainCtx.NetworkUpgrades.EtnaTime), + } + resp, err := vm.client.Initialize(ctx, &vmpb.InitializeRequest{ - NetworkId: chainCtx.NetworkID, - SubnetId: chainCtx.SubnetID[:], - ChainId: chainCtx.ChainID[:], - NodeId: chainCtx.NodeID.Bytes(), - PublicKey: bls.PublicKeyToCompressedBytes(chainCtx.PublicKey), - XChainId: chainCtx.XChainID[:], - CChainId: chainCtx.CChainID[:], - AvaxAssetId: chainCtx.AVAXAssetID[:], - ChainDataDir: chainCtx.ChainDataDir, - GenesisBytes: genesisBytes, - UpgradeBytes: upgradeBytes, - ConfigBytes: configBytes, - DbServerAddr: dbServerAddr, - ServerAddr: serverAddr, + NetworkId: chainCtx.NetworkID, + SubnetId: chainCtx.SubnetID[:], + ChainId: chainCtx.ChainID[:], + NodeId: chainCtx.NodeID.Bytes(), + PublicKey: bls.PublicKeyToCompressedBytes(chainCtx.PublicKey), + NetworkUpgrades: networkUpgrades, + XChainId: chainCtx.XChainID[:], + CChainId: chainCtx.CChainID[:], + AvaxAssetId: chainCtx.AVAXAssetID[:], + ChainDataDir: chainCtx.ChainDataDir, + GenesisBytes: genesisBytes, + UpgradeBytes: upgradeBytes, + ConfigBytes: configBytes, + DbServerAddr: dbServerAddr, + ServerAddr: serverAddr, }) if err != nil { return err diff --git a/vms/rpcchainvm/vm_server.go b/vms/rpcchainvm/vm_server.go index 577aa95b9d08..cc46d819cccd 100644 --- a/vms/rpcchainvm/vm_server.go +++ b/vms/rpcchainvm/vm_server.go @@ -29,6 +29,7 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/common/appsender" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/snow/validators/gvalidators" + "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/logging" @@ -58,6 +59,7 @@ var ( originalStderr = os.Stderr errExpectedBlockWithVerifyContext = errors.New("expected block.WithVerifyContext") + errNilNetworkUpgradesPB = errors.New("network upgrades protobuf is nil") ) // VMServer is a VM that is managed over RPC. @@ -112,6 +114,12 @@ func (vm *VMServer) Initialize(ctx context.Context, req *vmpb.InitializeRequest) if err != nil { return nil, err } + + networkUpgrades, err := convertNetworkUpgrades(req.NetworkUpgrades) + if err != nil { + return nil, err + } + xChainID, err := ids.ToID(req.XChainId) if err != nil { return nil, err @@ -230,11 +238,12 @@ func (vm *VMServer) Initialize(ctx context.Context, req *vmpb.InitializeRequest) }() vm.ctx = &snow.Context{ - NetworkID: req.NetworkId, - SubnetID: subnetID, - ChainID: chainID, - NodeID: nodeID, - PublicKey: publicKey, + NetworkID: req.NetworkId, + SubnetID: subnetID, + ChainID: chainID, + NodeID: nodeID, + PublicKey: publicKey, + NetworkUpgrades: networkUpgrades, XChainID: xChainID, CChainID: cChainID, @@ -843,3 +852,80 @@ func (vm *VMServer) StateSummaryAccept( Err: errorToErrEnum[err], }, errorToRPCError(err) } + +func convertNetworkUpgrades(pbUpgrades *vmpb.NetworkUpgrades) (upgrade.Config, error) { + if pbUpgrades == nil { + return upgrade.Config{}, errNilNetworkUpgradesPB + } + + ap1, err := grpcutils.TimestampAsTime(pbUpgrades.ApricotPhase_1Time) + if err != nil { + return upgrade.Config{}, err + } + ap2, err := grpcutils.TimestampAsTime(pbUpgrades.ApricotPhase_2Time) + if err != nil { + return upgrade.Config{}, err + } + ap3, err := grpcutils.TimestampAsTime(pbUpgrades.ApricotPhase_3Time) + if err != nil { + return upgrade.Config{}, err + } + ap4, err := grpcutils.TimestampAsTime(pbUpgrades.ApricotPhase_4Time) + if err != nil { + return upgrade.Config{}, err + } + ap5, err := grpcutils.TimestampAsTime(pbUpgrades.ApricotPhase_5Time) + if err != nil { + return upgrade.Config{}, err + } + apPre6, err := grpcutils.TimestampAsTime(pbUpgrades.ApricotPhasePre_6Time) + if err != nil { + return upgrade.Config{}, err + } + ap6, err := grpcutils.TimestampAsTime(pbUpgrades.ApricotPhase_6Time) + if err != nil { + return upgrade.Config{}, err + } + apPost6, err := grpcutils.TimestampAsTime(pbUpgrades.ApricotPhasePost_6Time) + if err != nil { + return upgrade.Config{}, err + } + banff, err := grpcutils.TimestampAsTime(pbUpgrades.BanffTime) + if err != nil { + return upgrade.Config{}, err + } + cortina, err := grpcutils.TimestampAsTime(pbUpgrades.CortinaTime) + if err != nil { + return upgrade.Config{}, err + } + durango, err := grpcutils.TimestampAsTime(pbUpgrades.DurangoTime) + if err != nil { + return upgrade.Config{}, err + } + etna, err := grpcutils.TimestampAsTime(pbUpgrades.EtnaTime) + if err != nil { + return upgrade.Config{}, err + } + + cortinaXChainStopVertexID, err := ids.ToID(pbUpgrades.CortinaXChainStopVertexId) + if err != nil { + return upgrade.Config{}, err + } + + return upgrade.Config{ + ApricotPhase1Time: ap1, + ApricotPhase2Time: ap2, + ApricotPhase3Time: ap3, + ApricotPhase4Time: ap4, + ApricotPhase4MinPChainHeight: pbUpgrades.ApricotPhase_4MinPChainHeight, + ApricotPhase5Time: ap5, + ApricotPhasePre6Time: apPre6, + ApricotPhase6Time: ap6, + ApricotPhasePost6Time: apPost6, + BanffTime: banff, + CortinaTime: cortina, + CortinaXChainStopVertexID: cortinaXChainStopVertexID, + DurangoTime: durango, + EtnaTime: etna, + }, nil +} From 85d3bfeabda2799cfa7ab2c5a241f10b1c50c4bc Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 13 Aug 2024 13:23:54 -0400 Subject: [PATCH 10/69] Implement dynamic fee builder (#3232) Co-authored-by: Alberto Benegiamo --- wallet/chain/p/builder/builder.go | 380 +++++++++- wallet/chain/p/builder/context.go | 18 +- wallet/chain/p/builder_test.go | 1170 ++++++++++++++--------------- 3 files changed, 934 insertions(+), 634 deletions(-) diff --git a/wallet/chain/p/builder/builder.go b/wallet/chain/p/builder/builder.go index ee127ed71c22..e15267893fcf 100644 --- a/wallet/chain/p/builder/builder.go +++ b/wallet/chain/p/builder/builder.go @@ -22,6 +22,9 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" + + feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" + txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) var ( @@ -325,10 +328,27 @@ func (b *builder) NewBaseTx( toStake := map[ids.ID]uint64{} ops := common.NewOptions(options) + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + outputComplexity, err := txfee.OutputComplexity(outputs...) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicBaseTxComplexities.Add( + &memoComplexity, + &outputComplexity, + ) + if err != nil { + return nil, err + } + inputs, changeOutputs, _, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -343,7 +363,7 @@ func (b *builder) NewBaseTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: outputs, - Memo: ops.Memo(), + Memo: memo, }} return tx, b.initCtx(tx) } @@ -366,6 +386,7 @@ func (b *builder) NewAddValidatorTx( toBurn, toStake, 0, + feecomponent.Dimensions{}, nil, ops, ) @@ -405,10 +426,27 @@ func (b *builder) NewAddSubnetValidatorTx( return nil, err } + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + authComplexity, err := txfee.AuthComplexity(subnetAuth) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicAddSubnetValidatorTxComplexities.Add( + &memoComplexity, + &authComplexity, + ) + if err != nil { + return nil, err + } + inputs, outputs, _, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -422,7 +460,7 @@ func (b *builder) NewAddSubnetValidatorTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: outputs, - Memo: ops.Memo(), + Memo: memo, }}, SubnetValidator: *vdr, SubnetAuth: subnetAuth, @@ -446,10 +484,27 @@ func (b *builder) NewRemoveSubnetValidatorTx( return nil, err } + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + authComplexity, err := txfee.AuthComplexity(subnetAuth) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicRemoveSubnetValidatorTxComplexities.Add( + &memoComplexity, + &authComplexity, + ) + if err != nil { + return nil, err + } + inputs, outputs, _, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -489,6 +544,7 @@ func (b *builder) NewAddDelegatorTx( toBurn, toStake, 0, + feecomponent.Dimensions{}, nil, ops, ) @@ -531,10 +587,43 @@ func (b *builder) NewCreateChainTx( return nil, err } + memo := ops.Memo() + bandwidth, err := math.Mul(uint64(len(fxIDs)), ids.IDLen) + if err != nil { + return nil, err + } + bandwidth, err = math.Add(bandwidth, uint64(len(chainName))) + if err != nil { + return nil, err + } + bandwidth, err = math.Add(bandwidth, uint64(len(genesis))) + if err != nil { + return nil, err + } + bandwidth, err = math.Add(bandwidth, uint64(len(memo))) + if err != nil { + return nil, err + } + dynamicComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: bandwidth, + } + authComplexity, err := txfee.AuthComplexity(subnetAuth) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicCreateChainTxComplexities.Add( + &dynamicComplexity, + &authComplexity, + ) + if err != nil { + return nil, err + } + inputs, outputs, _, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -549,7 +638,7 @@ func (b *builder) NewCreateChainTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: outputs, - Memo: ops.Memo(), + Memo: memo, }}, SubnetID: subnetID, ChainName: chainName, @@ -569,11 +658,29 @@ func (b *builder) NewCreateSubnetTx( b.context.AVAXAssetID: b.context.StaticFeeConfig.CreateSubnetTxFee, } toStake := map[ids.ID]uint64{} + ops := common.NewOptions(options) + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + ownerComplexity, err := txfee.OwnerComplexity(owner) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicCreateSubnetTxComplexities.Add( + &memoComplexity, + &ownerComplexity, + ) + if err != nil { + return nil, err + } + inputs, outputs, _, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -588,7 +695,7 @@ func (b *builder) NewCreateSubnetTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: outputs, - Memo: ops.Memo(), + Memo: memo, }}, Owner: owner, } @@ -611,10 +718,32 @@ func (b *builder) NewTransferSubnetOwnershipTx( return nil, err } + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + authComplexity, err := txfee.AuthComplexity(subnetAuth) + if err != nil { + return nil, err + } + ownerComplexity, err := txfee.OwnerComplexity(owner) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicTransferSubnetOwnershipTxComplexities.Add( + &memoComplexity, + &authComplexity, + &ownerComplexity, + ) + if err != nil { + return nil, err + } + inputs, outputs, _, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -629,7 +758,7 @@ func (b *builder) NewTransferSubnetOwnershipTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: outputs, - Memo: ops.Memo(), + Memo: memo, }}, Subnet: subnetID, Owner: owner, @@ -713,6 +842,27 @@ func (b *builder) NewImportTx( }) } + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + inputComplexity, err := txfee.InputComplexity(importedInputs...) + if err != nil { + return nil, err + } + outputComplexity, err := txfee.OutputComplexity(outputs...) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicImportTxComplexities.Add( + &memoComplexity, + &inputComplexity, + &outputComplexity, + ) + if err != nil { + return nil, err + } + var ( toBurn = map[ids.ID]uint64{} toStake = map[ids.ID]uint64{} @@ -728,6 +878,7 @@ func (b *builder) NewImportTx( toBurn, toStake, excessAVAX, + complexity, to, ops, ) @@ -743,7 +894,7 @@ func (b *builder) NewImportTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: outputs, - Memo: ops.Memo(), + Memo: memo, }}, SourceChain: sourceChainID, ImportedInputs: importedInputs, @@ -770,10 +921,27 @@ func (b *builder) NewExportTx( toStake := map[ids.ID]uint64{} ops := common.NewOptions(options) + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + outputComplexity, err := txfee.OutputComplexity(outputs...) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicExportTxComplexities.Add( + &memoComplexity, + &outputComplexity, + ) + if err != nil { + return nil, err + } + inputs, changeOutputs, _, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -788,7 +956,7 @@ func (b *builder) NewExportTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: changeOutputs, - Memo: ops.Memo(), + Memo: memo, }}, DestinationChain: chainID, ExportedOutputs: outputs, @@ -829,6 +997,7 @@ func (b *builder) NewTransformSubnetTx( toBurn, toStake, 0, + feecomponent.Dimensions{}, nil, ops, ) @@ -882,11 +1051,39 @@ func (b *builder) NewAddPermissionlessValidatorTx( toStake := map[ids.ID]uint64{ assetID: vdr.Wght, } + ops := common.NewOptions(options) + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + signerComplexity, err := txfee.SignerComplexity(signer) + if err != nil { + return nil, err + } + validatorOwnerComplexity, err := txfee.OwnerComplexity(validationRewardsOwner) + if err != nil { + return nil, err + } + delegatorOwnerComplexity, err := txfee.OwnerComplexity(delegationRewardsOwner) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicAddPermissionlessValidatorTxComplexities.Add( + &memoComplexity, + &signerComplexity, + &validatorOwnerComplexity, + &delegatorOwnerComplexity, + ) + if err != nil { + return nil, err + } + inputs, baseOutputs, stakeOutputs, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -902,7 +1099,7 @@ func (b *builder) NewAddPermissionlessValidatorTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: baseOutputs, - Memo: ops.Memo(), + Memo: memo, }}, Validator: vdr.Validator, Subnet: vdr.Subnet, @@ -931,11 +1128,29 @@ func (b *builder) NewAddPermissionlessDelegatorTx( toStake := map[ids.ID]uint64{ assetID: vdr.Wght, } + ops := common.NewOptions(options) + memo := ops.Memo() + memoComplexity := feecomponent.Dimensions{ + feecomponent.Bandwidth: uint64(len(memo)), + } + ownerComplexity, err := txfee.OwnerComplexity(rewardsOwner) + if err != nil { + return nil, err + } + complexity, err := txfee.IntrinsicAddPermissionlessDelegatorTxComplexities.Add( + &memoComplexity, + &ownerComplexity, + ) + if err != nil { + return nil, err + } + inputs, baseOutputs, stakeOutputs, err := b.spend( toBurn, toStake, 0, + complexity, nil, ops, ) @@ -950,7 +1165,7 @@ func (b *builder) NewAddPermissionlessDelegatorTx( BlockchainID: constants.PlatformChainID, Ins: inputs, Outs: baseOutputs, - Memo: ops.Memo(), + Memo: memo, }}, Validator: vdr.Validator, Subnet: vdr.Subnet, @@ -1021,6 +1236,8 @@ func (b *builder) getBalance( // preferential ordering on the unlock times. // - [excessAVAX] contains the amount of extra AVAX that spend can produce in // the change outputs in addition to the consumed and not burned AVAX. +// - [complexity] contains the currently accrued transaction complexity that +// will be used to calculate the required fees to be burned. // - [ownerOverride] optionally specifies the output owners to use for the // unlocked AVAX change output if no additional AVAX was needed to be // burned. If this value is nil, the default change owner is used. @@ -1028,6 +1245,7 @@ func (b *builder) spend( toBurn map[ids.ID]uint64, toStake map[ids.ID]uint64, excessAVAX uint64, + complexity feecomponent.Dimensions, ownerOverride *secp256k1fx.OutputOwners, options *common.Options, ) ( @@ -1057,8 +1275,12 @@ func (b *builder) spend( } s := spendHelper{ - toBurn: toBurn, - toStake: toStake, + weights: b.context.ComplexityWeights, + gasPrice: b.context.GasPrice, + + toBurn: toBurn, + toStake: toStake, + complexity: complexity, // Initialize the return values with empty slices to preserve backward // compatibility of the json representation of transactions with no @@ -1086,7 +1308,7 @@ func (b *builder) spend( continue } - s.addInput(&avax.TransferableInput{ + err = s.addInput(&avax.TransferableInput{ UTXOID: utxo.UTXOID, Asset: utxo.Asset, In: &stakeable.LockIn{ @@ -1099,9 +1321,12 @@ func (b *builder) spend( }, }, }) + if err != nil { + return nil, nil, nil, err + } excess := s.consumeLockedAsset(assetID, out.Amt) - s.addStakedOutput(&avax.TransferableOutput{ + err = s.addStakedOutput(&avax.TransferableOutput{ Asset: utxo.Asset, Out: &stakeable.LockOut{ Locktime: locktime, @@ -1111,13 +1336,16 @@ func (b *builder) spend( }, }, }) + if err != nil { + return nil, nil, nil, err + } if excess == 0 { continue } // This input had extra value, so some of it must be returned - s.addChangeOutput(&avax.TransferableOutput{ + err = s.addChangeOutput(&avax.TransferableOutput{ Asset: utxo.Asset, Out: &stakeable.LockOut{ Locktime: locktime, @@ -1127,6 +1355,9 @@ func (b *builder) spend( }, }, }) + if err != nil { + return nil, nil, nil, err + } } // Add all the remaining stake amounts assuming unlocked UTXOs. @@ -1135,7 +1366,7 @@ func (b *builder) spend( continue } - s.addStakedOutput(&avax.TransferableOutput{ + err = s.addStakedOutput(&avax.TransferableOutput{ Asset: avax.Asset{ ID: assetID, }, @@ -1144,6 +1375,9 @@ func (b *builder) spend( OutputOwners: *changeOwner, }, }) + if err != nil { + return nil, nil, nil, err + } } // AVAX is handled last to account for fees. @@ -1165,7 +1399,7 @@ func (b *builder) spend( continue } - s.addInput(&avax.TransferableInput{ + err = s.addInput(&avax.TransferableInput{ UTXOID: utxo.UTXOID, Asset: utxo.Asset, In: &secp256k1fx.TransferInput{ @@ -1175,6 +1409,9 @@ func (b *builder) spend( }, }, }) + if err != nil { + return nil, nil, nil, err + } excess := s.consumeAsset(assetID, out.Amt) if excess == 0 { @@ -1182,19 +1419,28 @@ func (b *builder) spend( } // This input had extra value, so some of it must be returned - s.addChangeOutput(&avax.TransferableOutput{ + err = s.addChangeOutput(&avax.TransferableOutput{ Asset: utxo.Asset, Out: &secp256k1fx.TransferOutput{ Amt: excess, OutputOwners: *changeOwner, }, }) + if err != nil { + return nil, nil, nil, err + } } for _, utxo := range utxosByAVAXAssetID.requested { - // If we have consumed enough of the asset, then we have no need burn - // more. - if !s.shouldConsumeAsset(b.context.AVAXAssetID) { + requiredFee, err := s.calculateFee() + if err != nil { + return nil, nil, nil, err + } + + // If we don't need to burn or stake additional AVAX and we have + // consumed enough AVAX to pay the required fee, we should stop + // consuming UTXOs. + if !s.shouldConsumeAsset(b.context.AVAXAssetID) && excessAVAX >= requiredFee { break } @@ -1209,7 +1455,7 @@ func (b *builder) spend( continue } - s.addInput(&avax.TransferableInput{ + err = s.addInput(&avax.TransferableInput{ UTXOID: utxo.UTXOID, Asset: utxo.Asset, In: &secp256k1fx.TransferInput{ @@ -1219,6 +1465,9 @@ func (b *builder) spend( }, }, }) + if err != nil { + return nil, nil, nil, err + } excess := s.consumeAsset(b.context.AVAXAssetID, out.Amt) excessAVAX, err = math.Add(excessAVAX, excess) @@ -1235,17 +1484,41 @@ func (b *builder) spend( return nil, nil, nil, err } - if excessAVAX > 0 { - newOutput := &avax.TransferableOutput{ - Asset: avax.Asset{ - ID: b.context.AVAXAssetID, - }, - Out: &secp256k1fx.TransferOutput{ - Amt: excessAVAX, - OutputOwners: *ownerOverride, - }, - } - s.changeOutputs = append(s.changeOutputs, newOutput) + requiredFee, err := s.calculateFee() + if err != nil { + return nil, nil, nil, err + } + if excessAVAX < requiredFee { + return nil, nil, nil, fmt.Errorf( + "%w: provided UTXOs needed %d more nAVAX (%q)", + ErrInsufficientFunds, + requiredFee-excessAVAX, + b.context.AVAXAssetID, + ) + } + + secpExcessAVAXOutput := &secp256k1fx.TransferOutput{ + Amt: 0, // Populated later if used + OutputOwners: *ownerOverride, + } + excessAVAXOutput := &avax.TransferableOutput{ + Asset: avax.Asset{ + ID: b.context.AVAXAssetID, + }, + Out: secpExcessAVAXOutput, + } + if err := s.addOutputComplexity(excessAVAXOutput); err != nil { + return nil, nil, nil, err + } + + requiredFeeWithChange, err := s.calculateFee() + if err != nil { + return nil, nil, nil, err + } + if excessAVAX > requiredFeeWithChange { + // It is worth adding the change output + secpExcessAVAXOutput.Amt = excessAVAX - requiredFeeWithChange + s.changeOutputs = append(s.changeOutputs, excessAVAXOutput) } utils.Sort(s.inputs) // sort inputs @@ -1291,24 +1564,49 @@ func (b *builder) initCtx(tx txs.UnsignedTx) error { } type spendHelper struct { - toBurn map[ids.ID]uint64 - toStake map[ids.ID]uint64 + weights feecomponent.Dimensions + gasPrice feecomponent.GasPrice + + toBurn map[ids.ID]uint64 + toStake map[ids.ID]uint64 + complexity feecomponent.Dimensions inputs []*avax.TransferableInput changeOutputs []*avax.TransferableOutput stakeOutputs []*avax.TransferableOutput } -func (s *spendHelper) addInput(input *avax.TransferableInput) { +func (s *spendHelper) addInput(input *avax.TransferableInput) error { + newInputComplexity, err := txfee.InputComplexity(input) + if err != nil { + return err + } + s.complexity, err = s.complexity.Add(&newInputComplexity) + if err != nil { + return err + } + s.inputs = append(s.inputs, input) + return nil } -func (s *spendHelper) addChangeOutput(output *avax.TransferableOutput) { +func (s *spendHelper) addChangeOutput(output *avax.TransferableOutput) error { s.changeOutputs = append(s.changeOutputs, output) + return s.addOutputComplexity(output) } -func (s *spendHelper) addStakedOutput(output *avax.TransferableOutput) { +func (s *spendHelper) addStakedOutput(output *avax.TransferableOutput) error { s.stakeOutputs = append(s.stakeOutputs, output) + return s.addOutputComplexity(output) +} + +func (s *spendHelper) addOutputComplexity(output *avax.TransferableOutput) error { + newOutputComplexity, err := txfee.OutputComplexity(output) + if err != nil { + return err + } + s.complexity, err = s.complexity.Add(&newOutputComplexity) + return err } func (s *spendHelper) shouldConsumeLockedAsset(assetID ids.ID) bool { @@ -1341,6 +1639,14 @@ func (s *spendHelper) consumeAsset(assetID ids.ID, amount uint64) uint64 { return s.consumeLockedAsset(assetID, amount-toBurn) } +func (s *spendHelper) calculateFee() (uint64, error) { + gas, err := s.complexity.ToGas(s.weights) + if err != nil { + return 0, err + } + return gas.Cost(s.gasPrice) +} + func (s *spendHelper) verifyAssetsConsumed() error { for assetID, amount := range s.toStake { if amount == 0 { diff --git a/wallet/chain/p/builder/context.go b/wallet/chain/p/builder/context.go index 33eb5ecf0af5..3729edca2deb 100644 --- a/wallet/chain/p/builder/context.go +++ b/wallet/chain/p/builder/context.go @@ -12,15 +12,19 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/avm" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + + feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" + txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) const Alias = "P" type Context struct { - NetworkID uint32 - AVAXAssetID ids.ID - StaticFeeConfig fee.StaticConfig + NetworkID uint32 + AVAXAssetID ids.ID + StaticFeeConfig txfee.StaticConfig + ComplexityWeights feecomponent.Dimensions + GasPrice feecomponent.GasPrice } func NewContextFromURI(ctx context.Context, uri string) (*Context, error) { @@ -52,7 +56,7 @@ func NewContextFromClients( return &Context{ NetworkID: networkID, AVAXAssetID: asset.AssetID, - StaticFeeConfig: fee.StaticConfig{ + StaticFeeConfig: txfee.StaticConfig{ TxFee: uint64(txFees.TxFee), CreateSubnetTxFee: uint64(txFees.CreateSubnetTxFee), TransformSubnetTxFee: uint64(txFees.TransformSubnetTxFee), @@ -62,6 +66,10 @@ func NewContextFromClients( AddSubnetValidatorFee: uint64(txFees.AddSubnetValidatorFee), AddSubnetDelegatorFee: uint64(txFees.AddSubnetDelegatorFee), }, + + // TODO: Populate these fields once they are exposed by the API + ComplexityWeights: feecomponent.Dimensions{}, + GasPrice: 0, }, nil } diff --git a/wallet/chain/p/builder_test.go b/wallet/chain/p/builder_test.go index 67d51eaa7fcd..97ae0992025b 100644 --- a/wallet/chain/p/builder_test.go +++ b/wallet/chain/p/builder_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "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/crypto/secp256k1" @@ -20,24 +21,81 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/platformvm/txs" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/vms/types" "github.com/ava-labs/avalanchego/wallet/chain/p/builder" + "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common/utxotest" + + feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" + txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) var ( - testKeys = secp256k1.TestKeys() + subnetID = ids.GenerateTestID() + nodeID = ids.GenerateTestNodeID() + + testKeys = secp256k1.TestKeys() + subnetAuthKey = testKeys[0] + subnetAuthAddr = subnetAuthKey.Address() + subnetOwner = &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{subnetAuthAddr}, + } + importKey = testKeys[0] + importAddr = importKey.Address() + importOwner = &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{importAddr}, + } + rewardKey = testKeys[0] + rewardAddr = rewardKey.Address() + rewardsOwner = &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{rewardAddr}, + } + utxoKey = testKeys[1] + utxoAddr = utxoKey.Address() + utxoOwner = secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{utxoAddr}, + } - // We hard-code [avaxAssetID] and [subnetAssetID] to make - // ordering of UTXOs generated by [testUTXOsList] is reproducible + // We hard-code [avaxAssetID] and [subnetAssetID] to make ordering of UTXOs + // generated by [makeTestUTXOs] reproducible. avaxAssetID = ids.Empty.Prefix(1789) subnetAssetID = ids.Empty.Prefix(2024) + utxos = makeTestUTXOs(utxoKey) + + avaxOutput = &avax.TransferableOutput{ + Asset: avax.Asset{ID: avaxAssetID}, + Out: &secp256k1fx.TransferOutput{ + Amt: 7 * units.Avax, + OutputOwners: utxoOwner, + }, + } - testContext = &builder.Context{ + subnets = map[ids.ID]*txs.Tx{ + subnetID: { + Unsigned: &txs.CreateSubnetTx{ + Owner: subnetOwner, + }, + }, + } + + primaryNetworkPermissionlessStaker = &txs.SubnetValidator{ + Validator: txs.Validator{ + NodeID: nodeID, + End: uint64(time.Now().Add(time.Hour).Unix()), + Wght: 2 * units.Avax, + }, + Subnet: constants.PrimaryNetworkID, + } + + testContextPreEtna = &builder.Context{ NetworkID: constants.UnitTestID, AVAXAssetID: avaxAssetID, - StaticFeeConfig: fee.StaticConfig{ + StaticFeeConfig: txfee.StaticConfig{ TxFee: units.MicroAvax, CreateSubnetTxFee: 19 * units.MicroAvax, TransformSubnetTxFee: 789 * units.MicroAvax, @@ -48,509 +106,442 @@ var ( AddSubnetDelegatorFee: 9 * units.Avax, }, } -) - -// These tests create a tx, then verify that utxos included in the tx are -// exactly necessary to pay fees for it. - -func TestBaseTx(t *testing.T) { - var ( - require = require.New(t) + staticFeeCalculator = txfee.NewStaticCalculator( + testContextPreEtna.StaticFeeConfig, + ) - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, - }) - backend = NewBackend(testContext, chainUTXOs, nil) + testContextPostEtna = &builder.Context{ + NetworkID: constants.UnitTestID, + AVAXAssetID: avaxAssetID, - // builder - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr), testContext, backend) + ComplexityWeights: feecomponent.Dimensions{ + feecomponent.Bandwidth: 1, + feecomponent.DBRead: 10, + feecomponent.DBWrite: 100, + feecomponent.Compute: 1000, + }, + GasPrice: 1, + } + dynamicFeeCalculator = txfee.NewDynamicCalculator( + testContextPostEtna.ComplexityWeights, + testContextPostEtna.GasPrice, + ) - // data to build the transaction - outputToMove = &avax.TransferableOutput{ - Asset: avax.Asset{ID: avaxAssetID}, - Out: &secp256k1fx.TransferOutput{ - Amt: 7 * units.Avax, - OutputOwners: secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{utxoAddr}, - }, - }, - } + testEnvironmentPreEtna = []environment{ + { + name: "Pre-Etna", + context: testContextPreEtna, + feeCalculator: staticFeeCalculator, + }, + { + name: "Pre-Etna with memo", + context: testContextPreEtna, + feeCalculator: staticFeeCalculator, + memo: []byte("memo"), + }, + } + testEnvironmentPostEtna = []environment{ + { + name: "Post-Etna", + context: testContextPostEtna, + feeCalculator: dynamicFeeCalculator, + }, + { + name: "Post-Etna with memo", + context: testContextPostEtna, + feeCalculator: dynamicFeeCalculator, + memo: []byte("memo"), + }, + } + testEnvironment = utils.Join( + testEnvironmentPreEtna, + testEnvironmentPostEtna, ) +) - utx, err := builder.NewBaseTx([]*avax.TransferableOutput{outputToMove}) - require.NoError(err) +type environment struct { + name string + context *builder.Context + feeCalculator txfee.Calculator + memo []byte +} - // check that the output is included in the transaction - require.Contains(utx.Outs, outputToMove) +// These tests create a tx, then verify that utxos included in the tx are +// exactly necessary to pay fees for it. - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.TxFee, - }, - ), - addInputAmounts(utx.Ins), - ) +func TestBaseTx(t *testing.T) { + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, nil) + builder = builder.New(set.Of(utxoAddr), e.context, backend) + ) + + utx, err := builder.NewBaseTx( + []*avax.TransferableOutput{avaxOutput}, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Contains(utx.Outs, avaxOutput) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx, + nil, + nil, + nil, + ) + }) + } } func TestAddSubnetValidatorTx(t *testing.T) { - var ( - require = require.New(t) + subnetValidator := &txs.SubnetValidator{ + Validator: txs.Validator{ + NodeID: nodeID, + End: uint64(time.Now().Add(time.Hour).Unix()), + }, + Subnet: subnetID, + } - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, subnets) + builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) + ) + + utx, err := builder.NewAddSubnetValidatorTx( + subnetValidator, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(*subnetValidator, utx.SubnetValidator) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + nil, + nil, + ) }) - - subnetID = ids.GenerateTestID() - subnetAuthKey = testKeys[0] - subnetAuthAddr = subnetAuthKey.Address() - subnetOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{subnetAuthAddr}, - } - subnets = map[ids.ID]*txs.Tx{ - subnetID: { - Unsigned: &txs.CreateSubnetTx{ - Owner: subnetOwner, - }, - }, - } - - backend = NewBackend(testContext, chainUTXOs, subnets) - - // builder - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), testContext, backend) - - // data to build the transaction - subnetValidator = &txs.SubnetValidator{ - Validator: txs.Validator{ - NodeID: ids.GenerateTestNodeID(), - End: uint64(time.Now().Add(time.Hour).Unix()), - }, - Subnet: subnetID, - } - ) - - // build the transaction - utx, err := builder.NewAddSubnetValidatorTx(subnetValidator) - require.NoError(err) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.AddSubnetValidatorFee, - }, - ), - addInputAmounts(utx.Ins), - ) + } } func TestRemoveSubnetValidatorTx(t *testing.T) { - var ( - require = require.New(t) - - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, subnets) + builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) + ) + + utx, err := builder.NewRemoveSubnetValidatorTx( + nodeID, + subnetID, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(nodeID, utx.NodeID) + require.Equal(subnetID, utx.Subnet) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + nil, + nil, + ) }) - - subnetID = ids.GenerateTestID() - subnetAuthKey = testKeys[0] - subnetAuthAddr = subnetAuthKey.Address() - subnetOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{subnetAuthAddr}, - } - subnets = map[ids.ID]*txs.Tx{ - subnetID: { - Unsigned: &txs.CreateSubnetTx{ - Owner: subnetOwner, - }, - }, - } - - backend = NewBackend(testContext, chainUTXOs, subnets) - - // builder - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), testContext, backend) - ) - - // build the transaction - utx, err := builder.NewRemoveSubnetValidatorTx( - ids.GenerateTestNodeID(), - subnetID, - ) - require.NoError(err) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.TxFee, - }, - ), - addInputAmounts(utx.Ins), - ) + } } func TestCreateChainTx(t *testing.T) { var ( - require = require.New(t) - - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, - }) - - subnetID = ids.GenerateTestID() - subnetAuthKey = testKeys[0] - subnetAuthAddr = subnetAuthKey.Address() - subnetOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{subnetAuthAddr}, - } - subnets = map[ids.ID]*txs.Tx{ - subnetID: { - Unsigned: &txs.CreateSubnetTx{ - Owner: subnetOwner, - }, - }, - } - - backend = NewBackend(testContext, chainUTXOs, subnets) - - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), testContext, backend) - - // data to build the transaction genesisBytes = []byte{'a', 'b', 'c'} vmID = ids.GenerateTestID() fxIDs = []ids.ID{ids.GenerateTestID()} chainName = "dummyChain" ) - // build the transaction - utx, err := builder.NewCreateChainTx( - subnetID, - genesisBytes, - vmID, - fxIDs, - chainName, - ) - require.NoError(err) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.CreateBlockchainTxFee, - }, - ), - addInputAmounts(utx.Ins), - ) + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, subnets) + builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) + ) + + utx, err := builder.NewCreateChainTx( + subnetID, + genesisBytes, + vmID, + fxIDs, + chainName, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(subnetID, utx.SubnetID) + require.Equal(genesisBytes, utx.GenesisData) + require.Equal(vmID, utx.VMID) + require.ElementsMatch(fxIDs, utx.FxIDs) + require.Equal(chainName, utx.ChainName) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + nil, + nil, + ) + }) + } } func TestCreateSubnetTx(t *testing.T) { - var ( - require = require.New(t) - - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, subnets) + builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) + ) + + utx, err := builder.NewCreateSubnetTx( + subnetOwner, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(subnetOwner, utx.Owner) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + nil, + nil, + ) }) - - subnetID = ids.GenerateTestID() - subnetAuthKey = testKeys[0] - subnetAuthAddr = subnetAuthKey.Address() - subnetOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{subnetAuthAddr}, - } - subnets = map[ids.ID]*txs.Tx{ - subnetID: { - Unsigned: &txs.CreateSubnetTx{ - Owner: subnetOwner, - }, - }, - } - - backend = NewBackend(testContext, chainUTXOs, subnets) - - // builder - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), testContext, backend) - ) - - // build the transaction - utx, err := builder.NewCreateSubnetTx(subnetOwner) - require.NoError(err) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.CreateSubnetTxFee, - }, - ), - addInputAmounts(utx.Ins), - ) + } } func TestTransferSubnetOwnershipTx(t *testing.T) { - var ( - require = require.New(t) - - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, subnets) + builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) + ) + + utx, err := builder.NewTransferSubnetOwnershipTx( + subnetID, + subnetOwner, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(subnetID, utx.Subnet) + require.Equal(subnetOwner, utx.Owner) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + nil, + nil, + ) }) - - subnetID = ids.GenerateTestID() - subnetAuthKey = testKeys[0] - subnetAuthAddr = subnetAuthKey.Address() - subnetOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{subnetAuthAddr}, - } - subnets = map[ids.ID]*txs.Tx{ - subnetID: { - Unsigned: &txs.CreateSubnetTx{ - Owner: subnetOwner, - }, - }, - } - - backend = NewBackend(testContext, chainUTXOs, subnets) - - // builder - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), testContext, backend) - ) - - // build the transaction - utx, err := builder.NewTransferSubnetOwnershipTx( - subnetID, - subnetOwner, - ) - require.NoError(err) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.TxFee, - }, - ), - addInputAmounts(utx.Ins), - ) + } } func TestImportTx(t *testing.T) { var ( - require = require.New(t) - - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) sourceChainID = ids.GenerateTestID() importedUTXOs = utxos[:1] - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, - sourceChainID: importedUTXOs, - }) - - backend = NewBackend(testContext, chainUTXOs, nil) - - // builder - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr), testContext, backend) - - // data to build the transaction - importKey = testKeys[0] - importTo = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ - importKey.Address(), - }, - } ) - // build the transaction - utx, err := builder.NewImportTx( - sourceChainID, - importTo, - ) - require.NoError(err) - - require.Empty(utx.Ins) // we spend the imported input (at least partially) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.TxFee, - }, - ), - addInputAmounts(utx.Ins, utx.ImportedInputs), - ) + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + sourceChainID: importedUTXOs, + }) + backend = NewBackend(e.context, chainUTXOs, nil) + builder = builder.New(set.Of(utxoAddr), e.context, backend) + ) + + utx, err := builder.NewImportTx( + sourceChainID, + importOwner, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(sourceChainID, utx.SourceChain) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + require.Empty(utx.Ins) // The imported input should be sufficient for fees + require.Len(utx.ImportedInputs, len(importedUTXOs)) // All utxos should be imported + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + utx.ImportedInputs, + nil, + nil, + ) + }) + } } func TestExportTx(t *testing.T) { - var ( - require = require.New(t) - - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, + exportedOutputs := []*avax.TransferableOutput{avaxOutput} + + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, nil) + builder = builder.New(set.Of(utxoAddr), e.context, backend) + ) + + utx, err := builder.NewExportTx( + subnetID, + exportedOutputs, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(subnetID, utx.DestinationChain) + require.ElementsMatch(exportedOutputs, utx.ExportedOutputs) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + utx.ExportedOutputs, + nil, + ) }) - backend = NewBackend(testContext, chainUTXOs, nil) - - // builder - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr), testContext, backend) - - // data to build the transaction - subnetID = ids.GenerateTestID() - exportedOutputs = []*avax.TransferableOutput{{ - Asset: avax.Asset{ID: avaxAssetID}, - Out: &secp256k1fx.TransferOutput{ - Amt: 7 * units.Avax, - OutputOwners: secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{utxoAddr}, - }, - }, - }} - ) - - // build the transaction - utx, err := builder.NewExportTx( - subnetID, - exportedOutputs, - ) - require.NoError(err) - - require.Equal(utx.ExportedOutputs, exportedOutputs) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs, utx.ExportedOutputs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.TxFee, - }, - ), - addInputAmounts(utx.Ins), - ) + } } func TestTransformSubnetTx(t *testing.T) { - var ( - require = require.New(t) - - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, - }) - - subnetID = ids.GenerateTestID() - subnetAuthKey = testKeys[0] - subnetAuthAddr = subnetAuthKey.Address() - subnetOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{subnetAuthAddr}, - } - subnets = map[ids.ID]*txs.Tx{ - subnetID: { - Unsigned: &txs.CreateSubnetTx{ - Owner: subnetOwner, + const ( + initialSupply = 40 * units.MegaAvax + maxSupply = 100 * units.MegaAvax + minConsumptionRate uint64 = reward.PercentDenominator + maxConsumptionRate uint64 = reward.PercentDenominator + minValidatorStake uint64 = 1 + maxValidatorStake = 100 * units.MegaAvax + minStakeDuration = time.Second + maxStakeDuration = 365 * 24 * time.Hour + minDelegationFee uint32 = 0 + minDelegatorStake uint64 = 1 + maxValidatorWeightFactor byte = 5 + uptimeRequirement uint32 = .80 * reward.PercentDenominator + ) + + // TransformSubnetTx is not valid to be issued post-Etna + for _, e := range testEnvironmentPreEtna { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, subnets) + builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) + ) + + utx, err := builder.NewTransformSubnetTx( + subnetID, + subnetAssetID, + initialSupply, + maxSupply, + minConsumptionRate, + maxConsumptionRate, + minValidatorStake, + maxValidatorStake, + minStakeDuration, + maxStakeDuration, + minDelegationFee, + minDelegatorStake, + maxValidatorWeightFactor, + uptimeRequirement, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(subnetID, utx.Subnet) + require.Equal(subnetAssetID, utx.AssetID) + require.Equal(initialSupply, utx.InitialSupply) + require.Equal(maxSupply, utx.MaximumSupply) + require.Equal(minConsumptionRate, utx.MinConsumptionRate) + require.Equal(minValidatorStake, utx.MinValidatorStake) + require.Equal(maxValidatorStake, utx.MaxValidatorStake) + require.Equal(uint32(minStakeDuration/time.Second), utx.MinStakeDuration) + require.Equal(uint32(maxStakeDuration/time.Second), utx.MaxStakeDuration) + require.Equal(minDelegationFee, utx.MinDelegationFee) + require.Equal(minDelegatorStake, utx.MinDelegatorStake) + require.Equal(maxValidatorWeightFactor, utx.MaxValidatorWeightFactor) + require.Equal(uptimeRequirement, utx.UptimeRequirement) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + nil, + map[ids.ID]uint64{ + subnetAssetID: maxSupply - initialSupply, }, - }, - } - - backend = NewBackend(testContext, chainUTXOs, subnets) - - // builder - utxoAddr = utxosKey.Address() - builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), testContext, backend) - - // data to build the transaction - initialSupply = 40 * units.MegaAvax - maxSupply = 100 * units.MegaAvax - ) - - // build the transaction - utx, err := builder.NewTransformSubnetTx( - subnetID, - subnetAssetID, - initialSupply, // initial supply - maxSupply, // max supply - reward.PercentDenominator, // min consumption rate - reward.PercentDenominator, // max consumption rate - 1, // min validator stake - 100*units.MegaAvax, // max validator stake - time.Second, // min stake duration - 365*24*time.Hour, // max stake duration - 0, // min delegation fee - 1, // min delegator stake - 5, // max validator weight factor - .80*reward.PercentDenominator, // uptime requirement - ) - require.NoError(err) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.TransformSubnetTxFee, - subnetAssetID: maxSupply - initialSupply, - }, - ), - addInputAmounts(utx.Ins), - ) + ) + }) + } } func TestAddPermissionlessValidatorTx(t *testing.T) { - var ( - require = require.New(t) - - // backend - utxosOffset uint64 = 2024 - utxosKey = testKeys[1] - utxosAddr = utxosKey.Address() - ) + var utxosOffset uint64 = 2024 makeUTXO := func(amount uint64) *avax.UTXO { utxosOffset++ return &avax.UTXO{ @@ -560,159 +551,128 @@ func TestAddPermissionlessValidatorTx(t *testing.T) { }, Asset: avax.Asset{ID: avaxAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: amount, - OutputOwners: secp256k1fx.OutputOwners{ - Locktime: 0, - Addrs: []ids.ShortID{utxosAddr}, - Threshold: 1, - }, + Amt: amount, + OutputOwners: utxoOwner, }, } } var ( utxos = []*avax.UTXO{ - makeUTXO(testContext.StaticFeeConfig.AddPrimaryNetworkValidatorFee), // UTXO to pay the fee - makeUTXO(1 * units.NanoAvax), // small UTXO - makeUTXO(9 * units.Avax), // large UTXO + makeUTXO(testContextPreEtna.StaticFeeConfig.AddPrimaryNetworkValidatorFee), // UTXO to pay the fee + makeUTXO(1 * units.NanoAvax), // small UTXO + makeUTXO(9 * units.Avax), // large UTXO } - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, - }) - backend = NewBackend(testContext, chainUTXOs, nil) - - // builder - utxoAddr = utxosKey.Address() - rewardKey = testKeys[0] - rewardAddr = rewardKey.Address() - builder = builder.New(set.Of(utxoAddr, rewardAddr), testContext, backend) - - // data to build the transaction - validationRewardsOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ - rewardAddr, - }, - } - delegationRewardsOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ - rewardAddr, - }, - } - ) - - sk, err := bls.NewSecretKey() - require.NoError(err) - - // build the transaction - utx, err := builder.NewAddPermissionlessValidatorTx( - &txs.SubnetValidator{ - Validator: txs.Validator{ - NodeID: ids.GenerateTestNodeID(), - End: uint64(time.Now().Add(time.Hour).Unix()), - Wght: 2 * units.Avax, - }, - Subnet: constants.PrimaryNetworkID, - }, - signer.NewProofOfPossession(sk), - avaxAssetID, - validationRewardsOwner, - delegationRewardsOwner, - reward.PercentDenominator, - ) - require.NoError(err) - - // check stake amount - require.Equal( - map[ids.ID]uint64{ - avaxAssetID: 2 * units.Avax, - }, - addOutputAmounts(utx.StakeOuts), - ) - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs, utx.StakeOuts), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.AddPrimaryNetworkValidatorFee, - }, - ), - addInputAmounts(utx.Ins), + validationRewardsOwner = rewardsOwner + delegationRewardsOwner = rewardsOwner + delegationShares uint32 = reward.PercentDenominator ) - // Outputs should be merged if possible. For example, if there are two - // unlocked inputs consumed for staking, this should only produce one staked - // output. - require.Len(utx.StakeOuts, 1) + sk, err := bls.NewSecretKey() + require.NoError(t, err) + + pop := signer.NewProofOfPossession(sk) + + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, nil) + builder = builder.New(set.Of(utxoAddr, rewardAddr), e.context, backend) + ) + + utx, err := builder.NewAddPermissionlessValidatorTx( + primaryNetworkPermissionlessStaker, + pop, + avaxAssetID, + validationRewardsOwner, + delegationRewardsOwner, + delegationShares, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(primaryNetworkPermissionlessStaker.Validator, utx.Validator) + require.Equal(primaryNetworkPermissionlessStaker.Subnet, utx.Subnet) + require.Equal(pop, utx.Signer) + // Outputs should be merged if possible. For example, if there are two + // unlocked inputs consumed for staking, this should only produce one staked + // output. + require.Len(utx.StakeOuts, 1) + // check stake amount + require.Equal( + map[ids.ID]uint64{ + avaxAssetID: primaryNetworkPermissionlessStaker.Wght, + }, + addOutputAmounts(utx.StakeOuts), + ) + require.Equal(validationRewardsOwner, utx.ValidatorRewardsOwner) + require.Equal(delegationRewardsOwner, utx.DelegatorRewardsOwner) + require.Equal(delegationShares, utx.DelegationShares) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + utx.StakeOuts, + nil, + ) + }) + } } func TestAddPermissionlessDelegatorTx(t *testing.T) { - var ( - require = require.New(t) - - // backend - utxosKey = testKeys[1] - utxos = makeTestUTXOs(utxosKey) - chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ - constants.PlatformChainID: utxos, + for _, e := range testEnvironment { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = NewBackend(e.context, chainUTXOs, nil) + builder = builder.New(set.Of(utxoAddr, rewardAddr), e.context, backend) + ) + + utx, err := builder.NewAddPermissionlessDelegatorTx( + primaryNetworkPermissionlessStaker, + avaxAssetID, + rewardsOwner, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(primaryNetworkPermissionlessStaker.Validator, utx.Validator) + require.Equal(primaryNetworkPermissionlessStaker.Subnet, utx.Subnet) + // check stake amount + require.Equal( + map[ids.ID]uint64{ + avaxAssetID: primaryNetworkPermissionlessStaker.Wght, + }, + addOutputAmounts(utx.StakeOuts), + ) + require.Equal(rewardsOwner, utx.DelegationRewardsOwner) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + utx.StakeOuts, + nil, + ) }) - backend = NewBackend(testContext, chainUTXOs, nil) - - // builder - utxoAddr = utxosKey.Address() - rewardKey = testKeys[0] - rewardAddr = rewardKey.Address() - builder = builder.New(set.Of(utxoAddr, rewardAddr), testContext, backend) - - // data to build the transaction - rewardsOwner = &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ - rewardAddr, - }, - } - ) - - // build the transaction - utx, err := builder.NewAddPermissionlessDelegatorTx( - &txs.SubnetValidator{ - Validator: txs.Validator{ - NodeID: ids.GenerateTestNodeID(), - End: uint64(time.Now().Add(time.Hour).Unix()), - Wght: 2 * units.Avax, - }, - Subnet: constants.PrimaryNetworkID, - }, - avaxAssetID, - rewardsOwner, - ) - require.NoError(err) - - // check stake amount - require.Equal( - map[ids.ID]uint64{ - avaxAssetID: 2 * units.Avax, - }, - addOutputAmounts(utx.StakeOuts), - ) - - // check fee calculation - require.Equal( - addAmounts( - addOutputAmounts(utx.Outs, utx.StakeOuts), - map[ids.ID]uint64{ - avaxAssetID: testContext.StaticFeeConfig.AddPrimaryNetworkDelegatorFee, - }, - ), - addInputAmounts(utx.Ins), - ) + } } func makeTestUTXOs(utxosKey *secp256k1.PrivateKey) []*avax.UTXO { - // Note: we avoid ids.GenerateTestNodeID here to make sure that UTXO IDs won't change - // run by run. This simplifies checking what utxos are included in the built txs. + // Note: we avoid ids.GenerateTestNodeID here to make sure that UTXO IDs + // won't change run by run. This simplifies checking what utxos are included + // in the built txs. const utxosOffset uint64 = 2024 utxosAddr := utxosKey.Address() @@ -799,6 +759,32 @@ func makeTestUTXOs(utxosKey *secp256k1.PrivateKey) []*avax.UTXO { } } +// requireFeeIsCorrect calculates the required fee for the unsigned transaction +// and verifies that the burned amount is exactly the required fee. +func requireFeeIsCorrect( + require *require.Assertions, + feeCalculator txfee.Calculator, + utx txs.UnsignedTx, + baseTx *avax.BaseTx, + additionalIns []*avax.TransferableInput, + additionalOuts []*avax.TransferableOutput, + additionalFee map[ids.ID]uint64, +) { + amountConsumed := addInputAmounts(baseTx.Ins, additionalIns) + amountProduced := addOutputAmounts(baseTx.Outs, additionalOuts) + + expectedFee, err := feeCalculator.CalculateFee(utx) + require.NoError(err) + expectedAmountBurned := addAmounts( + map[ids.ID]uint64{ + avaxAssetID: expectedFee, + }, + additionalFee, + ) + expectedAmountConsumed := addAmounts(amountProduced, expectedAmountBurned) + require.Equal(expectedAmountConsumed, amountConsumed) +} + func addAmounts(allAmounts ...map[ids.ID]uint64) map[ids.ID]uint64 { amounts := make(map[ids.ID]uint64) for _, amountsToAdd := range allAmounts { From 7520071656afce32d6f9a0bf51fa390e62846fb5 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 13 Aug 2024 11:01:38 -0700 Subject: [PATCH 11/69] bump coreth past upgrade schedule refactor (#3278) --- go.mod | 6 +-- go.sum | 12 +++--- tests/fixture/tmpnet/genesis.go | 4 +- tests/fixture/tmpnet/network.go | 28 ++++++------ tests/upgrade/upgrade_test.go | 22 ++++++++++ version/constants.go | 75 --------------------------------- 6 files changed, 50 insertions(+), 97 deletions(-) diff --git a/go.mod b/go.mod index f440ad419e1e..bc1e96772e80 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/DataDog/zstd v1.5.2 github.com/NYTimes/gziphandler v1.1.1 github.com/antithesishq/antithesis-sdk-go v0.3.8 - github.com/ava-labs/coreth v0.13.8-0.20240802110637-b3e5088d062d + github.com/ava-labs/coreth v0.13.8-fix-genesis-upgrade github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95 github.com/btcsuite/btcd/btcutil v1.1.3 github.com/cockroachdb/pebble v0.0.0-20230928194634-aa077af62593 @@ -34,7 +34,7 @@ require ( github.com/nbutton23/zxcvbn-go v0.0.0-20180912185939-ae427f1e4c1d github.com/onsi/ginkgo/v2 v2.13.1 github.com/pires/go-proxyproto v0.6.2 - github.com/prometheus/client_golang v1.14.0 + github.com/prometheus/client_golang v1.16.0 github.com/prometheus/client_model v0.3.0 github.com/prometheus/common v0.42.0 github.com/rs/cors v1.7.0 @@ -156,7 +156,7 @@ require ( github.com/zondax/ledger-go v0.14.3 // indirect go.opentelemetry.io/otel/metric v1.22.0 // indirect go.opentelemetry.io/proto/otlp v1.0.0 // indirect - go.uber.org/multierr v1.10.0 // indirect + go.uber.org/multierr v1.11.0 // indirect golang.org/x/sys v0.18.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/tools v0.17.0 // indirect diff --git a/go.sum b/go.sum index 4f50be7c1b7c..1f06a819fe3a 100644 --- a/go.sum +++ b/go.sum @@ -62,8 +62,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/antithesishq/antithesis-sdk-go v0.3.8 h1:OvGoHxIcOXFJLyn9IJQ5DzByZ3YVAWNBc394ObzDRb8= github.com/antithesishq/antithesis-sdk-go v0.3.8/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/coreth v0.13.8-0.20240802110637-b3e5088d062d h1:klPTcKVvqfA2KSKaRvQAO56Pd4XAqGhwgMTQ6/W+w7w= -github.com/ava-labs/coreth v0.13.8-0.20240802110637-b3e5088d062d/go.mod h1:tXDujonxXFOF6oK5HS2EmgtSXJK3Gy6RpZxb5WzR9rM= +github.com/ava-labs/coreth v0.13.8-fix-genesis-upgrade h1:xWsvSGtZcGna3B2BLU2BvK3qskbcc9ZNtgC0ck91CkI= +github.com/ava-labs/coreth v0.13.8-fix-genesis-upgrade/go.mod h1:Ouul9dJouniUIJVX1gDqx8CrHyGvmwZkK28mrgKb/4I= github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95 h1:dOVbtdnZL++pENdTCNZ1nu41eYDQkTML4sWebDnnq8c= github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95/go.mod h1:pJxaT9bUgeRNVmNRgtCHb7sFDIRKy7CzTQVi8gGNT6g= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= @@ -498,8 +498,8 @@ github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qR github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= -github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= +github.com/prometheus/client_golang v1.16.0 h1:yk/hx9hDbrGHovbci4BY+pRMfSuuat626eFsHb7tmT8= +github.com/prometheus/client_golang v1.16.0/go.mod h1:Zsulrv/L9oM40tJ7T815tM89lFEugiJ9HzIqaAx4LKc= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.3.0 h1:UBgGFHqYdG/TPFD1B1ogZywDqEkwp3fBMvqdiQ7Xew4= github.com/prometheus/client_model v0.3.0/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= @@ -644,8 +644,8 @@ go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/mock v0.4.0 h1:VcM4ZOtdbR4f6VXfiOpwpVJDL6lCReaZ6mw31wqh7KU= go.uber.org/mock v0.4.0/go.mod h1:a6FSlNadKUHUa9IP5Vyt1zh4fC7uAwxMutEAscFbkZc= -go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= -go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= golang.org/x/crypto v0.0.0-20170613210332-850760c427c5/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= diff --git a/tests/fixture/tmpnet/genesis.go b/tests/fixture/tmpnet/genesis.go index a9c85fe8b441..aa308be6ee71 100644 --- a/tests/fixture/tmpnet/genesis.go +++ b/tests/fixture/tmpnet/genesis.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/avalanchego/genesis" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting/address" @@ -149,7 +150,8 @@ func NewTestGenesis( // Define C-Chain genesis cChainGenesis := &core.Genesis{ Config: params.AvalancheLocalChainConfig, - Difficulty: big.NewInt(0), // Difficulty is a mandatory field + Difficulty: big.NewInt(0), // Difficulty is a mandatory field + Timestamp: uint64(upgrade.InitiallyActiveTime.Unix()), // This time enables Avalanche upgrades by default GasLimit: defaultGasLimit, Alloc: cChainBalances, } diff --git a/tests/fixture/tmpnet/network.go b/tests/fixture/tmpnet/network.go index 61f738e3f30d..5e85c020386e 100644 --- a/tests/fixture/tmpnet/network.go +++ b/tests/fixture/tmpnet/network.go @@ -298,18 +298,7 @@ func (n *Network) Create(rootDir string) error { } if n.NetworkID == 0 && n.Genesis == nil { - // Pre-fund known legacy keys to support ad-hoc testing. Usage of a legacy key will - // require knowing the key beforehand rather than retrieving it from the set of pre-funded - // keys exposed by a network. Since allocation will not be exclusive, a test using a - // legacy key is unlikely to be a good candidate for parallel execution. - keysToFund := []*secp256k1.PrivateKey{ - genesis.VMRQKey, - genesis.EWOQKey, - HardhatKey, - } - keysToFund = append(keysToFund, n.PreFundedKeys...) - - genesis, err := NewTestGenesis(defaultNetworkID, n.Nodes, keysToFund) + genesis, err := n.DefaultGenesis() if err != nil { return err } @@ -328,6 +317,21 @@ func (n *Network) Create(rootDir string) error { return n.Write() } +func (n *Network) DefaultGenesis() (*genesis.UnparsedConfig, error) { + // Pre-fund known legacy keys to support ad-hoc testing. Usage of a legacy key will + // require knowing the key beforehand rather than retrieving it from the set of pre-funded + // keys exposed by a network. Since allocation will not be exclusive, a test using a + // legacy key is unlikely to be a good candidate for parallel execution. + keysToFund := []*secp256k1.PrivateKey{ + genesis.VMRQKey, + genesis.EWOQKey, + HardhatKey, + } + keysToFund = append(keysToFund, n.PreFundedKeys...) + + return NewTestGenesis(defaultNetworkID, n.Nodes, keysToFund) +} + // Starts the specified nodes func (n *Network) StartNodes(ctx context.Context, w io.Writer, nodesToStart ...*Node) error { if len(nodesToStart) == 0 { diff --git a/tests/upgrade/upgrade_test.go b/tests/upgrade/upgrade_test.go index 32c76fd6dd0f..374af3385f83 100644 --- a/tests/upgrade/upgrade_test.go +++ b/tests/upgrade/upgrade_test.go @@ -4,15 +4,18 @@ package upgrade import ( + "encoding/json" "flag" "fmt" "testing" + "github.com/ava-labs/coreth/core" "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" + "github.com/ava-labs/avalanchego/upgrade" ) func TestUpgrade(t *testing.T) { @@ -45,6 +48,25 @@ var _ = ginkgo.Describe("[Upgrade]", func() { ginkgo.It("can upgrade versions", func() { network := tmpnet.NewDefaultNetwork("avalanchego-upgrade") + + { + // Get the default genesis so we can modify it + genesis, err := network.DefaultGenesis() + require.NoError(err) + network.Genesis = genesis + // Etna enables Cancun which modifies the outcome of the C-Chain genesis + // This is because of new header fields that modify the genesis block hash. + // This code can be removed once the Etna upgrade is activated. + cChainGenesis := new(core.Genesis) + cChainGenesisStr := network.Genesis.CChainGenesis + require.NoError(json.Unmarshal([]byte(cChainGenesisStr), cChainGenesis)) + unscheduledActivationTime := uint64(upgrade.UnscheduledActivationTime.Unix()) + cChainGenesis.Config.EUpgradeTime = &unscheduledActivationTime + cChainGenesisBytes, err := json.Marshal(cChainGenesis) + require.NoError(err) + network.Genesis.CChainGenesis = string(cChainGenesisBytes) + } + e2e.StartNetwork(tc, network, avalancheGoExecPath, "" /* pluginDir */, 0 /* shutdownDelay */, false /* reuseNetwork */) tc.By(fmt.Sprintf("restarting all nodes with %q binary", avalancheGoExecPathToUpgradeTo)) diff --git a/version/constants.go b/version/constants.go index 3742f7ffe61f..a2ef3ced40c4 100644 --- a/version/constants.go +++ b/version/constants.go @@ -8,9 +8,6 @@ import ( "time" _ "embed" - - "github.com/ava-labs/avalanchego/upgrade" - "github.com/ava-labs/avalanchego/utils/constants" ) const ( @@ -67,78 +64,6 @@ var ( // set of avalanchego versions that supported that version. This is not used // by avalanchego, but is useful for downstream libraries. RPCChainVMProtocolCompatibility map[uint][]*Semantic - - // Deprecated: This will be removed once coreth no longer uses it. - ApricotPhase1Times = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.ApricotPhase1Time, - constants.FujiID: upgrade.Fuji.ApricotPhase1Time, - } - - // Deprecated: This will be removed once coreth no longer uses it. - ApricotPhase2Times = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.ApricotPhase2Time, - constants.FujiID: upgrade.Fuji.ApricotPhase2Time, - } - - // Deprecated: This will be removed once coreth no longer uses it. - ApricotPhase3Times = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.ApricotPhase3Time, - constants.FujiID: upgrade.Fuji.ApricotPhase3Time, - } - - // Deprecated: This will be removed once coreth no longer uses it. - ApricotPhase4Times = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.ApricotPhase4Time, - constants.FujiID: upgrade.Fuji.ApricotPhase4Time, - } - - // Deprecated: This will be removed once coreth no longer uses it. - ApricotPhase5Times = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.ApricotPhase5Time, - constants.FujiID: upgrade.Fuji.ApricotPhase5Time, - } - - // Deprecated: This will be removed once coreth no longer uses it. - ApricotPhasePre6Times = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.ApricotPhasePre6Time, - constants.FujiID: upgrade.Fuji.ApricotPhasePre6Time, - } - - // Deprecated: This will be removed once coreth no longer uses it. - ApricotPhase6Times = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.ApricotPhase6Time, - constants.FujiID: upgrade.Fuji.ApricotPhase6Time, - } - - // Deprecated: This will be removed once coreth no longer uses it. - ApricotPhasePost6Times = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.ApricotPhasePost6Time, - constants.FujiID: upgrade.Fuji.ApricotPhasePost6Time, - } - - // Deprecated: This will be removed once coreth no longer uses it. - BanffTimes = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.BanffTime, - constants.FujiID: upgrade.Fuji.BanffTime, - } - - // Deprecated: This will be removed once coreth no longer uses it. - CortinaTimes = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.CortinaTime, - constants.FujiID: upgrade.Fuji.CortinaTime, - } - - // Deprecated: This will be removed once coreth no longer uses it. - DurangoTimes = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.DurangoTime, - constants.FujiID: upgrade.Fuji.DurangoTime, - } - - // Deprecated: This will be removed once coreth no longer uses it. - EUpgradeTimes = map[uint32]time.Time{ - constants.MainnetID: upgrade.Mainnet.EtnaTime, - constants.FujiID: upgrade.Fuji.EtnaTime, - } ) func init() { From ab83fb41528de93c1790301cdd67a07dda9299f0 Mon Sep 17 00:00:00 2001 From: Darioush Jalali Date: Tue, 13 Aug 2024 13:33:40 -0700 Subject: [PATCH 12/69] Remove cross-chain requests (#3277) --- go.mod | 2 +- go.sum | 4 +- message/internal_msg_builder.go | 158 --- message/ops.go | 22 +- network/p2p/client.go | 62 - network/p2p/handler.go | 49 +- network/p2p/network.go | 12 - network/p2p/network_test.go | 141 +-- network/p2p/router.go | 122 +- network/p2p/throttler_handler.go | 4 - proto/appsender/appsender.proto | 33 - proto/pb/appsender/appsender.pb.go | 366 +----- proto/pb/appsender/appsender_grpc.pb.go | 119 +- proto/pb/vm/vm.pb.go | 1127 ++++++----------- proto/pb/vm/vm_grpc.pb.go | 111 -- proto/vm/vm.proto | 35 - scripts/mocks.mockgen.source.txt | 2 +- snow/engine/avalanche/vertex/mock_vm.go | 42 - .../common/appsender/appsender_client.go | 38 - .../common/appsender/appsender_server.go | 27 - snow/engine/common/engine.go | 62 +- snow/engine/common/mock_sender.go | 44 +- snow/engine/common/no_ops_handlers.go | 31 - snow/engine/common/sender.go | 38 +- snow/engine/common/traced_engine.go | 32 - snow/engine/enginetest/engine.go | 71 +- snow/engine/enginetest/sender.go | 79 +- snow/engine/enginetest/vm.go | 101 +- snow/engine/snowman/block/mock_chain_vm.go | 42 - snow/networking/handler/handler.go | 33 +- snow/networking/router/chain_router_test.go | 131 +- snow/networking/sender/sender.go | 64 - snow/networking/sender/sender_test.go | 18 - snow/networking/sender/traced_sender.go | 34 - tests/upgrade/upgrade_test.go | 2 +- vms/avm/network/atomic.go | 47 - vms/rpcchainvm/vm_client.go | 37 - vms/rpcchainvm/vm_server.go | 33 - 38 files changed, 519 insertions(+), 2856 deletions(-) diff --git a/go.mod b/go.mod index bc1e96772e80..f847fee1dd8f 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/DataDog/zstd v1.5.2 github.com/NYTimes/gziphandler v1.1.1 github.com/antithesishq/antithesis-sdk-go v0.3.8 - github.com/ava-labs/coreth v0.13.8-fix-genesis-upgrade + github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240813194342-7635a96aa180 github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95 github.com/btcsuite/btcd/btcutil v1.1.3 github.com/cockroachdb/pebble v0.0.0-20230928194634-aa077af62593 diff --git a/go.sum b/go.sum index 1f06a819fe3a..5881b9005f47 100644 --- a/go.sum +++ b/go.sum @@ -62,8 +62,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/antithesishq/antithesis-sdk-go v0.3.8 h1:OvGoHxIcOXFJLyn9IJQ5DzByZ3YVAWNBc394ObzDRb8= github.com/antithesishq/antithesis-sdk-go v0.3.8/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/coreth v0.13.8-fix-genesis-upgrade h1:xWsvSGtZcGna3B2BLU2BvK3qskbcc9ZNtgC0ck91CkI= -github.com/ava-labs/coreth v0.13.8-fix-genesis-upgrade/go.mod h1:Ouul9dJouniUIJVX1gDqx8CrHyGvmwZkK28mrgKb/4I= +github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240813194342-7635a96aa180 h1:6aIHp7wbyGVYdhHVQUbG7BEcbCMEQ5SYopPPJyipyvk= +github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240813194342-7635a96aa180/go.mod h1:/wNBVq7J7wlC2Kbov7kk6LV5xZvau7VF9zwTVOeyAjY= github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95 h1:dOVbtdnZL++pENdTCNZ1nu41eYDQkTML4sWebDnnq8c= github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95/go.mod h1:pJxaT9bUgeRNVmNRgtCHb7sFDIRKy7CzTQVi8gGNT6g= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= diff --git a/message/internal_msg_builder.go b/message/internal_msg_builder.go index 141dabaae414..9de6dabbd442 100644 --- a/message/internal_msg_builder.go +++ b/message/internal_msg_builder.go @@ -6,7 +6,6 @@ package message import ( "fmt" - "time" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/proto/pb/p2p" @@ -48,21 +47,6 @@ var ( _ chainIDGetter = (*QueryFailed)(nil) _ requestIDGetter = (*QueryFailed)(nil) - _ fmt.Stringer = (*CrossChainAppRequest)(nil) - _ sourceChainIDGetter = (*CrossChainAppRequest)(nil) - _ chainIDGetter = (*CrossChainAppRequest)(nil) - _ requestIDGetter = (*CrossChainAppRequest)(nil) - - _ fmt.Stringer = (*CrossChainAppRequestFailed)(nil) - _ sourceChainIDGetter = (*CrossChainAppRequestFailed)(nil) - _ chainIDGetter = (*CrossChainAppRequestFailed)(nil) - _ requestIDGetter = (*CrossChainAppRequestFailed)(nil) - - _ fmt.Stringer = (*CrossChainAppResponse)(nil) - _ sourceChainIDGetter = (*CrossChainAppResponse)(nil) - _ chainIDGetter = (*CrossChainAppResponse)(nil) - _ requestIDGetter = (*CrossChainAppResponse)(nil) - _ fmt.Stringer = (*Disconnected)(nil) _ fmt.Stringer = (*GossipRequest)(nil) @@ -329,148 +313,6 @@ func InternalQueryFailed( } } -type CrossChainAppRequest struct { - SourceChainID ids.ID `json:"source_chain_id,omitempty"` - DestinationChainID ids.ID `json:"destination_chain_id,omitempty"` - RequestID uint32 `json:"request_id,omitempty"` - Message []byte `json:"message,omitempty"` -} - -func (m *CrossChainAppRequest) String() string { - return fmt.Sprintf( - "SourceChainID: %s DestinationChainID: %s RequestID: %d Message: 0x%x", - m.SourceChainID, m.DestinationChainID, m.RequestID, m.Message, - ) -} - -func (m *CrossChainAppRequest) GetSourceChainID() ids.ID { - return m.SourceChainID -} - -func (m *CrossChainAppRequest) GetChainId() []byte { - return m.DestinationChainID[:] -} - -func (m *CrossChainAppRequest) GetRequestId() uint32 { - return m.RequestID -} - -func InternalCrossChainAppRequest( - nodeID ids.NodeID, - sourceChainID ids.ID, - destinationChainID ids.ID, - requestID uint32, - deadline time.Duration, - msg []byte, -) InboundMessage { - return &inboundMessage{ - nodeID: nodeID, - op: CrossChainAppRequestOp, - message: &CrossChainAppRequest{ - SourceChainID: sourceChainID, - DestinationChainID: destinationChainID, - RequestID: requestID, - Message: msg, - }, - expiration: time.Now().Add(deadline), - } -} - -type CrossChainAppRequestFailed struct { - SourceChainID ids.ID `json:"source_chain_id,omitempty"` - DestinationChainID ids.ID `json:"destination_chain_id,omitempty"` - RequestID uint32 `json:"request_id,omitempty"` - ErrorCode int32 `json:"error_code,omitempty"` - ErrorMessage string `json:"error_message,omitempty"` -} - -func (m *CrossChainAppRequestFailed) String() string { - return fmt.Sprintf( - "SourceChainID: %s DestinationChainID: %s RequestID: %d", - m.SourceChainID, m.DestinationChainID, m.RequestID, - ) -} - -func (m *CrossChainAppRequestFailed) GetSourceChainID() ids.ID { - return m.SourceChainID -} - -func (m *CrossChainAppRequestFailed) GetChainId() []byte { - return m.DestinationChainID[:] -} - -func (m *CrossChainAppRequestFailed) GetRequestId() uint32 { - return m.RequestID -} - -func InternalCrossChainAppError( - nodeID ids.NodeID, - sourceChainID ids.ID, - destinationChainID ids.ID, - requestID uint32, - errorCode int32, - errorMessage string, -) InboundMessage { - return &inboundMessage{ - nodeID: nodeID, - op: CrossChainAppErrorOp, - message: &CrossChainAppRequestFailed{ - SourceChainID: sourceChainID, - DestinationChainID: destinationChainID, - RequestID: requestID, - ErrorCode: errorCode, - ErrorMessage: errorMessage, - }, - expiration: mockable.MaxTime, - } -} - -type CrossChainAppResponse struct { - SourceChainID ids.ID `json:"source_chain_id,omitempty"` - DestinationChainID ids.ID `json:"destination_chain_id,omitempty"` - RequestID uint32 `json:"request_id,omitempty"` - Message []byte `json:"message,omitempty"` -} - -func (m *CrossChainAppResponse) String() string { - return fmt.Sprintf( - "SourceChainID: %s DestinationChainID: %s RequestID: %d Message: 0x%x", - m.SourceChainID, m.DestinationChainID, m.RequestID, m.Message, - ) -} - -func (m *CrossChainAppResponse) GetSourceChainID() ids.ID { - return m.SourceChainID -} - -func (m *CrossChainAppResponse) GetChainId() []byte { - return m.DestinationChainID[:] -} - -func (m *CrossChainAppResponse) GetRequestId() uint32 { - return m.RequestID -} - -func InternalCrossChainAppResponse( - nodeID ids.NodeID, - sourceChainID ids.ID, - destinationChainID ids.ID, - requestID uint32, - msg []byte, -) InboundMessage { - return &inboundMessage{ - nodeID: nodeID, - op: CrossChainAppResponseOp, - message: &CrossChainAppResponse{ - SourceChainID: sourceChainID, - DestinationChainID: destinationChainID, - RequestID: requestID, - Message: msg, - }, - expiration: mockable.MaxTime, - } -} - type Connected struct { NodeVersion *version.Application `json:"node_version,omitempty"` } diff --git a/message/ops.go b/message/ops.go index 11c69087b5f8..92c4697949b6 100644 --- a/message/ops.go +++ b/message/ops.go @@ -54,10 +54,6 @@ const ( AppErrorOp AppResponseOp AppGossipOp - // Cross chain: - CrossChainAppRequestOp - CrossChainAppErrorOp - CrossChainAppResponseOp // Internal: ConnectedOp ConnectedSubnetOp @@ -116,9 +112,6 @@ var ( GetAncestorsFailedOp, GetFailedOp, QueryFailedOp, - CrossChainAppRequestOp, - CrossChainAppErrorOp, - CrossChainAppResponseOp, ConnectedOp, ConnectedSubnetOp, DisconnectedOp, @@ -168,10 +161,6 @@ var ( AppErrorOp, AppGossipOp, AppResponseOp, - // Cross chain - CrossChainAppRequestOp, - CrossChainAppErrorOp, - CrossChainAppResponseOp, } FailedToResponseOps = map[Op]Op{ @@ -183,7 +172,6 @@ var ( GetFailedOp: PutOp, QueryFailedOp: ChitsOp, AppErrorOp: AppResponseOp, - CrossChainAppErrorOp: CrossChainAppResponseOp, } UnrequestedOps = set.Of( GetAcceptedFrontierOp, @@ -194,7 +182,6 @@ var ( PullQueryOp, AppRequestOp, AppGossipOp, - CrossChainAppRequestOp, GetStateSummaryFrontierOp, GetAcceptedStateSummaryOp, ) @@ -271,14 +258,7 @@ func (op Op) String() string { return "app_response" case AppGossipOp: return "app_gossip" - // Cross chain - case CrossChainAppRequestOp: - return "cross_chain_app_request" - case CrossChainAppErrorOp: - return "cross_chain_app_error" - case CrossChainAppResponseOp: - return "cross_chain_app_response" - // Internal + // Internal case ConnectedOp: return "connected" case ConnectedSubnetOp: diff --git a/network/p2p/client.go b/network/p2p/client.go index 18556bfad1fa..2e5013a211f0 100644 --- a/network/p2p/client.go +++ b/network/p2p/client.go @@ -31,16 +31,6 @@ type AppResponseCallback func( err error, ) -// CrossChainAppResponseCallback is called upon receiving an -// CrossChainAppResponse for a CrossChainAppRequest issued by Client. -// Callers should check [err] to see whether the AppRequest failed or not. -type CrossChainAppResponseCallback func( - ctx context.Context, - chainID ids.ID, - responseBytes []byte, - err error, -) - type Client struct { handlerID uint64 handlerIDStr string @@ -140,58 +130,6 @@ func (c *Client) AppGossip( ) } -// CrossChainAppRequest sends a cross chain app request to another vm. -// [onResponse] is invoked upon an error or a response. -func (c *Client) CrossChainAppRequest( - ctx context.Context, - chainID ids.ID, - appRequestBytes []byte, - onResponse CrossChainAppResponseCallback, -) error { - // Cancellation is removed from this context to avoid erroring unexpectedly. - // SendCrossChainAppRequest should be non-blocking and any error other than - // context cancellation is unexpected. - // - // This guarantees that the router should never receive an unexpected - // CrossChainAppResponse. - ctxWithoutCancel := context.WithoutCancel(ctx) - - c.router.lock.Lock() - defer c.router.lock.Unlock() - - requestID := c.router.requestID - if _, ok := c.router.pendingCrossChainAppRequests[requestID]; ok { - return fmt.Errorf( - "failed to issue request with request id %d: %w", - requestID, - ErrRequestPending, - ) - } - - if err := c.sender.SendCrossChainAppRequest( - ctxWithoutCancel, - chainID, - requestID, - PrefixMessage(c.handlerPrefix, appRequestBytes), - ); err != nil { - c.router.log.Error("unexpected error when sending message", - zap.Stringer("op", message.CrossChainAppRequestOp), - zap.Stringer("chainID", chainID), - zap.Uint32("requestID", requestID), - zap.Error(err), - ) - return err - } - - c.router.pendingCrossChainAppRequests[requestID] = pendingCrossChainAppRequest{ - handlerID: c.handlerIDStr, - callback: onResponse, - } - c.router.requestID += 2 - - return nil -} - // PrefixMessage prefixes the original message with the protocol identifier. // // Only gossip and request messages need to be prefixed. diff --git a/network/p2p/handler.go b/network/p2p/handler.go index 3223ed362229..23819cd18465 100644 --- a/network/p2p/handler.go +++ b/network/p2p/handler.go @@ -46,15 +46,6 @@ type Handler interface { deadline time.Time, requestBytes []byte, ) ([]byte, *common.AppError) - // CrossChainAppRequest is called when handling a CrossChainAppRequest - // message. - // Returns the bytes for the response corresponding to [requestBytes] - CrossChainAppRequest( - ctx context.Context, - chainID ids.ID, - deadline time.Time, - requestBytes []byte, - ) ([]byte, error) } // NoOpHandler drops all messages @@ -66,10 +57,6 @@ func (NoOpHandler) AppRequest(context.Context, ids.NodeID, time.Time, []byte) ([ return nil, nil } -func (NoOpHandler) CrossChainAppRequest(context.Context, ids.ID, time.Time, []byte) ([]byte, error) { - return nil, nil -} - func NewValidatorHandler( handler Handler, validatorSet ValidatorSet, @@ -109,10 +96,6 @@ func (v ValidatorHandler) AppRequest(ctx context.Context, nodeID ids.NodeID, dea return v.handler.AppRequest(ctx, nodeID, deadline, requestBytes) } -func (v ValidatorHandler) CrossChainAppRequest(ctx context.Context, chainID ids.ID, deadline time.Time, requestBytes []byte) ([]byte, error) { - return v.handler.CrossChainAppRequest(ctx, chainID, deadline, requestBytes) -} - // responder automatically sends the response for a given request type responder struct { Handler @@ -140,29 +123,9 @@ func (r *responder) AppRequest(ctx context.Context, nodeID ids.NodeID, requestID return r.sender.SendAppResponse(ctx, nodeID, requestID, appResponse) } -// CrossChainAppRequest calls the underlying handler and sends back the response -// to chainID -func (r *responder) CrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, request []byte) error { - appResponse, err := r.Handler.CrossChainAppRequest(ctx, chainID, deadline, request) - if err != nil { - r.log.Debug("failed to handle message", - zap.Stringer("messageOp", message.CrossChainAppRequestOp), - zap.Stringer("chainID", chainID), - zap.Uint32("requestID", requestID), - zap.Time("deadline", deadline), - zap.Uint64("handlerID", r.handlerID), - zap.Binary("message", request), - ) - return nil //nolint:nilerr - } - - return r.sender.SendCrossChainAppResponse(ctx, chainID, requestID, appResponse) -} - type TestHandler struct { - AppGossipF func(ctx context.Context, nodeID ids.NodeID, gossipBytes []byte) - AppRequestF func(ctx context.Context, nodeID ids.NodeID, deadline time.Time, requestBytes []byte) ([]byte, *common.AppError) - CrossChainAppRequestF func(ctx context.Context, chainID ids.ID, deadline time.Time, requestBytes []byte) ([]byte, error) + AppGossipF func(ctx context.Context, nodeID ids.NodeID, gossipBytes []byte) + AppRequestF func(ctx context.Context, nodeID ids.NodeID, deadline time.Time, requestBytes []byte) ([]byte, *common.AppError) } func (t TestHandler) AppGossip(ctx context.Context, nodeID ids.NodeID, gossipBytes []byte) { @@ -180,11 +143,3 @@ func (t TestHandler) AppRequest(ctx context.Context, nodeID ids.NodeID, deadline return t.AppRequestF(ctx, nodeID, deadline, requestBytes) } - -func (t TestHandler) CrossChainAppRequest(ctx context.Context, chainID ids.ID, deadline time.Time, requestBytes []byte) ([]byte, error) { - if t.CrossChainAppRequestF == nil { - return nil, nil - } - - return t.CrossChainAppRequestF(ctx, chainID, deadline, requestBytes) -} diff --git a/network/p2p/network.go b/network/p2p/network.go index 491b35bbe9b9..fff077645d9a 100644 --- a/network/p2p/network.go +++ b/network/p2p/network.go @@ -124,18 +124,6 @@ func (n *Network) AppGossip(ctx context.Context, nodeID ids.NodeID, msg []byte) return n.router.AppGossip(ctx, nodeID, msg) } -func (n *Network) CrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, request []byte) error { - return n.router.CrossChainAppRequest(ctx, chainID, requestID, deadline, request) -} - -func (n *Network) CrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, response []byte) error { - return n.router.CrossChainAppResponse(ctx, chainID, requestID, response) -} - -func (n *Network) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error { - return n.router.CrossChainAppRequestFailed(ctx, chainID, requestID, appErr) -} - func (n *Network) Connected(_ context.Context, nodeID ids.NodeID, _ *version.Application) error { n.Peers.add(nodeID) return nil diff --git a/network/p2p/network_test.go b/network/p2p/network_test.go index 5d4e746eaf1d..7ef18da3dbcb 100644 --- a/network/p2p/network_test.go +++ b/network/p2p/network_test.go @@ -35,10 +35,9 @@ func TestMessageRouting(t *testing.T) { require := require.New(t) ctx := context.Background() wantNodeID := ids.GenerateTestNodeID() - wantChainID := ids.GenerateTestID() wantMsg := []byte("message") - var appGossipCalled, appRequestCalled, crossChainAppRequestCalled bool + var appGossipCalled, appRequestCalled bool testHandler := &TestHandler{ AppGossipF: func(_ context.Context, nodeID ids.NodeID, msg []byte) { appGossipCalled = true @@ -51,18 +50,11 @@ func TestMessageRouting(t *testing.T) { require.Equal(wantMsg, msg) return nil, nil }, - CrossChainAppRequestF: func(_ context.Context, chainID ids.ID, _ time.Time, msg []byte) ([]byte, error) { - crossChainAppRequestCalled = true - require.Equal(wantChainID, chainID) - require.Equal(wantMsg, msg) - return nil, nil - }, } sender := &enginetest.SenderStub{ - SentAppGossip: make(chan []byte, 1), - SentAppRequest: make(chan []byte, 1), - SentCrossChainAppRequest: make(chan []byte, 1), + SentAppGossip: make(chan []byte, 1), + SentAppRequest: make(chan []byte, 1), } network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") @@ -83,10 +75,6 @@ func TestMessageRouting(t *testing.T) { require.NoError(client.AppRequest(ctx, set.Of(ids.EmptyNodeID), wantMsg, func(context.Context, ids.NodeID, []byte, error) {})) require.NoError(network.AppRequest(ctx, wantNodeID, 1, time.Time{}, <-sender.SentAppRequest)) require.True(appRequestCalled) - - require.NoError(client.CrossChainAppRequest(ctx, ids.Empty, wantMsg, func(context.Context, ids.ID, []byte, error) {})) - require.NoError(network.CrossChainAppRequest(ctx, wantChainID, 1, time.Time{}, <-sender.SentCrossChainAppRequest)) - require.True(crossChainAppRequestCalled) } // Tests that the Client prefixes messages with the handler prefix @@ -95,9 +83,8 @@ func TestClientPrefixesMessages(t *testing.T) { ctx := context.Background() sender := enginetest.SenderStub{ - SentAppRequest: make(chan []byte, 1), - SentAppGossip: make(chan []byte, 1), - SentCrossChainAppRequest: make(chan []byte, 1), + SentAppRequest: make(chan []byte, 1), + SentAppGossip: make(chan []byte, 1), } network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") @@ -126,16 +113,6 @@ func TestClientPrefixesMessages(t *testing.T) { require.Equal(handlerPrefix, gotAppRequest[0]) require.Equal(want, gotAppRequest[1:]) - require.NoError(client.CrossChainAppRequest( - ctx, - ids.Empty, - want, - func(context.Context, ids.ID, []byte, error) {}, - )) - gotCrossChainAppRequest := <-sender.SentCrossChainAppRequest - require.Equal(handlerPrefix, gotCrossChainAppRequest[0]) - require.Equal(want, gotCrossChainAppRequest[1:]) - require.NoError(client.AppGossip( ctx, common.SendConfig{ @@ -254,105 +231,6 @@ func TestAppRequestFailed(t *testing.T) { <-done } -// Tests that the Client callback is called on a successful response -func TestCrossChainAppRequestResponse(t *testing.T) { - require := require.New(t) - ctx := context.Background() - - sender := enginetest.SenderStub{ - SentCrossChainAppRequest: make(chan []byte, 1), - } - network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") - require.NoError(err) - client := network.NewClient(handlerID) - - wantChainID := ids.GenerateTestID() - wantResponse := []byte("response") - done := make(chan struct{}) - - callback := func(_ context.Context, gotChainID ids.ID, gotResponse []byte, err error) { - require.Equal(wantChainID, gotChainID) - require.NoError(err) - require.Equal(wantResponse, gotResponse) - - close(done) - } - - require.NoError(client.CrossChainAppRequest(ctx, wantChainID, []byte("request"), callback)) - <-sender.SentCrossChainAppRequest - - require.NoError(network.CrossChainAppResponse(ctx, wantChainID, 1, wantResponse)) - <-done -} - -// Tests that the Client does not provide a cancelled context to the AppSender. -func TestCrossChainAppRequestCancelledContext(t *testing.T) { - require := require.New(t) - ctx := context.Background() - - sentMessages := make(chan []byte, 1) - sender := &enginetest.Sender{ - SendCrossChainAppRequestF: func(ctx context.Context, _ ids.ID, _ uint32, msgBytes []byte) { - require.NoError(ctx.Err()) - sentMessages <- msgBytes - }, - } - network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") - require.NoError(err) - client := network.NewClient(handlerID) - - cancelledCtx, cancel := context.WithCancel(ctx) - cancel() - - wantChainID := ids.GenerateTestID() - wantResponse := []byte("response") - done := make(chan struct{}) - - callback := func(_ context.Context, gotChainID ids.ID, gotResponse []byte, err error) { - require.Equal(wantChainID, gotChainID) - require.NoError(err) - require.Equal(wantResponse, gotResponse) - - close(done) - } - - require.NoError(client.CrossChainAppRequest(cancelledCtx, wantChainID, []byte("request"), callback)) - <-sentMessages - - require.NoError(network.CrossChainAppResponse(ctx, wantChainID, 1, wantResponse)) - <-done -} - -// Tests that the Client callback is given an error if the request fails -func TestCrossChainAppRequestFailed(t *testing.T) { - require := require.New(t) - ctx := context.Background() - - sender := enginetest.SenderStub{ - SentCrossChainAppRequest: make(chan []byte, 1), - } - network, err := NewNetwork(logging.NoLog{}, sender, prometheus.NewRegistry(), "") - require.NoError(err) - client := network.NewClient(handlerID) - - wantChainID := ids.GenerateTestID() - done := make(chan struct{}) - - callback := func(_ context.Context, gotChainID ids.ID, gotResponse []byte, err error) { - require.Equal(wantChainID, gotChainID) - require.ErrorIs(err, errFoo) - require.Nil(gotResponse) - - close(done) - } - - require.NoError(client.CrossChainAppRequest(ctx, wantChainID, []byte("request"), callback)) - <-sender.SentCrossChainAppRequest - - require.NoError(network.CrossChainAppRequestFailed(ctx, wantChainID, 1, errFoo)) - <-done -} - // Messages for unregistered handlers should be dropped gracefully func TestAppGossipMessageForUnregisteredHandler(t *testing.T) { tests := []struct { @@ -517,10 +395,6 @@ func TestResponseForUnrequestedRequest(t *testing.T) { require.Fail("should not be called") return nil, nil }, - CrossChainAppRequestF: func(context.Context, ids.ID, time.Time, []byte) ([]byte, error) { - require.Fail("should not be called") - return nil, nil - }, } network, err := NewNetwork(logging.NoLog{}, nil, prometheus.NewRegistry(), "") require.NoError(err) @@ -530,11 +404,6 @@ func TestResponseForUnrequestedRequest(t *testing.T) { require.ErrorIs(err, ErrUnrequestedResponse) err = network.AppRequestFailed(ctx, ids.EmptyNodeID, 0, common.ErrTimeout) require.ErrorIs(err, ErrUnrequestedResponse) - err = network.CrossChainAppResponse(ctx, ids.Empty, 0, []byte("foobar")) - require.ErrorIs(err, ErrUnrequestedResponse) - err = network.CrossChainAppRequestFailed(ctx, ids.Empty, 0, common.ErrTimeout) - - require.ErrorIs(err, ErrUnrequestedResponse) }) } } diff --git a/network/p2p/router.go b/network/p2p/router.go index 8f099ddb0b64..9c020ab49356 100644 --- a/network/p2p/router.go +++ b/network/p2p/router.go @@ -33,11 +33,6 @@ type pendingAppRequest struct { callback AppResponseCallback } -type pendingCrossChainAppRequest struct { - handlerID string - callback CrossChainAppResponseCallback -} - // meteredHandler emits metrics for a Handler type meteredHandler struct { *responder @@ -73,11 +68,10 @@ type router struct { sender common.AppSender metrics metrics - lock sync.RWMutex - handlers map[uint64]*meteredHandler - pendingAppRequests map[uint32]pendingAppRequest - pendingCrossChainAppRequests map[uint32]pendingCrossChainAppRequest - requestID uint32 + lock sync.RWMutex + handlers map[uint64]*meteredHandler + pendingAppRequests map[uint32]pendingAppRequest + requestID uint32 } // newRouter returns a new instance of Router @@ -87,12 +81,11 @@ func newRouter( metrics metrics, ) *router { return &router{ - log: log, - sender: sender, - metrics: metrics, - handlers: make(map[uint64]*meteredHandler), - pendingAppRequests: make(map[uint32]pendingAppRequest), - pendingCrossChainAppRequests: make(map[uint32]pendingCrossChainAppRequest), + log: log, + sender: sender, + metrics: metrics, + handlers: make(map[uint64]*meteredHandler), + pendingAppRequests: make(map[uint32]pendingAppRequest), // invariant: sdk uses odd-numbered requestIDs requestID: 1, } @@ -232,93 +225,6 @@ func (r *router) AppGossip(ctx context.Context, nodeID ids.NodeID, gossip []byte ) } -// CrossChainAppRequest routes a CrossChainAppRequest message to a Handler -// based on the handler prefix. The message is dropped if no matching handler -// can be found. -// -// Any error condition propagated outside Handler application logic is -// considered fatal -func (r *router) CrossChainAppRequest( - ctx context.Context, - chainID ids.ID, - requestID uint32, - deadline time.Time, - msg []byte, -) error { - start := time.Now() - parsedMsg, handler, handlerID, ok := r.parse(msg) - if !ok { - r.log.Debug("received message for unregistered handler", - zap.Stringer("messageOp", message.CrossChainAppRequestOp), - zap.Stringer("chainID", chainID), - zap.Uint32("requestID", requestID), - zap.Time("deadline", deadline), - zap.Binary("message", msg), - ) - return nil - } - - if err := handler.CrossChainAppRequest(ctx, chainID, requestID, deadline, parsedMsg); err != nil { - return err - } - - return r.metrics.observe( - prometheus.Labels{ - opLabel: message.CrossChainAppRequestOp.String(), - handlerLabel: handlerID, - }, - start, - ) -} - -// CrossChainAppRequestFailed routes a CrossChainAppRequestFailed message to -// the callback corresponding to requestID. -// -// Any error condition propagated outside Handler application logic is -// considered fatal -func (r *router) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error { - start := time.Now() - pending, ok := r.clearCrossChainAppRequest(requestID) - if !ok { - // we should never receive a timeout without a corresponding requestID - return ErrUnrequestedResponse - } - - pending.callback(ctx, chainID, nil, appErr) - - return r.metrics.observe( - prometheus.Labels{ - opLabel: message.CrossChainAppErrorOp.String(), - handlerLabel: pending.handlerID, - }, - start, - ) -} - -// CrossChainAppResponse routes a CrossChainAppResponse message to the callback -// corresponding to requestID. -// -// Any error condition propagated outside Handler application logic is -// considered fatal -func (r *router) CrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, response []byte) error { - start := time.Now() - pending, ok := r.clearCrossChainAppRequest(requestID) - if !ok { - // we should never receive a timeout without a corresponding requestID - return ErrUnrequestedResponse - } - - pending.callback(ctx, chainID, response, nil) - - return r.metrics.observe( - prometheus.Labels{ - opLabel: message.CrossChainAppResponseOp.String(), - handlerLabel: pending.handlerID, - }, - start, - ) -} - // Parse parses a gossip or request message and maps it to a corresponding // handler if present. // @@ -354,16 +260,6 @@ func (r *router) clearAppRequest(requestID uint32) (pendingAppRequest, bool) { return callback, ok } -// Invariant: Assumes [r.lock] isn't held. -func (r *router) clearCrossChainAppRequest(requestID uint32) (pendingCrossChainAppRequest, bool) { - r.lock.Lock() - defer r.lock.Unlock() - - callback, ok := r.pendingCrossChainAppRequests[requestID] - delete(r.pendingCrossChainAppRequests, requestID) - return callback, ok -} - // Parse a gossip or request message. // // Returns: diff --git a/network/p2p/throttler_handler.go b/network/p2p/throttler_handler.go index 2718f733223c..5547729e6bc2 100644 --- a/network/p2p/throttler_handler.go +++ b/network/p2p/throttler_handler.go @@ -49,7 +49,3 @@ func (t ThrottlerHandler) AppRequest(ctx context.Context, nodeID ids.NodeID, dea return t.handler.AppRequest(ctx, nodeID, deadline, requestBytes) } - -func (t ThrottlerHandler) CrossChainAppRequest(ctx context.Context, chainID ids.ID, deadline time.Time, requestBytes []byte) ([]byte, error) { - return t.handler.CrossChainAppRequest(ctx, chainID, deadline, requestBytes) -} diff --git a/proto/appsender/appsender.proto b/proto/appsender/appsender.proto index 5a03d449359e..b28f0dd27ea2 100644 --- a/proto/appsender/appsender.proto +++ b/proto/appsender/appsender.proto @@ -11,10 +11,6 @@ service AppSender { rpc SendAppResponse(SendAppResponseMsg) returns (google.protobuf.Empty); rpc SendAppError(SendAppErrorMsg) returns (google.protobuf.Empty); rpc SendAppGossip(SendAppGossipMsg) returns (google.protobuf.Empty); - - rpc SendCrossChainAppRequest(SendCrossChainAppRequestMsg) returns (google.protobuf.Empty); - rpc SendCrossChainAppResponse(SendCrossChainAppResponseMsg) returns (google.protobuf.Empty); - rpc SendCrossChainAppError(SendCrossChainAppErrorMsg) returns (google.protobuf.Empty); } message SendAppRequestMsg { @@ -55,32 +51,3 @@ message SendAppGossipMsg { // The message body bytes msg = 5; } - -message SendCrossChainAppRequestMsg { - // The chain to send this request to - bytes chain_id = 1; - // the ID of this request - uint32 request_id = 2; - // The request body - bytes request = 3; -} - -message SendCrossChainAppResponseMsg { - // The chain to send this response to - bytes chain_id = 1; - // the ID of this request - uint32 request_id = 2; - // The response body - bytes response = 3; -} - -message SendCrossChainAppErrorMsg { - // The chain to send a response to - bytes chain_id = 1; - // ID of this request - uint32 request_id = 2; - // Application-defined error code - sint32 error_code = 3; - // Application-defined error message - string error_message = 4; -} diff --git a/proto/pb/appsender/appsender.pb.go b/proto/pb/appsender/appsender.pb.go index 0513d08bb736..8174a7a0ed17 100644 --- a/proto/pb/appsender/appsender.pb.go +++ b/proto/pb/appsender/appsender.pb.go @@ -309,213 +309,6 @@ func (x *SendAppGossipMsg) GetMsg() []byte { return nil } -type SendCrossChainAppRequestMsg struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // The chain to send this request to - ChainId []byte `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - // the ID of this request - RequestId uint32 `protobuf:"varint,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` - // The request body - Request []byte `protobuf:"bytes,3,opt,name=request,proto3" json:"request,omitempty"` -} - -func (x *SendCrossChainAppRequestMsg) Reset() { - *x = SendCrossChainAppRequestMsg{} - if protoimpl.UnsafeEnabled { - mi := &file_appsender_appsender_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *SendCrossChainAppRequestMsg) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*SendCrossChainAppRequestMsg) ProtoMessage() {} - -func (x *SendCrossChainAppRequestMsg) ProtoReflect() protoreflect.Message { - mi := &file_appsender_appsender_proto_msgTypes[4] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use SendCrossChainAppRequestMsg.ProtoReflect.Descriptor instead. -func (*SendCrossChainAppRequestMsg) Descriptor() ([]byte, []int) { - return file_appsender_appsender_proto_rawDescGZIP(), []int{4} -} - -func (x *SendCrossChainAppRequestMsg) GetChainId() []byte { - if x != nil { - return x.ChainId - } - return nil -} - -func (x *SendCrossChainAppRequestMsg) GetRequestId() uint32 { - if x != nil { - return x.RequestId - } - return 0 -} - -func (x *SendCrossChainAppRequestMsg) GetRequest() []byte { - if x != nil { - return x.Request - } - return nil -} - -type SendCrossChainAppResponseMsg struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // The chain to send this response to - ChainId []byte `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - // the ID of this request - RequestId uint32 `protobuf:"varint,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` - // The response body - Response []byte `protobuf:"bytes,3,opt,name=response,proto3" json:"response,omitempty"` -} - -func (x *SendCrossChainAppResponseMsg) Reset() { - *x = SendCrossChainAppResponseMsg{} - if protoimpl.UnsafeEnabled { - mi := &file_appsender_appsender_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *SendCrossChainAppResponseMsg) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*SendCrossChainAppResponseMsg) ProtoMessage() {} - -func (x *SendCrossChainAppResponseMsg) ProtoReflect() protoreflect.Message { - mi := &file_appsender_appsender_proto_msgTypes[5] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use SendCrossChainAppResponseMsg.ProtoReflect.Descriptor instead. -func (*SendCrossChainAppResponseMsg) Descriptor() ([]byte, []int) { - return file_appsender_appsender_proto_rawDescGZIP(), []int{5} -} - -func (x *SendCrossChainAppResponseMsg) GetChainId() []byte { - if x != nil { - return x.ChainId - } - return nil -} - -func (x *SendCrossChainAppResponseMsg) GetRequestId() uint32 { - if x != nil { - return x.RequestId - } - return 0 -} - -func (x *SendCrossChainAppResponseMsg) GetResponse() []byte { - if x != nil { - return x.Response - } - return nil -} - -type SendCrossChainAppErrorMsg struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // The chain to send a response to - ChainId []byte `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - // ID of this request - RequestId uint32 `protobuf:"varint,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` - // Application-defined error code - ErrorCode int32 `protobuf:"zigzag32,3,opt,name=error_code,json=errorCode,proto3" json:"error_code,omitempty"` - // Application-defined error message - ErrorMessage string `protobuf:"bytes,4,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` -} - -func (x *SendCrossChainAppErrorMsg) Reset() { - *x = SendCrossChainAppErrorMsg{} - if protoimpl.UnsafeEnabled { - mi := &file_appsender_appsender_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *SendCrossChainAppErrorMsg) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*SendCrossChainAppErrorMsg) ProtoMessage() {} - -func (x *SendCrossChainAppErrorMsg) ProtoReflect() protoreflect.Message { - mi := &file_appsender_appsender_proto_msgTypes[6] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use SendCrossChainAppErrorMsg.ProtoReflect.Descriptor instead. -func (*SendCrossChainAppErrorMsg) Descriptor() ([]byte, []int) { - return file_appsender_appsender_proto_rawDescGZIP(), []int{6} -} - -func (x *SendCrossChainAppErrorMsg) GetChainId() []byte { - if x != nil { - return x.ChainId - } - return nil -} - -func (x *SendCrossChainAppErrorMsg) GetRequestId() uint32 { - if x != nil { - return x.RequestId - } - return 0 -} - -func (x *SendCrossChainAppErrorMsg) GetErrorCode() int32 { - if x != nil { - return x.ErrorCode - } - return 0 -} - -func (x *SendCrossChainAppErrorMsg) GetErrorMessage() string { - if x != nil { - return x.ErrorMessage - } - return "" -} - var File_appsender_appsender_proto protoreflect.FileDescriptor var file_appsender_appsender_proto_rawDesc = []byte{ @@ -555,71 +348,29 @@ var file_appsender_appsender_proto_rawDesc = []byte{ 0x6e, 0x6f, 0x6e, 0x56, 0x61, 0x6c, 0x69, 0x64, 0x61, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, 0x52, 0x05, 0x70, 0x65, 0x65, 0x72, 0x73, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22, 0x71, 0x0a, 0x1b, 0x53, 0x65, 0x6e, 0x64, 0x43, 0x72, 0x6f, - 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, - 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x18, - 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x74, 0x0a, 0x1c, 0x53, 0x65, 0x6e, 0x64, - 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, - 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, - 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, - 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x99, - 0x01, 0x0a, 0x19, 0x53, 0x65, 0x6e, 0x64, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, - 0x6e, 0x41, 0x70, 0x70, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, - 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, - 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, - 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x11, 0x52, 0x09, 0x65, 0x72, 0x72, 0x6f, - 0x72, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, - 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, - 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x32, 0xb9, 0x04, 0x0a, 0x09, 0x41, - 0x70, 0x70, 0x53, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x12, 0x46, 0x0a, 0x0e, 0x53, 0x65, 0x6e, 0x64, - 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1c, 0x2e, 0x61, 0x70, 0x70, - 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, - 0x12, 0x48, 0x0a, 0x0f, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x2e, 0x61, 0x70, 0x70, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x2e, - 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, - 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x42, 0x0a, 0x0c, 0x53, 0x65, - 0x6e, 0x64, 0x41, 0x70, 0x70, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x1a, 0x2e, 0x61, 0x70, 0x70, - 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x45, 0x72, - 0x72, 0x6f, 0x72, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x44, - 0x0a, 0x0d, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x12, - 0x1b, 0x2e, 0x61, 0x70, 0x70, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, - 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, - 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, - 0x6d, 0x70, 0x74, 0x79, 0x12, 0x5a, 0x0a, 0x18, 0x53, 0x65, 0x6e, 0x64, 0x43, 0x72, 0x6f, 0x73, - 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x12, 0x26, 0x2e, 0x61, 0x70, 0x70, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x2e, 0x53, 0x65, 0x6e, - 0x64, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, - 0x12, 0x5c, 0x0a, 0x19, 0x53, 0x65, 0x6e, 0x64, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, - 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x27, 0x2e, - 0x61, 0x70, 0x70, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x43, 0x72, - 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x56, - 0x0a, 0x16, 0x53, 0x65, 0x6e, 0x64, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, - 0x41, 0x70, 0x70, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x24, 0x2e, 0x61, 0x70, 0x70, 0x73, 0x65, - 0x6e, 0x64, 0x65, 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, - 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x73, 0x67, 0x1a, 0x16, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, 0x34, 0x5a, 0x32, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x76, 0x61, 0x2d, 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x61, 0x76, - 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x68, 0x65, 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, - 0x70, 0x62, 0x2f, 0x61, 0x70, 0x70, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x33, + 0x52, 0x03, 0x6d, 0x73, 0x67, 0x32, 0xa7, 0x02, 0x0a, 0x09, 0x41, 0x70, 0x70, 0x53, 0x65, 0x6e, + 0x64, 0x65, 0x72, 0x12, 0x46, 0x0a, 0x0e, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1c, 0x2e, 0x61, 0x70, 0x70, 0x73, 0x65, 0x6e, 0x64, 0x65, + 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x48, 0x0a, 0x0f, 0x53, + 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, + 0x2e, 0x61, 0x70, 0x70, 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x41, + 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x42, 0x0a, 0x0c, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, + 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x1a, 0x2e, 0x61, 0x70, 0x70, 0x73, 0x65, 0x6e, 0x64, 0x65, + 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x73, + 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x44, 0x0a, 0x0d, 0x53, 0x65, 0x6e, + 0x64, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x12, 0x1b, 0x2e, 0x61, 0x70, 0x70, + 0x73, 0x65, 0x6e, 0x64, 0x65, 0x72, 0x2e, 0x53, 0x65, 0x6e, 0x64, 0x41, 0x70, 0x70, 0x47, 0x6f, + 0x73, 0x73, 0x69, 0x70, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, + 0x34, 0x5a, 0x32, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x76, + 0x61, 0x2d, 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x61, 0x76, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x68, 0x65, + 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x70, 0x62, 0x2f, 0x61, 0x70, 0x70, 0x73, + 0x65, 0x6e, 0x64, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( @@ -634,34 +385,25 @@ func file_appsender_appsender_proto_rawDescGZIP() []byte { return file_appsender_appsender_proto_rawDescData } -var file_appsender_appsender_proto_msgTypes = make([]protoimpl.MessageInfo, 7) +var file_appsender_appsender_proto_msgTypes = make([]protoimpl.MessageInfo, 4) var file_appsender_appsender_proto_goTypes = []interface{}{ - (*SendAppRequestMsg)(nil), // 0: appsender.SendAppRequestMsg - (*SendAppResponseMsg)(nil), // 1: appsender.SendAppResponseMsg - (*SendAppErrorMsg)(nil), // 2: appsender.SendAppErrorMsg - (*SendAppGossipMsg)(nil), // 3: appsender.SendAppGossipMsg - (*SendCrossChainAppRequestMsg)(nil), // 4: appsender.SendCrossChainAppRequestMsg - (*SendCrossChainAppResponseMsg)(nil), // 5: appsender.SendCrossChainAppResponseMsg - (*SendCrossChainAppErrorMsg)(nil), // 6: appsender.SendCrossChainAppErrorMsg - (*emptypb.Empty)(nil), // 7: google.protobuf.Empty + (*SendAppRequestMsg)(nil), // 0: appsender.SendAppRequestMsg + (*SendAppResponseMsg)(nil), // 1: appsender.SendAppResponseMsg + (*SendAppErrorMsg)(nil), // 2: appsender.SendAppErrorMsg + (*SendAppGossipMsg)(nil), // 3: appsender.SendAppGossipMsg + (*emptypb.Empty)(nil), // 4: google.protobuf.Empty } var file_appsender_appsender_proto_depIdxs = []int32{ 0, // 0: appsender.AppSender.SendAppRequest:input_type -> appsender.SendAppRequestMsg 1, // 1: appsender.AppSender.SendAppResponse:input_type -> appsender.SendAppResponseMsg 2, // 2: appsender.AppSender.SendAppError:input_type -> appsender.SendAppErrorMsg 3, // 3: appsender.AppSender.SendAppGossip:input_type -> appsender.SendAppGossipMsg - 4, // 4: appsender.AppSender.SendCrossChainAppRequest:input_type -> appsender.SendCrossChainAppRequestMsg - 5, // 5: appsender.AppSender.SendCrossChainAppResponse:input_type -> appsender.SendCrossChainAppResponseMsg - 6, // 6: appsender.AppSender.SendCrossChainAppError:input_type -> appsender.SendCrossChainAppErrorMsg - 7, // 7: appsender.AppSender.SendAppRequest:output_type -> google.protobuf.Empty - 7, // 8: appsender.AppSender.SendAppResponse:output_type -> google.protobuf.Empty - 7, // 9: appsender.AppSender.SendAppError:output_type -> google.protobuf.Empty - 7, // 10: appsender.AppSender.SendAppGossip:output_type -> google.protobuf.Empty - 7, // 11: appsender.AppSender.SendCrossChainAppRequest:output_type -> google.protobuf.Empty - 7, // 12: appsender.AppSender.SendCrossChainAppResponse:output_type -> google.protobuf.Empty - 7, // 13: appsender.AppSender.SendCrossChainAppError:output_type -> google.protobuf.Empty - 7, // [7:14] is the sub-list for method output_type - 0, // [0:7] is the sub-list for method input_type + 4, // 4: appsender.AppSender.SendAppRequest:output_type -> google.protobuf.Empty + 4, // 5: appsender.AppSender.SendAppResponse:output_type -> google.protobuf.Empty + 4, // 6: appsender.AppSender.SendAppError:output_type -> google.protobuf.Empty + 4, // 7: appsender.AppSender.SendAppGossip:output_type -> google.protobuf.Empty + 4, // [4:8] is the sub-list for method output_type + 0, // [0:4] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name @@ -721,42 +463,6 @@ func file_appsender_appsender_proto_init() { return nil } } - file_appsender_appsender_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SendCrossChainAppRequestMsg); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_appsender_appsender_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SendCrossChainAppResponseMsg); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_appsender_appsender_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*SendCrossChainAppErrorMsg); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } } type x struct{} out := protoimpl.TypeBuilder{ @@ -764,7 +470,7 @@ func file_appsender_appsender_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_appsender_appsender_proto_rawDesc, NumEnums: 0, - NumMessages: 7, + NumMessages: 4, NumExtensions: 0, NumServices: 1, }, diff --git a/proto/pb/appsender/appsender_grpc.pb.go b/proto/pb/appsender/appsender_grpc.pb.go index 2bd4c9cf664f..a44295b3aea6 100644 --- a/proto/pb/appsender/appsender_grpc.pb.go +++ b/proto/pb/appsender/appsender_grpc.pb.go @@ -20,13 +20,10 @@ import ( const _ = grpc.SupportPackageIsVersion7 const ( - AppSender_SendAppRequest_FullMethodName = "/appsender.AppSender/SendAppRequest" - AppSender_SendAppResponse_FullMethodName = "/appsender.AppSender/SendAppResponse" - AppSender_SendAppError_FullMethodName = "/appsender.AppSender/SendAppError" - AppSender_SendAppGossip_FullMethodName = "/appsender.AppSender/SendAppGossip" - AppSender_SendCrossChainAppRequest_FullMethodName = "/appsender.AppSender/SendCrossChainAppRequest" - AppSender_SendCrossChainAppResponse_FullMethodName = "/appsender.AppSender/SendCrossChainAppResponse" - AppSender_SendCrossChainAppError_FullMethodName = "/appsender.AppSender/SendCrossChainAppError" + AppSender_SendAppRequest_FullMethodName = "/appsender.AppSender/SendAppRequest" + AppSender_SendAppResponse_FullMethodName = "/appsender.AppSender/SendAppResponse" + AppSender_SendAppError_FullMethodName = "/appsender.AppSender/SendAppError" + AppSender_SendAppGossip_FullMethodName = "/appsender.AppSender/SendAppGossip" ) // AppSenderClient is the client API for AppSender service. @@ -37,9 +34,6 @@ type AppSenderClient interface { SendAppResponse(ctx context.Context, in *SendAppResponseMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) SendAppError(ctx context.Context, in *SendAppErrorMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) SendAppGossip(ctx context.Context, in *SendAppGossipMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) - SendCrossChainAppRequest(ctx context.Context, in *SendCrossChainAppRequestMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) - SendCrossChainAppResponse(ctx context.Context, in *SendCrossChainAppResponseMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) - SendCrossChainAppError(ctx context.Context, in *SendCrossChainAppErrorMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) } type appSenderClient struct { @@ -86,33 +80,6 @@ func (c *appSenderClient) SendAppGossip(ctx context.Context, in *SendAppGossipMs return out, nil } -func (c *appSenderClient) SendCrossChainAppRequest(ctx context.Context, in *SendCrossChainAppRequestMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) { - out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, AppSender_SendCrossChainAppRequest_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *appSenderClient) SendCrossChainAppResponse(ctx context.Context, in *SendCrossChainAppResponseMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) { - out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, AppSender_SendCrossChainAppResponse_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *appSenderClient) SendCrossChainAppError(ctx context.Context, in *SendCrossChainAppErrorMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) { - out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, AppSender_SendCrossChainAppError_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - // AppSenderServer is the server API for AppSender service. // All implementations must embed UnimplementedAppSenderServer // for forward compatibility @@ -121,9 +88,6 @@ type AppSenderServer interface { SendAppResponse(context.Context, *SendAppResponseMsg) (*emptypb.Empty, error) SendAppError(context.Context, *SendAppErrorMsg) (*emptypb.Empty, error) SendAppGossip(context.Context, *SendAppGossipMsg) (*emptypb.Empty, error) - SendCrossChainAppRequest(context.Context, *SendCrossChainAppRequestMsg) (*emptypb.Empty, error) - SendCrossChainAppResponse(context.Context, *SendCrossChainAppResponseMsg) (*emptypb.Empty, error) - SendCrossChainAppError(context.Context, *SendCrossChainAppErrorMsg) (*emptypb.Empty, error) mustEmbedUnimplementedAppSenderServer() } @@ -143,15 +107,6 @@ func (UnimplementedAppSenderServer) SendAppError(context.Context, *SendAppErrorM func (UnimplementedAppSenderServer) SendAppGossip(context.Context, *SendAppGossipMsg) (*emptypb.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method SendAppGossip not implemented") } -func (UnimplementedAppSenderServer) SendCrossChainAppRequest(context.Context, *SendCrossChainAppRequestMsg) (*emptypb.Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method SendCrossChainAppRequest not implemented") -} -func (UnimplementedAppSenderServer) SendCrossChainAppResponse(context.Context, *SendCrossChainAppResponseMsg) (*emptypb.Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method SendCrossChainAppResponse not implemented") -} -func (UnimplementedAppSenderServer) SendCrossChainAppError(context.Context, *SendCrossChainAppErrorMsg) (*emptypb.Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method SendCrossChainAppError not implemented") -} func (UnimplementedAppSenderServer) mustEmbedUnimplementedAppSenderServer() {} // UnsafeAppSenderServer may be embedded to opt out of forward compatibility for this service. @@ -237,60 +192,6 @@ func _AppSender_SendAppGossip_Handler(srv interface{}, ctx context.Context, dec return interceptor(ctx, in, info, handler) } -func _AppSender_SendCrossChainAppRequest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SendCrossChainAppRequestMsg) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AppSenderServer).SendCrossChainAppRequest(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AppSender_SendCrossChainAppRequest_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AppSenderServer).SendCrossChainAppRequest(ctx, req.(*SendCrossChainAppRequestMsg)) - } - return interceptor(ctx, in, info, handler) -} - -func _AppSender_SendCrossChainAppResponse_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SendCrossChainAppResponseMsg) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AppSenderServer).SendCrossChainAppResponse(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AppSender_SendCrossChainAppResponse_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AppSenderServer).SendCrossChainAppResponse(ctx, req.(*SendCrossChainAppResponseMsg)) - } - return interceptor(ctx, in, info, handler) -} - -func _AppSender_SendCrossChainAppError_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(SendCrossChainAppErrorMsg) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AppSenderServer).SendCrossChainAppError(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AppSender_SendCrossChainAppError_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AppSenderServer).SendCrossChainAppError(ctx, req.(*SendCrossChainAppErrorMsg)) - } - return interceptor(ctx, in, info, handler) -} - // AppSender_ServiceDesc is the grpc.ServiceDesc for AppSender service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) @@ -314,18 +215,6 @@ var AppSender_ServiceDesc = grpc.ServiceDesc{ MethodName: "SendAppGossip", Handler: _AppSender_SendAppGossip_Handler, }, - { - MethodName: "SendCrossChainAppRequest", - Handler: _AppSender_SendCrossChainAppRequest_Handler, - }, - { - MethodName: "SendCrossChainAppResponse", - Handler: _AppSender_SendCrossChainAppResponse_Handler, - }, - { - MethodName: "SendCrossChainAppError", - Handler: _AppSender_SendCrossChainAppError_Handler, - }, }, Streams: []grpc.StreamDesc{}, Metadata: "appsender/appsender.proto", diff --git a/proto/pb/vm/vm.pb.go b/proto/pb/vm/vm.pb.go index 829b6fba5144..796dfb758ac8 100644 --- a/proto/pb/vm/vm.pb.go +++ b/proto/pb/vm/vm.pb.go @@ -177,7 +177,7 @@ func (x StateSummaryAcceptResponse_Mode) Number() protoreflect.EnumNumber { // Deprecated: Use StateSummaryAcceptResponse_Mode.Descriptor instead. func (StateSummaryAcceptResponse_Mode) EnumDescriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{44, 0} + return file_vm_vm_proto_rawDescGZIP(), []int{41, 0} } type InitializeRequest struct { @@ -1813,222 +1813,6 @@ func (x *AppGossipMsg) GetMsg() []byte { return nil } -type CrossChainAppRequestMsg struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // The chain that sent us this request - ChainId []byte `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - // The ID of this request - RequestId uint32 `protobuf:"varint,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` - // deadline for this request - Deadline *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=deadline,proto3" json:"deadline,omitempty"` - // The request body - Request []byte `protobuf:"bytes,4,opt,name=request,proto3" json:"request,omitempty"` -} - -func (x *CrossChainAppRequestMsg) Reset() { - *x = CrossChainAppRequestMsg{} - if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[24] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CrossChainAppRequestMsg) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CrossChainAppRequestMsg) ProtoMessage() {} - -func (x *CrossChainAppRequestMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[24] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CrossChainAppRequestMsg.ProtoReflect.Descriptor instead. -func (*CrossChainAppRequestMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{24} -} - -func (x *CrossChainAppRequestMsg) GetChainId() []byte { - if x != nil { - return x.ChainId - } - return nil -} - -func (x *CrossChainAppRequestMsg) GetRequestId() uint32 { - if x != nil { - return x.RequestId - } - return 0 -} - -func (x *CrossChainAppRequestMsg) GetDeadline() *timestamppb.Timestamp { - if x != nil { - return x.Deadline - } - return nil -} - -func (x *CrossChainAppRequestMsg) GetRequest() []byte { - if x != nil { - return x.Request - } - return nil -} - -type CrossChainAppRequestFailedMsg struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // The chain that we failed to get a response from - ChainId []byte `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - // The ID of the request we sent and didn't get a response to - RequestId uint32 `protobuf:"varint,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` - // Application-defined error code - ErrorCode int32 `protobuf:"zigzag32,3,opt,name=error_code,json=errorCode,proto3" json:"error_code,omitempty"` - // Application-defined error message - ErrorMessage string `protobuf:"bytes,4,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` -} - -func (x *CrossChainAppRequestFailedMsg) Reset() { - *x = CrossChainAppRequestFailedMsg{} - if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[25] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CrossChainAppRequestFailedMsg) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CrossChainAppRequestFailedMsg) ProtoMessage() {} - -func (x *CrossChainAppRequestFailedMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[25] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CrossChainAppRequestFailedMsg.ProtoReflect.Descriptor instead. -func (*CrossChainAppRequestFailedMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{25} -} - -func (x *CrossChainAppRequestFailedMsg) GetChainId() []byte { - if x != nil { - return x.ChainId - } - return nil -} - -func (x *CrossChainAppRequestFailedMsg) GetRequestId() uint32 { - if x != nil { - return x.RequestId - } - return 0 -} - -func (x *CrossChainAppRequestFailedMsg) GetErrorCode() int32 { - if x != nil { - return x.ErrorCode - } - return 0 -} - -func (x *CrossChainAppRequestFailedMsg) GetErrorMessage() string { - if x != nil { - return x.ErrorMessage - } - return "" -} - -type CrossChainAppResponseMsg struct { - state protoimpl.MessageState - sizeCache protoimpl.SizeCache - unknownFields protoimpl.UnknownFields - - // The chain that we got a response from - ChainId []byte `protobuf:"bytes,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - // Request ID of request that this is in response to - RequestId uint32 `protobuf:"varint,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` - // The response body - Response []byte `protobuf:"bytes,3,opt,name=response,proto3" json:"response,omitempty"` -} - -func (x *CrossChainAppResponseMsg) Reset() { - *x = CrossChainAppResponseMsg{} - if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[26] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) - } -} - -func (x *CrossChainAppResponseMsg) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CrossChainAppResponseMsg) ProtoMessage() {} - -func (x *CrossChainAppResponseMsg) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[26] - if protoimpl.UnsafeEnabled && x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CrossChainAppResponseMsg.ProtoReflect.Descriptor instead. -func (*CrossChainAppResponseMsg) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{26} -} - -func (x *CrossChainAppResponseMsg) GetChainId() []byte { - if x != nil { - return x.ChainId - } - return nil -} - -func (x *CrossChainAppResponseMsg) GetRequestId() uint32 { - if x != nil { - return x.RequestId - } - return 0 -} - -func (x *CrossChainAppResponseMsg) GetResponse() []byte { - if x != nil { - return x.Response - } - return nil -} - type ConnectedRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache @@ -2046,7 +1830,7 @@ type ConnectedRequest struct { func (x *ConnectedRequest) Reset() { *x = ConnectedRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[27] + mi := &file_vm_vm_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2059,7 +1843,7 @@ func (x *ConnectedRequest) String() string { func (*ConnectedRequest) ProtoMessage() {} func (x *ConnectedRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[27] + mi := &file_vm_vm_proto_msgTypes[24] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2072,7 +1856,7 @@ func (x *ConnectedRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ConnectedRequest.ProtoReflect.Descriptor instead. func (*ConnectedRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{27} + return file_vm_vm_proto_rawDescGZIP(), []int{24} } func (x *ConnectedRequest) GetNodeId() []byte { @@ -2121,7 +1905,7 @@ type DisconnectedRequest struct { func (x *DisconnectedRequest) Reset() { *x = DisconnectedRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[28] + mi := &file_vm_vm_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2134,7 +1918,7 @@ func (x *DisconnectedRequest) String() string { func (*DisconnectedRequest) ProtoMessage() {} func (x *DisconnectedRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[28] + mi := &file_vm_vm_proto_msgTypes[25] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2147,7 +1931,7 @@ func (x *DisconnectedRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DisconnectedRequest.ProtoReflect.Descriptor instead. func (*DisconnectedRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{28} + return file_vm_vm_proto_rawDescGZIP(), []int{25} } func (x *DisconnectedRequest) GetNodeId() []byte { @@ -2171,7 +1955,7 @@ type GetAncestorsRequest struct { func (x *GetAncestorsRequest) Reset() { *x = GetAncestorsRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[29] + mi := &file_vm_vm_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2184,7 +1968,7 @@ func (x *GetAncestorsRequest) String() string { func (*GetAncestorsRequest) ProtoMessage() {} func (x *GetAncestorsRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[29] + mi := &file_vm_vm_proto_msgTypes[26] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2197,7 +1981,7 @@ func (x *GetAncestorsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetAncestorsRequest.ProtoReflect.Descriptor instead. func (*GetAncestorsRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{29} + return file_vm_vm_proto_rawDescGZIP(), []int{26} } func (x *GetAncestorsRequest) GetBlkId() []byte { @@ -2239,7 +2023,7 @@ type GetAncestorsResponse struct { func (x *GetAncestorsResponse) Reset() { *x = GetAncestorsResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[30] + mi := &file_vm_vm_proto_msgTypes[27] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2252,7 +2036,7 @@ func (x *GetAncestorsResponse) String() string { func (*GetAncestorsResponse) ProtoMessage() {} func (x *GetAncestorsResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[30] + mi := &file_vm_vm_proto_msgTypes[27] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2265,7 +2049,7 @@ func (x *GetAncestorsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetAncestorsResponse.ProtoReflect.Descriptor instead. func (*GetAncestorsResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{30} + return file_vm_vm_proto_rawDescGZIP(), []int{27} } func (x *GetAncestorsResponse) GetBlksBytes() [][]byte { @@ -2286,7 +2070,7 @@ type BatchedParseBlockRequest struct { func (x *BatchedParseBlockRequest) Reset() { *x = BatchedParseBlockRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[31] + mi := &file_vm_vm_proto_msgTypes[28] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2299,7 +2083,7 @@ func (x *BatchedParseBlockRequest) String() string { func (*BatchedParseBlockRequest) ProtoMessage() {} func (x *BatchedParseBlockRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[31] + mi := &file_vm_vm_proto_msgTypes[28] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2312,7 +2096,7 @@ func (x *BatchedParseBlockRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use BatchedParseBlockRequest.ProtoReflect.Descriptor instead. func (*BatchedParseBlockRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{31} + return file_vm_vm_proto_rawDescGZIP(), []int{28} } func (x *BatchedParseBlockRequest) GetRequest() [][]byte { @@ -2333,7 +2117,7 @@ type BatchedParseBlockResponse struct { func (x *BatchedParseBlockResponse) Reset() { *x = BatchedParseBlockResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[32] + mi := &file_vm_vm_proto_msgTypes[29] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2346,7 +2130,7 @@ func (x *BatchedParseBlockResponse) String() string { func (*BatchedParseBlockResponse) ProtoMessage() {} func (x *BatchedParseBlockResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[32] + mi := &file_vm_vm_proto_msgTypes[29] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2359,7 +2143,7 @@ func (x *BatchedParseBlockResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use BatchedParseBlockResponse.ProtoReflect.Descriptor instead. func (*BatchedParseBlockResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{32} + return file_vm_vm_proto_rawDescGZIP(), []int{29} } func (x *BatchedParseBlockResponse) GetResponse() []*ParseBlockResponse { @@ -2380,7 +2164,7 @@ type GetBlockIDAtHeightRequest struct { func (x *GetBlockIDAtHeightRequest) Reset() { *x = GetBlockIDAtHeightRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[33] + mi := &file_vm_vm_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2393,7 +2177,7 @@ func (x *GetBlockIDAtHeightRequest) String() string { func (*GetBlockIDAtHeightRequest) ProtoMessage() {} func (x *GetBlockIDAtHeightRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[33] + mi := &file_vm_vm_proto_msgTypes[30] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2406,7 +2190,7 @@ func (x *GetBlockIDAtHeightRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetBlockIDAtHeightRequest.ProtoReflect.Descriptor instead. func (*GetBlockIDAtHeightRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{33} + return file_vm_vm_proto_rawDescGZIP(), []int{30} } func (x *GetBlockIDAtHeightRequest) GetHeight() uint64 { @@ -2428,7 +2212,7 @@ type GetBlockIDAtHeightResponse struct { func (x *GetBlockIDAtHeightResponse) Reset() { *x = GetBlockIDAtHeightResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[34] + mi := &file_vm_vm_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2441,7 +2225,7 @@ func (x *GetBlockIDAtHeightResponse) String() string { func (*GetBlockIDAtHeightResponse) ProtoMessage() {} func (x *GetBlockIDAtHeightResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[34] + mi := &file_vm_vm_proto_msgTypes[31] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2454,7 +2238,7 @@ func (x *GetBlockIDAtHeightResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetBlockIDAtHeightResponse.ProtoReflect.Descriptor instead. func (*GetBlockIDAtHeightResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{34} + return file_vm_vm_proto_rawDescGZIP(), []int{31} } func (x *GetBlockIDAtHeightResponse) GetBlkId() []byte { @@ -2482,7 +2266,7 @@ type GatherResponse struct { func (x *GatherResponse) Reset() { *x = GatherResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[35] + mi := &file_vm_vm_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2495,7 +2279,7 @@ func (x *GatherResponse) String() string { func (*GatherResponse) ProtoMessage() {} func (x *GatherResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[35] + mi := &file_vm_vm_proto_msgTypes[32] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2508,7 +2292,7 @@ func (x *GatherResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GatherResponse.ProtoReflect.Descriptor instead. func (*GatherResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{35} + return file_vm_vm_proto_rawDescGZIP(), []int{32} } func (x *GatherResponse) GetMetricFamilies() []*_go.MetricFamily { @@ -2530,7 +2314,7 @@ type StateSyncEnabledResponse struct { func (x *StateSyncEnabledResponse) Reset() { *x = StateSyncEnabledResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[36] + mi := &file_vm_vm_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2543,7 +2327,7 @@ func (x *StateSyncEnabledResponse) String() string { func (*StateSyncEnabledResponse) ProtoMessage() {} func (x *StateSyncEnabledResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[36] + mi := &file_vm_vm_proto_msgTypes[33] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2556,7 +2340,7 @@ func (x *StateSyncEnabledResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use StateSyncEnabledResponse.ProtoReflect.Descriptor instead. func (*StateSyncEnabledResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{36} + return file_vm_vm_proto_rawDescGZIP(), []int{33} } func (x *StateSyncEnabledResponse) GetEnabled() bool { @@ -2587,7 +2371,7 @@ type GetOngoingSyncStateSummaryResponse struct { func (x *GetOngoingSyncStateSummaryResponse) Reset() { *x = GetOngoingSyncStateSummaryResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[37] + mi := &file_vm_vm_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2600,7 +2384,7 @@ func (x *GetOngoingSyncStateSummaryResponse) String() string { func (*GetOngoingSyncStateSummaryResponse) ProtoMessage() {} func (x *GetOngoingSyncStateSummaryResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[37] + mi := &file_vm_vm_proto_msgTypes[34] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2613,7 +2397,7 @@ func (x *GetOngoingSyncStateSummaryResponse) ProtoReflect() protoreflect.Message // Deprecated: Use GetOngoingSyncStateSummaryResponse.ProtoReflect.Descriptor instead. func (*GetOngoingSyncStateSummaryResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{37} + return file_vm_vm_proto_rawDescGZIP(), []int{34} } func (x *GetOngoingSyncStateSummaryResponse) GetId() []byte { @@ -2658,7 +2442,7 @@ type GetLastStateSummaryResponse struct { func (x *GetLastStateSummaryResponse) Reset() { *x = GetLastStateSummaryResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[38] + mi := &file_vm_vm_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2671,7 +2455,7 @@ func (x *GetLastStateSummaryResponse) String() string { func (*GetLastStateSummaryResponse) ProtoMessage() {} func (x *GetLastStateSummaryResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[38] + mi := &file_vm_vm_proto_msgTypes[35] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2684,7 +2468,7 @@ func (x *GetLastStateSummaryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetLastStateSummaryResponse.ProtoReflect.Descriptor instead. func (*GetLastStateSummaryResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{38} + return file_vm_vm_proto_rawDescGZIP(), []int{35} } func (x *GetLastStateSummaryResponse) GetId() []byte { @@ -2726,7 +2510,7 @@ type ParseStateSummaryRequest struct { func (x *ParseStateSummaryRequest) Reset() { *x = ParseStateSummaryRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[39] + mi := &file_vm_vm_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2739,7 +2523,7 @@ func (x *ParseStateSummaryRequest) String() string { func (*ParseStateSummaryRequest) ProtoMessage() {} func (x *ParseStateSummaryRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[39] + mi := &file_vm_vm_proto_msgTypes[36] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2752,7 +2536,7 @@ func (x *ParseStateSummaryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ParseStateSummaryRequest.ProtoReflect.Descriptor instead. func (*ParseStateSummaryRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{39} + return file_vm_vm_proto_rawDescGZIP(), []int{36} } func (x *ParseStateSummaryRequest) GetBytes() []byte { @@ -2775,7 +2559,7 @@ type ParseStateSummaryResponse struct { func (x *ParseStateSummaryResponse) Reset() { *x = ParseStateSummaryResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[40] + mi := &file_vm_vm_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2788,7 +2572,7 @@ func (x *ParseStateSummaryResponse) String() string { func (*ParseStateSummaryResponse) ProtoMessage() {} func (x *ParseStateSummaryResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[40] + mi := &file_vm_vm_proto_msgTypes[37] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2801,7 +2585,7 @@ func (x *ParseStateSummaryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ParseStateSummaryResponse.ProtoReflect.Descriptor instead. func (*ParseStateSummaryResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{40} + return file_vm_vm_proto_rawDescGZIP(), []int{37} } func (x *ParseStateSummaryResponse) GetId() []byte { @@ -2836,7 +2620,7 @@ type GetStateSummaryRequest struct { func (x *GetStateSummaryRequest) Reset() { *x = GetStateSummaryRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[41] + mi := &file_vm_vm_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2849,7 +2633,7 @@ func (x *GetStateSummaryRequest) String() string { func (*GetStateSummaryRequest) ProtoMessage() {} func (x *GetStateSummaryRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[41] + mi := &file_vm_vm_proto_msgTypes[38] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2862,7 +2646,7 @@ func (x *GetStateSummaryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetStateSummaryRequest.ProtoReflect.Descriptor instead. func (*GetStateSummaryRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{41} + return file_vm_vm_proto_rawDescGZIP(), []int{38} } func (x *GetStateSummaryRequest) GetHeight() uint64 { @@ -2885,7 +2669,7 @@ type GetStateSummaryResponse struct { func (x *GetStateSummaryResponse) Reset() { *x = GetStateSummaryResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[42] + mi := &file_vm_vm_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2898,7 +2682,7 @@ func (x *GetStateSummaryResponse) String() string { func (*GetStateSummaryResponse) ProtoMessage() {} func (x *GetStateSummaryResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[42] + mi := &file_vm_vm_proto_msgTypes[39] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2911,7 +2695,7 @@ func (x *GetStateSummaryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetStateSummaryResponse.ProtoReflect.Descriptor instead. func (*GetStateSummaryResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{42} + return file_vm_vm_proto_rawDescGZIP(), []int{39} } func (x *GetStateSummaryResponse) GetId() []byte { @@ -2946,7 +2730,7 @@ type StateSummaryAcceptRequest struct { func (x *StateSummaryAcceptRequest) Reset() { *x = StateSummaryAcceptRequest{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[43] + mi := &file_vm_vm_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2959,7 +2743,7 @@ func (x *StateSummaryAcceptRequest) String() string { func (*StateSummaryAcceptRequest) ProtoMessage() {} func (x *StateSummaryAcceptRequest) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[43] + mi := &file_vm_vm_proto_msgTypes[40] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2972,7 +2756,7 @@ func (x *StateSummaryAcceptRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use StateSummaryAcceptRequest.ProtoReflect.Descriptor instead. func (*StateSummaryAcceptRequest) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{43} + return file_vm_vm_proto_rawDescGZIP(), []int{40} } func (x *StateSummaryAcceptRequest) GetBytes() []byte { @@ -2994,7 +2778,7 @@ type StateSummaryAcceptResponse struct { func (x *StateSummaryAcceptResponse) Reset() { *x = StateSummaryAcceptResponse{} if protoimpl.UnsafeEnabled { - mi := &file_vm_vm_proto_msgTypes[44] + mi := &file_vm_vm_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3007,7 +2791,7 @@ func (x *StateSummaryAcceptResponse) String() string { func (*StateSummaryAcceptResponse) ProtoMessage() {} func (x *StateSummaryAcceptResponse) ProtoReflect() protoreflect.Message { - mi := &file_vm_vm_proto_msgTypes[44] + mi := &file_vm_vm_proto_msgTypes[41] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3020,7 +2804,7 @@ func (x *StateSummaryAcceptResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use StateSummaryAcceptResponse.ProtoReflect.Descriptor instead. func (*StateSummaryAcceptResponse) Descriptor() ([]byte, []int) { - return file_vm_vm_proto_rawDescGZIP(), []int{44} + return file_vm_vm_proto_rawDescGZIP(), []int{41} } func (x *StateSummaryAcceptResponse) GetMode() StateSummaryAcceptResponse_Mode { @@ -3289,292 +3073,249 @@ var file_vm_vm_proto_rawDesc = []byte{ 0x0a, 0x0c, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x4d, 0x73, 0x67, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22, 0xa5, 0x01, 0x0a, 0x17, 0x43, 0x72, - 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, - 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, - 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, - 0x36, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x08, 0x64, - 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x22, 0x9d, 0x01, 0x0a, 0x1d, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, - 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, - 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, - 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, - 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x11, 0x52, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, - 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, - 0x65, 0x22, 0x70, 0x0a, 0x18, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, - 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x12, 0x19, 0x0a, - 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x22, 0x81, 0x01, 0x0a, 0x10, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, - 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, - 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, - 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x6d, - 0x69, 0x6e, 0x6f, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6d, 0x69, 0x6e, 0x6f, - 0x72, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, - 0x52, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x22, 0x2e, 0x0a, 0x13, 0x44, 0x69, 0x73, 0x63, 0x6f, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x03, 0x6d, 0x73, 0x67, 0x22, 0x81, 0x01, 0x0a, 0x10, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x22, 0xb3, 0x01, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x41, - 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, - 0x15, 0x0a, 0x06, 0x62, 0x6c, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x05, 0x62, 0x6c, 0x6b, 0x49, 0x64, 0x12, 0x24, 0x0a, 0x0e, 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, - 0x6f, 0x63, 0x6b, 0x73, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, - 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x4e, 0x75, 0x6d, 0x12, 0x26, 0x0a, 0x0f, - 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, - 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0d, 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, - 0x53, 0x69, 0x7a, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, - 0x6b, 0x73, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x69, 0x76, 0x61, 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x15, 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, - 0x73, 0x52, 0x65, 0x74, 0x72, 0x69, 0x76, 0x61, 0x6c, 0x54, 0x69, 0x6d, 0x65, 0x22, 0x35, 0x0a, - 0x14, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x6c, 0x6b, 0x73, 0x5f, 0x62, 0x79, - 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x09, 0x62, 0x6c, 0x6b, 0x73, 0x42, - 0x79, 0x74, 0x65, 0x73, 0x22, 0x34, 0x0a, 0x18, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, - 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x18, 0x01, 0x20, 0x03, 0x28, - 0x0c, 0x52, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x22, 0x4f, 0x0a, 0x19, 0x42, 0x61, + 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6d, + 0x61, 0x6a, 0x6f, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6d, 0x61, 0x6a, 0x6f, + 0x72, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, + 0x52, 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, + 0x18, 0x05, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x22, 0x2e, 0x0a, + 0x13, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x6e, 0x6f, 0x64, 0x65, 0x49, 0x64, 0x22, 0xb3, 0x01, + 0x0a, 0x13, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x15, 0x0a, 0x06, 0x62, 0x6c, 0x6b, 0x5f, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x6c, 0x6b, 0x49, 0x64, 0x12, 0x24, 0x0a, 0x0e, + 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x5f, 0x6e, 0x75, 0x6d, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x05, 0x52, 0x0c, 0x6d, 0x61, 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x4e, + 0x75, 0x6d, 0x12, 0x26, 0x0a, 0x0f, 0x6d, 0x61, 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, + 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x05, 0x52, 0x0d, 0x6d, 0x61, 0x78, + 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x37, 0x0a, 0x18, 0x6d, 0x61, + 0x78, 0x5f, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x5f, 0x72, 0x65, 0x74, 0x72, 0x69, 0x76, 0x61, + 0x6c, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x03, 0x52, 0x15, 0x6d, 0x61, + 0x78, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x52, 0x65, 0x74, 0x72, 0x69, 0x76, 0x61, 0x6c, 0x54, + 0x69, 0x6d, 0x65, 0x22, 0x35, 0x0a, 0x14, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, + 0x6f, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x62, + 0x6c, 0x6b, 0x73, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, + 0x09, 0x62, 0x6c, 0x6b, 0x73, 0x42, 0x79, 0x74, 0x65, 0x73, 0x22, 0x34, 0x0a, 0x18, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x50, - 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, - 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22, 0x33, 0x0a, 0x19, 0x47, - 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, - 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, - 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, - 0x22, 0x50, 0x0a, 0x1a, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, - 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x15, - 0x0a, 0x06, 0x62, 0x6c, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, - 0x62, 0x6c, 0x6b, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, - 0x72, 0x72, 0x22, 0x5d, 0x0a, 0x0e, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x0f, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x5f, 0x66, - 0x61, 0x6d, 0x69, 0x6c, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, - 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, - 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x46, 0x61, 0x6d, 0x69, 0x6c, - 0x79, 0x52, 0x0e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x46, 0x61, 0x6d, 0x69, 0x6c, 0x69, 0x65, - 0x73, 0x22, 0x51, 0x0a, 0x18, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, 0x6e, 0x63, 0x45, 0x6e, - 0x61, 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, - 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, - 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, - 0x03, 0x65, 0x72, 0x72, 0x22, 0x7f, 0x0a, 0x22, 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, - 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x18, 0x0a, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x07, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x22, 0x4f, 0x0a, 0x19, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, + 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x32, 0x0a, + 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, + 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, + 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x52, 0x08, 0x72, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x22, 0x33, 0x0a, 0x19, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, + 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, + 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, + 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x50, 0x0a, 0x1a, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x73, 0x70, + 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x15, 0x0a, 0x06, 0x62, 0x6c, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x6c, 0x6b, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x03, 0x65, + 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, + 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x5d, 0x0a, 0x0e, 0x47, 0x61, 0x74, 0x68, + 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x0f, 0x6d, 0x65, + 0x74, 0x72, 0x69, 0x63, 0x5f, 0x66, 0x61, 0x6d, 0x69, 0x6c, 0x69, 0x65, 0x73, 0x18, 0x01, 0x20, + 0x03, 0x28, 0x0b, 0x32, 0x22, 0x2e, 0x69, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x6d, 0x65, 0x74, 0x68, + 0x65, 0x75, 0x73, 0x2e, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x2e, 0x4d, 0x65, 0x74, 0x72, 0x69, + 0x63, 0x46, 0x61, 0x6d, 0x69, 0x6c, 0x79, 0x52, 0x0e, 0x6d, 0x65, 0x74, 0x72, 0x69, 0x63, 0x46, + 0x61, 0x6d, 0x69, 0x6c, 0x69, 0x65, 0x73, 0x22, 0x51, 0x0a, 0x18, 0x53, 0x74, 0x61, 0x74, 0x65, + 0x53, 0x79, 0x6e, 0x63, 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x08, 0x52, 0x07, 0x65, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x1b, 0x0a, + 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, + 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x7f, 0x0a, 0x22, 0x47, 0x65, + 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, + 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, + 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, + 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, + 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, + 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, + 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x78, 0x0a, 0x1b, 0x47, + 0x65, 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, - 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x78, 0x0a, 0x1b, 0x47, 0x65, 0x74, 0x4c, 0x61, 0x73, 0x74, + 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x30, 0x0a, 0x18, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, + 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, + 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x22, 0x60, 0x0a, 0x19, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x14, 0x0a, 0x05, - 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, - 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0e, 0x32, - 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, - 0x30, 0x0a, 0x18, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, - 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, - 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, - 0x73, 0x22, 0x60, 0x0a, 0x19, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, - 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, - 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x16, - 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, - 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, - 0x65, 0x72, 0x72, 0x22, 0x30, 0x0a, 0x16, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, - 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, - 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, - 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x5c, 0x0a, 0x17, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, - 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, - 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, - 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, - 0x65, 0x72, 0x72, 0x22, 0x31, 0x0a, 0x19, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, - 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x22, 0xc5, 0x01, 0x0a, 0x1a, 0x53, 0x74, 0x61, 0x74, 0x65, - 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x0e, 0x32, 0x23, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, - 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x2e, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x04, 0x6d, 0x6f, 0x64, 0x65, 0x12, 0x1b, - 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, - 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x51, 0x0a, 0x04, 0x4d, - 0x6f, 0x64, 0x65, 0x12, 0x14, 0x0a, 0x10, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, - 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x4d, 0x4f, 0x44, - 0x45, 0x5f, 0x53, 0x4b, 0x49, 0x50, 0x50, 0x45, 0x44, 0x10, 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x4d, - 0x4f, 0x44, 0x45, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x49, 0x43, 0x10, 0x02, 0x12, 0x10, 0x0a, 0x0c, - 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x44, 0x59, 0x4e, 0x41, 0x4d, 0x49, 0x43, 0x10, 0x03, 0x2a, 0x65, - 0x0a, 0x05, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x15, 0x0a, 0x11, 0x53, 0x54, 0x41, 0x54, 0x45, - 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x17, - 0x0a, 0x13, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x59, - 0x4e, 0x43, 0x49, 0x4e, 0x47, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x53, 0x54, 0x41, 0x54, 0x45, - 0x5f, 0x42, 0x4f, 0x4f, 0x54, 0x53, 0x54, 0x52, 0x41, 0x50, 0x50, 0x49, 0x4e, 0x47, 0x10, 0x02, - 0x12, 0x13, 0x0a, 0x0f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x4e, 0x4f, 0x52, 0x4d, 0x41, 0x4c, - 0x5f, 0x4f, 0x50, 0x10, 0x03, 0x2a, 0x6b, 0x0a, 0x05, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x15, - 0x0a, 0x11, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, - 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x43, - 0x4c, 0x4f, 0x53, 0x45, 0x44, 0x10, 0x01, 0x12, 0x13, 0x0a, 0x0f, 0x45, 0x52, 0x52, 0x4f, 0x52, - 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x46, 0x4f, 0x55, 0x4e, 0x44, 0x10, 0x02, 0x12, 0x24, 0x0a, 0x20, - 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x59, 0x4e, 0x43, - 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x49, 0x4d, 0x50, 0x4c, 0x45, 0x4d, 0x45, 0x4e, 0x54, 0x45, 0x44, - 0x10, 0x03, 0x32, 0x86, 0x11, 0x0a, 0x02, 0x56, 0x4d, 0x12, 0x3b, 0x0a, 0x0a, 0x49, 0x6e, 0x69, - 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x12, 0x15, 0x2e, 0x76, 0x6d, 0x2e, 0x49, 0x6e, 0x69, - 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, - 0x2e, 0x76, 0x6d, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, - 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, - 0x74, 0x65, 0x12, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, - 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3a, 0x0a, - 0x08, 0x53, 0x68, 0x75, 0x74, 0x64, 0x6f, 0x77, 0x6e, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, - 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, - 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x44, 0x0a, 0x0e, 0x43, 0x72, 0x65, - 0x61, 0x74, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x12, 0x16, 0x2e, 0x67, 0x6f, - 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, - 0x70, 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, - 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, - 0x39, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x14, 0x2e, 0x76, - 0x6d, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3f, 0x0a, 0x0c, 0x44, 0x69, - 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, - 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3b, 0x0a, 0x0a, 0x42, - 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x15, 0x2e, 0x76, 0x6d, 0x2e, 0x42, - 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x1a, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3b, 0x0a, 0x0a, 0x50, 0x61, 0x72, 0x73, - 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x15, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, - 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, - 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, - 0x6b, 0x12, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, - 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x41, 0x0a, 0x0d, - 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x12, 0x18, 0x2e, - 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, - 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x20, 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x12, 0x1b, 0x0a, 0x03, + 0x65, 0x72, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, + 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x30, 0x0a, 0x16, 0x47, 0x65, 0x74, + 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x12, 0x16, 0x0a, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x06, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x5c, 0x0a, 0x17, 0x47, + 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, + 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, + 0x28, 0x0c, 0x52, 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x12, 0x1b, 0x0a, 0x03, + 0x65, 0x72, 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, + 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, 0x72, 0x22, 0x31, 0x0a, 0x19, 0x53, 0x74, 0x61, + 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x14, 0x0a, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x05, 0x62, 0x79, 0x74, 0x65, 0x73, 0x22, 0xc5, 0x01, 0x0a, + 0x1a, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, + 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x04, 0x6d, + 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x23, 0x2e, 0x76, 0x6d, 0x2e, 0x53, + 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, + 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x2e, 0x4d, 0x6f, 0x64, 0x65, 0x52, 0x04, + 0x6d, 0x6f, 0x64, 0x65, 0x12, 0x1b, 0x0a, 0x03, 0x65, 0x72, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0e, 0x32, 0x09, 0x2e, 0x76, 0x6d, 0x2e, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x52, 0x03, 0x65, 0x72, + 0x72, 0x22, 0x51, 0x0a, 0x04, 0x4d, 0x6f, 0x64, 0x65, 0x12, 0x14, 0x0a, 0x10, 0x4d, 0x4f, 0x44, + 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, + 0x10, 0x0a, 0x0c, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x53, 0x4b, 0x49, 0x50, 0x50, 0x45, 0x44, 0x10, + 0x01, 0x12, 0x0f, 0x0a, 0x0b, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x53, 0x54, 0x41, 0x54, 0x49, 0x43, + 0x10, 0x02, 0x12, 0x10, 0x0a, 0x0c, 0x4d, 0x4f, 0x44, 0x45, 0x5f, 0x44, 0x59, 0x4e, 0x41, 0x4d, + 0x49, 0x43, 0x10, 0x03, 0x2a, 0x65, 0x0a, 0x05, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x15, 0x0a, + 0x11, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, + 0x45, 0x44, 0x10, 0x00, 0x12, 0x17, 0x0a, 0x13, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x53, 0x54, + 0x41, 0x54, 0x45, 0x5f, 0x53, 0x59, 0x4e, 0x43, 0x49, 0x4e, 0x47, 0x10, 0x01, 0x12, 0x17, 0x0a, + 0x13, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, 0x42, 0x4f, 0x4f, 0x54, 0x53, 0x54, 0x52, 0x41, 0x50, + 0x50, 0x49, 0x4e, 0x47, 0x10, 0x02, 0x12, 0x13, 0x0a, 0x0f, 0x53, 0x54, 0x41, 0x54, 0x45, 0x5f, + 0x4e, 0x4f, 0x52, 0x4d, 0x41, 0x4c, 0x5f, 0x4f, 0x50, 0x10, 0x03, 0x2a, 0x6b, 0x0a, 0x05, 0x45, + 0x72, 0x72, 0x6f, 0x72, 0x12, 0x15, 0x0a, 0x11, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x55, 0x4e, + 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x10, 0x0a, 0x0c, 0x45, + 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x43, 0x4c, 0x4f, 0x53, 0x45, 0x44, 0x10, 0x01, 0x12, 0x13, 0x0a, + 0x0f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x46, 0x4f, 0x55, 0x4e, 0x44, + 0x10, 0x02, 0x12, 0x24, 0x0a, 0x20, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x5f, 0x53, 0x54, 0x41, 0x54, + 0x45, 0x5f, 0x53, 0x59, 0x4e, 0x43, 0x5f, 0x4e, 0x4f, 0x54, 0x5f, 0x49, 0x4d, 0x50, 0x4c, 0x45, + 0x4d, 0x45, 0x4e, 0x54, 0x45, 0x44, 0x10, 0x03, 0x32, 0x91, 0x0f, 0x0a, 0x02, 0x56, 0x4d, 0x12, + 0x3b, 0x0a, 0x0a, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x12, 0x15, 0x2e, + 0x76, 0x6d, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x49, 0x6e, 0x69, 0x74, 0x69, 0x61, + 0x6c, 0x69, 0x7a, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, + 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x12, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x65, + 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, + 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x3a, 0x0a, 0x08, 0x53, 0x68, 0x75, 0x74, 0x64, 0x6f, 0x77, 0x6e, 0x12, + 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, - 0x34, 0x0a, 0x06, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x44, 0x0a, 0x0e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, + 0x73, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, + 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1a, 0x2e, 0x76, 0x6d, 0x2e, 0x43, + 0x72, 0x65, 0x61, 0x74, 0x65, 0x48, 0x61, 0x6e, 0x64, 0x6c, 0x65, 0x72, 0x73, 0x52, 0x65, 0x73, + 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x65, 0x64, 0x12, 0x14, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, + 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, + 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, + 0x12, 0x3f, 0x0a, 0x0c, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x65, 0x64, + 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, + 0x65, 0x64, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, - 0x79, 0x1a, 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x52, 0x65, 0x73, - 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, - 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x56, 0x65, - 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, - 0x0a, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x11, 0x2e, 0x76, 0x6d, - 0x2e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x16, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x43, 0x0a, 0x10, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, + 0x79, 0x12, 0x3b, 0x0a, 0x0a, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, + 0x15, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x75, 0x69, 0x6c, + 0x64, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3b, + 0x0a, 0x0a, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x15, 0x2e, 0x76, + 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, + 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x35, 0x0a, 0x08, 0x47, + 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x12, 0x13, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, + 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x14, 0x2e, 0x76, + 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, + 0x73, 0x65, 0x12, 0x41, 0x0a, 0x0d, 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, 0x65, 0x72, 0x65, + 0x6e, 0x63, 0x65, 0x12, 0x18, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x65, 0x74, 0x50, 0x72, 0x65, 0x66, + 0x65, 0x72, 0x65, 0x6e, 0x63, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x34, 0x0a, 0x06, 0x48, 0x65, 0x61, 0x6c, 0x74, 0x68, 0x12, + 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, + 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x48, 0x65, 0x61, + 0x6c, 0x74, 0x68, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x36, 0x0a, 0x07, 0x56, + 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x13, + 0x2e, 0x76, 0x6d, 0x2e, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x37, 0x0a, 0x0a, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x12, 0x11, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x43, 0x0a, 0x10, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, - 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x39, 0x0a, 0x0b, 0x41, - 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x12, 0x2e, 0x76, 0x6d, 0x2e, - 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, 0x1a, 0x16, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x35, 0x0a, 0x09, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, - 0x73, 0x69, 0x70, 0x12, 0x10, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, - 0x69, 0x70, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x34, 0x0a, - 0x06, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, + 0x79, 0x12, 0x39, 0x0a, 0x0b, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, + 0x12, 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, + 0x65, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, + 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x35, 0x0a, 0x09, + 0x41, 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x12, 0x10, 0x2e, 0x76, 0x6d, 0x2e, 0x41, + 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, + 0x70, 0x74, 0x79, 0x12, 0x34, 0x0a, 0x06, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, 0x12, 0x16, 0x2e, + 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, + 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x61, 0x74, 0x68, 0x65, + 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x41, 0x0a, 0x0c, 0x47, 0x65, 0x74, + 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x47, + 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x18, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, + 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x11, + 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, + 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x1d, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, + 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x53, + 0x0a, 0x12, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, + 0x69, 0x67, 0x68, 0x74, 0x12, 0x1d, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x1e, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, + 0x6e, 0x73, 0x65, 0x12, 0x48, 0x0a, 0x10, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, 0x6e, 0x63, + 0x45, 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, - 0x12, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x61, 0x74, 0x68, 0x65, 0x72, 0x52, 0x65, 0x73, 0x70, 0x6f, - 0x6e, 0x73, 0x65, 0x12, 0x4b, 0x0a, 0x14, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, - 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x2e, 0x76, 0x6d, - 0x2e, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x4d, 0x73, 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, - 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, - 0x12, 0x57, 0x0a, 0x1a, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, - 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x12, 0x21, - 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, - 0x70, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x46, 0x61, 0x69, 0x6c, 0x65, 0x64, 0x4d, 0x73, - 0x67, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x4d, 0x0a, 0x15, 0x43, 0x72, 0x6f, - 0x73, 0x73, 0x43, 0x68, 0x61, 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x43, 0x72, 0x6f, 0x73, 0x73, 0x43, 0x68, 0x61, - 0x69, 0x6e, 0x41, 0x70, 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x4d, 0x73, 0x67, - 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, - 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x41, 0x0a, 0x0c, 0x47, 0x65, 0x74, 0x41, - 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, - 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x1a, 0x18, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, - 0x6f, 0x72, 0x73, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x11, 0x42, - 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, - 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, - 0x73, 0x65, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, - 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64, 0x50, 0x61, 0x72, 0x73, 0x65, - 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x53, 0x0a, - 0x12, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, - 0x67, 0x68, 0x74, 0x12, 0x1d, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, - 0x6b, 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x1a, 0x1e, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x42, 0x6c, 0x6f, 0x63, 0x6b, - 0x49, 0x44, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, - 0x73, 0x65, 0x12, 0x48, 0x0a, 0x10, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, 0x6e, 0x63, 0x45, - 0x6e, 0x61, 0x62, 0x6c, 0x65, 0x64, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1c, - 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, 0x6e, 0x63, 0x45, 0x6e, 0x61, - 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5c, 0x0a, 0x1a, - 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, - 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, - 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, - 0x74, 0x79, 0x1a, 0x26, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, - 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, - 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4e, 0x0a, 0x13, 0x47, 0x65, - 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, - 0x79, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1f, 0x2e, 0x76, 0x6d, 0x2e, 0x47, + 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x79, 0x6e, 0x63, 0x45, 0x6e, + 0x61, 0x62, 0x6c, 0x65, 0x64, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x5c, 0x0a, + 0x1a, 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, 0x69, 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, + 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, 0x16, 0x2e, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, + 0x70, 0x74, 0x79, 0x1a, 0x26, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x4f, 0x6e, 0x67, 0x6f, + 0x69, 0x6e, 0x67, 0x53, 0x79, 0x6e, 0x63, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, + 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4e, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, - 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x11, 0x50, 0x61, - 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, - 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, - 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, - 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, - 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4a, 0x0a, 0x0f, - 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, - 0x1a, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, - 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1b, 0x2e, 0x76, 0x6d, - 0x2e, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, - 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, - 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, - 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, - 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, - 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, - 0x63, 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, + 0x72, 0x79, 0x12, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, + 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x1a, 0x1f, 0x2e, 0x76, 0x6d, 0x2e, + 0x47, 0x65, 0x74, 0x4c, 0x61, 0x73, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, + 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x50, 0x0a, 0x11, 0x50, + 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, + 0x12, 0x1c, 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, + 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, + 0x2e, 0x76, 0x6d, 0x2e, 0x50, 0x61, 0x72, 0x73, 0x65, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, + 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x4a, 0x0a, + 0x0f, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, + 0x12, 0x1a, 0x2e, 0x76, 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, + 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1b, 0x2e, 0x76, + 0x6d, 0x2e, 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, + 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3e, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, + 0x6f, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x17, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, 0x63, 0x6b, 0x56, 0x65, 0x72, 0x69, 0x66, + 0x79, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x3d, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, + 0x6f, 0x63, 0x6b, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, + 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, + 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3d, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, + 0x6b, 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, + 0x63, 0x6b, 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, - 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x3d, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x63, 0x6b, - 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x16, 0x2e, 0x76, 0x6d, 0x2e, 0x42, 0x6c, 0x6f, 0x63, - 0x6b, 0x52, 0x65, 0x6a, 0x65, 0x63, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, - 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x53, 0x0a, 0x12, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, - 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x12, 0x1d, 0x2e, 0x76, + 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x12, 0x53, 0x0a, 0x12, 0x53, 0x74, 0x61, 0x74, 0x65, + 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x12, 0x1d, 0x2e, + 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, + 0x63, 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1e, 0x2e, 0x76, 0x6d, 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, - 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1e, 0x2e, 0x76, 0x6d, - 0x2e, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x41, 0x63, 0x63, - 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x2d, 0x5a, 0x2b, 0x67, - 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x76, 0x61, 0x2d, 0x6c, 0x61, - 0x62, 0x73, 0x2f, 0x61, 0x76, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x68, 0x65, 0x67, 0x6f, 0x2f, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x70, 0x62, 0x2f, 0x76, 0x6d, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, - 0x6f, 0x33, + 0x63, 0x65, 0x70, 0x74, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x42, 0x2d, 0x5a, 0x2b, + 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x76, 0x61, 0x2d, 0x6c, + 0x61, 0x62, 0x73, 0x2f, 0x61, 0x76, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x68, 0x65, 0x67, 0x6f, 0x2f, + 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x70, 0x62, 0x2f, 0x76, 0x6d, 0x62, 0x06, 0x70, 0x72, 0x6f, + 0x74, 0x6f, 0x33, } var ( @@ -3590,7 +3331,7 @@ func file_vm_vm_proto_rawDescGZIP() []byte { } var file_vm_vm_proto_enumTypes = make([]protoimpl.EnumInfo, 3) -var file_vm_vm_proto_msgTypes = make([]protoimpl.MessageInfo, 45) +var file_vm_vm_proto_msgTypes = make([]protoimpl.MessageInfo, 42) var file_vm_vm_proto_goTypes = []interface{}{ (State)(0), // 0: vm.State (Error)(0), // 1: vm.Error @@ -3619,135 +3360,125 @@ var file_vm_vm_proto_goTypes = []interface{}{ (*AppRequestFailedMsg)(nil), // 24: vm.AppRequestFailedMsg (*AppResponseMsg)(nil), // 25: vm.AppResponseMsg (*AppGossipMsg)(nil), // 26: vm.AppGossipMsg - (*CrossChainAppRequestMsg)(nil), // 27: vm.CrossChainAppRequestMsg - (*CrossChainAppRequestFailedMsg)(nil), // 28: vm.CrossChainAppRequestFailedMsg - (*CrossChainAppResponseMsg)(nil), // 29: vm.CrossChainAppResponseMsg - (*ConnectedRequest)(nil), // 30: vm.ConnectedRequest - (*DisconnectedRequest)(nil), // 31: vm.DisconnectedRequest - (*GetAncestorsRequest)(nil), // 32: vm.GetAncestorsRequest - (*GetAncestorsResponse)(nil), // 33: vm.GetAncestorsResponse - (*BatchedParseBlockRequest)(nil), // 34: vm.BatchedParseBlockRequest - (*BatchedParseBlockResponse)(nil), // 35: vm.BatchedParseBlockResponse - (*GetBlockIDAtHeightRequest)(nil), // 36: vm.GetBlockIDAtHeightRequest - (*GetBlockIDAtHeightResponse)(nil), // 37: vm.GetBlockIDAtHeightResponse - (*GatherResponse)(nil), // 38: vm.GatherResponse - (*StateSyncEnabledResponse)(nil), // 39: vm.StateSyncEnabledResponse - (*GetOngoingSyncStateSummaryResponse)(nil), // 40: vm.GetOngoingSyncStateSummaryResponse - (*GetLastStateSummaryResponse)(nil), // 41: vm.GetLastStateSummaryResponse - (*ParseStateSummaryRequest)(nil), // 42: vm.ParseStateSummaryRequest - (*ParseStateSummaryResponse)(nil), // 43: vm.ParseStateSummaryResponse - (*GetStateSummaryRequest)(nil), // 44: vm.GetStateSummaryRequest - (*GetStateSummaryResponse)(nil), // 45: vm.GetStateSummaryResponse - (*StateSummaryAcceptRequest)(nil), // 46: vm.StateSummaryAcceptRequest - (*StateSummaryAcceptResponse)(nil), // 47: vm.StateSummaryAcceptResponse - (*timestamppb.Timestamp)(nil), // 48: google.protobuf.Timestamp - (*_go.MetricFamily)(nil), // 49: io.prometheus.client.MetricFamily - (*emptypb.Empty)(nil), // 50: google.protobuf.Empty + (*ConnectedRequest)(nil), // 27: vm.ConnectedRequest + (*DisconnectedRequest)(nil), // 28: vm.DisconnectedRequest + (*GetAncestorsRequest)(nil), // 29: vm.GetAncestorsRequest + (*GetAncestorsResponse)(nil), // 30: vm.GetAncestorsResponse + (*BatchedParseBlockRequest)(nil), // 31: vm.BatchedParseBlockRequest + (*BatchedParseBlockResponse)(nil), // 32: vm.BatchedParseBlockResponse + (*GetBlockIDAtHeightRequest)(nil), // 33: vm.GetBlockIDAtHeightRequest + (*GetBlockIDAtHeightResponse)(nil), // 34: vm.GetBlockIDAtHeightResponse + (*GatherResponse)(nil), // 35: vm.GatherResponse + (*StateSyncEnabledResponse)(nil), // 36: vm.StateSyncEnabledResponse + (*GetOngoingSyncStateSummaryResponse)(nil), // 37: vm.GetOngoingSyncStateSummaryResponse + (*GetLastStateSummaryResponse)(nil), // 38: vm.GetLastStateSummaryResponse + (*ParseStateSummaryRequest)(nil), // 39: vm.ParseStateSummaryRequest + (*ParseStateSummaryResponse)(nil), // 40: vm.ParseStateSummaryResponse + (*GetStateSummaryRequest)(nil), // 41: vm.GetStateSummaryRequest + (*GetStateSummaryResponse)(nil), // 42: vm.GetStateSummaryResponse + (*StateSummaryAcceptRequest)(nil), // 43: vm.StateSummaryAcceptRequest + (*StateSummaryAcceptResponse)(nil), // 44: vm.StateSummaryAcceptResponse + (*timestamppb.Timestamp)(nil), // 45: google.protobuf.Timestamp + (*_go.MetricFamily)(nil), // 46: io.prometheus.client.MetricFamily + (*emptypb.Empty)(nil), // 47: google.protobuf.Empty } var file_vm_vm_proto_depIdxs = []int32{ 4, // 0: vm.InitializeRequest.network_upgrades:type_name -> vm.NetworkUpgrades - 48, // 1: vm.NetworkUpgrades.apricot_phase_1_time:type_name -> google.protobuf.Timestamp - 48, // 2: vm.NetworkUpgrades.apricot_phase_2_time:type_name -> google.protobuf.Timestamp - 48, // 3: vm.NetworkUpgrades.apricot_phase_3_time:type_name -> google.protobuf.Timestamp - 48, // 4: vm.NetworkUpgrades.apricot_phase_4_time:type_name -> google.protobuf.Timestamp - 48, // 5: vm.NetworkUpgrades.apricot_phase_5_time:type_name -> google.protobuf.Timestamp - 48, // 6: vm.NetworkUpgrades.apricot_phase_pre_6_time:type_name -> google.protobuf.Timestamp - 48, // 7: vm.NetworkUpgrades.apricot_phase_6_time:type_name -> google.protobuf.Timestamp - 48, // 8: vm.NetworkUpgrades.apricot_phase_post_6_time:type_name -> google.protobuf.Timestamp - 48, // 9: vm.NetworkUpgrades.banff_time:type_name -> google.protobuf.Timestamp - 48, // 10: vm.NetworkUpgrades.cortina_time:type_name -> google.protobuf.Timestamp - 48, // 11: vm.NetworkUpgrades.durango_time:type_name -> google.protobuf.Timestamp - 48, // 12: vm.NetworkUpgrades.etna_time:type_name -> google.protobuf.Timestamp - 48, // 13: vm.InitializeResponse.timestamp:type_name -> google.protobuf.Timestamp + 45, // 1: vm.NetworkUpgrades.apricot_phase_1_time:type_name -> google.protobuf.Timestamp + 45, // 2: vm.NetworkUpgrades.apricot_phase_2_time:type_name -> google.protobuf.Timestamp + 45, // 3: vm.NetworkUpgrades.apricot_phase_3_time:type_name -> google.protobuf.Timestamp + 45, // 4: vm.NetworkUpgrades.apricot_phase_4_time:type_name -> google.protobuf.Timestamp + 45, // 5: vm.NetworkUpgrades.apricot_phase_5_time:type_name -> google.protobuf.Timestamp + 45, // 6: vm.NetworkUpgrades.apricot_phase_pre_6_time:type_name -> google.protobuf.Timestamp + 45, // 7: vm.NetworkUpgrades.apricot_phase_6_time:type_name -> google.protobuf.Timestamp + 45, // 8: vm.NetworkUpgrades.apricot_phase_post_6_time:type_name -> google.protobuf.Timestamp + 45, // 9: vm.NetworkUpgrades.banff_time:type_name -> google.protobuf.Timestamp + 45, // 10: vm.NetworkUpgrades.cortina_time:type_name -> google.protobuf.Timestamp + 45, // 11: vm.NetworkUpgrades.durango_time:type_name -> google.protobuf.Timestamp + 45, // 12: vm.NetworkUpgrades.etna_time:type_name -> google.protobuf.Timestamp + 45, // 13: vm.InitializeResponse.timestamp:type_name -> google.protobuf.Timestamp 0, // 14: vm.SetStateRequest.state:type_name -> vm.State - 48, // 15: vm.SetStateResponse.timestamp:type_name -> google.protobuf.Timestamp + 45, // 15: vm.SetStateResponse.timestamp:type_name -> google.protobuf.Timestamp 9, // 16: vm.CreateHandlersResponse.handlers:type_name -> vm.Handler - 48, // 17: vm.BuildBlockResponse.timestamp:type_name -> google.protobuf.Timestamp - 48, // 18: vm.ParseBlockResponse.timestamp:type_name -> google.protobuf.Timestamp - 48, // 19: vm.GetBlockResponse.timestamp:type_name -> google.protobuf.Timestamp + 45, // 17: vm.BuildBlockResponse.timestamp:type_name -> google.protobuf.Timestamp + 45, // 18: vm.ParseBlockResponse.timestamp:type_name -> google.protobuf.Timestamp + 45, // 19: vm.GetBlockResponse.timestamp:type_name -> google.protobuf.Timestamp 1, // 20: vm.GetBlockResponse.err:type_name -> vm.Error - 48, // 21: vm.BlockVerifyResponse.timestamp:type_name -> google.protobuf.Timestamp - 48, // 22: vm.AppRequestMsg.deadline:type_name -> google.protobuf.Timestamp - 48, // 23: vm.CrossChainAppRequestMsg.deadline:type_name -> google.protobuf.Timestamp - 13, // 24: vm.BatchedParseBlockResponse.response:type_name -> vm.ParseBlockResponse - 1, // 25: vm.GetBlockIDAtHeightResponse.err:type_name -> vm.Error - 49, // 26: vm.GatherResponse.metric_families:type_name -> io.prometheus.client.MetricFamily - 1, // 27: vm.StateSyncEnabledResponse.err:type_name -> vm.Error - 1, // 28: vm.GetOngoingSyncStateSummaryResponse.err:type_name -> vm.Error - 1, // 29: vm.GetLastStateSummaryResponse.err:type_name -> vm.Error - 1, // 30: vm.ParseStateSummaryResponse.err:type_name -> vm.Error - 1, // 31: vm.GetStateSummaryResponse.err:type_name -> vm.Error - 2, // 32: vm.StateSummaryAcceptResponse.mode:type_name -> vm.StateSummaryAcceptResponse.Mode - 1, // 33: vm.StateSummaryAcceptResponse.err:type_name -> vm.Error - 3, // 34: vm.VM.Initialize:input_type -> vm.InitializeRequest - 6, // 35: vm.VM.SetState:input_type -> vm.SetStateRequest - 50, // 36: vm.VM.Shutdown:input_type -> google.protobuf.Empty - 50, // 37: vm.VM.CreateHandlers:input_type -> google.protobuf.Empty - 30, // 38: vm.VM.Connected:input_type -> vm.ConnectedRequest - 31, // 39: vm.VM.Disconnected:input_type -> vm.DisconnectedRequest - 10, // 40: vm.VM.BuildBlock:input_type -> vm.BuildBlockRequest - 12, // 41: vm.VM.ParseBlock:input_type -> vm.ParseBlockRequest - 14, // 42: vm.VM.GetBlock:input_type -> vm.GetBlockRequest - 16, // 43: vm.VM.SetPreference:input_type -> vm.SetPreferenceRequest - 50, // 44: vm.VM.Health:input_type -> google.protobuf.Empty - 50, // 45: vm.VM.Version:input_type -> google.protobuf.Empty - 23, // 46: vm.VM.AppRequest:input_type -> vm.AppRequestMsg - 24, // 47: vm.VM.AppRequestFailed:input_type -> vm.AppRequestFailedMsg - 25, // 48: vm.VM.AppResponse:input_type -> vm.AppResponseMsg - 26, // 49: vm.VM.AppGossip:input_type -> vm.AppGossipMsg - 50, // 50: vm.VM.Gather:input_type -> google.protobuf.Empty - 27, // 51: vm.VM.CrossChainAppRequest:input_type -> vm.CrossChainAppRequestMsg - 28, // 52: vm.VM.CrossChainAppRequestFailed:input_type -> vm.CrossChainAppRequestFailedMsg - 29, // 53: vm.VM.CrossChainAppResponse:input_type -> vm.CrossChainAppResponseMsg - 32, // 54: vm.VM.GetAncestors:input_type -> vm.GetAncestorsRequest - 34, // 55: vm.VM.BatchedParseBlock:input_type -> vm.BatchedParseBlockRequest - 36, // 56: vm.VM.GetBlockIDAtHeight:input_type -> vm.GetBlockIDAtHeightRequest - 50, // 57: vm.VM.StateSyncEnabled:input_type -> google.protobuf.Empty - 50, // 58: vm.VM.GetOngoingSyncStateSummary:input_type -> google.protobuf.Empty - 50, // 59: vm.VM.GetLastStateSummary:input_type -> google.protobuf.Empty - 42, // 60: vm.VM.ParseStateSummary:input_type -> vm.ParseStateSummaryRequest - 44, // 61: vm.VM.GetStateSummary:input_type -> vm.GetStateSummaryRequest - 17, // 62: vm.VM.BlockVerify:input_type -> vm.BlockVerifyRequest - 19, // 63: vm.VM.BlockAccept:input_type -> vm.BlockAcceptRequest - 20, // 64: vm.VM.BlockReject:input_type -> vm.BlockRejectRequest - 46, // 65: vm.VM.StateSummaryAccept:input_type -> vm.StateSummaryAcceptRequest - 5, // 66: vm.VM.Initialize:output_type -> vm.InitializeResponse - 7, // 67: vm.VM.SetState:output_type -> vm.SetStateResponse - 50, // 68: vm.VM.Shutdown:output_type -> google.protobuf.Empty - 8, // 69: vm.VM.CreateHandlers:output_type -> vm.CreateHandlersResponse - 50, // 70: vm.VM.Connected:output_type -> google.protobuf.Empty - 50, // 71: vm.VM.Disconnected:output_type -> google.protobuf.Empty - 11, // 72: vm.VM.BuildBlock:output_type -> vm.BuildBlockResponse - 13, // 73: vm.VM.ParseBlock:output_type -> vm.ParseBlockResponse - 15, // 74: vm.VM.GetBlock:output_type -> vm.GetBlockResponse - 50, // 75: vm.VM.SetPreference:output_type -> google.protobuf.Empty - 21, // 76: vm.VM.Health:output_type -> vm.HealthResponse - 22, // 77: vm.VM.Version:output_type -> vm.VersionResponse - 50, // 78: vm.VM.AppRequest:output_type -> google.protobuf.Empty - 50, // 79: vm.VM.AppRequestFailed:output_type -> google.protobuf.Empty - 50, // 80: vm.VM.AppResponse:output_type -> google.protobuf.Empty - 50, // 81: vm.VM.AppGossip:output_type -> google.protobuf.Empty - 38, // 82: vm.VM.Gather:output_type -> vm.GatherResponse - 50, // 83: vm.VM.CrossChainAppRequest:output_type -> google.protobuf.Empty - 50, // 84: vm.VM.CrossChainAppRequestFailed:output_type -> google.protobuf.Empty - 50, // 85: vm.VM.CrossChainAppResponse:output_type -> google.protobuf.Empty - 33, // 86: vm.VM.GetAncestors:output_type -> vm.GetAncestorsResponse - 35, // 87: vm.VM.BatchedParseBlock:output_type -> vm.BatchedParseBlockResponse - 37, // 88: vm.VM.GetBlockIDAtHeight:output_type -> vm.GetBlockIDAtHeightResponse - 39, // 89: vm.VM.StateSyncEnabled:output_type -> vm.StateSyncEnabledResponse - 40, // 90: vm.VM.GetOngoingSyncStateSummary:output_type -> vm.GetOngoingSyncStateSummaryResponse - 41, // 91: vm.VM.GetLastStateSummary:output_type -> vm.GetLastStateSummaryResponse - 43, // 92: vm.VM.ParseStateSummary:output_type -> vm.ParseStateSummaryResponse - 45, // 93: vm.VM.GetStateSummary:output_type -> vm.GetStateSummaryResponse - 18, // 94: vm.VM.BlockVerify:output_type -> vm.BlockVerifyResponse - 50, // 95: vm.VM.BlockAccept:output_type -> google.protobuf.Empty - 50, // 96: vm.VM.BlockReject:output_type -> google.protobuf.Empty - 47, // 97: vm.VM.StateSummaryAccept:output_type -> vm.StateSummaryAcceptResponse - 66, // [66:98] is the sub-list for method output_type - 34, // [34:66] is the sub-list for method input_type - 34, // [34:34] is the sub-list for extension type_name - 34, // [34:34] is the sub-list for extension extendee - 0, // [0:34] is the sub-list for field type_name + 45, // 21: vm.BlockVerifyResponse.timestamp:type_name -> google.protobuf.Timestamp + 45, // 22: vm.AppRequestMsg.deadline:type_name -> google.protobuf.Timestamp + 13, // 23: vm.BatchedParseBlockResponse.response:type_name -> vm.ParseBlockResponse + 1, // 24: vm.GetBlockIDAtHeightResponse.err:type_name -> vm.Error + 46, // 25: vm.GatherResponse.metric_families:type_name -> io.prometheus.client.MetricFamily + 1, // 26: vm.StateSyncEnabledResponse.err:type_name -> vm.Error + 1, // 27: vm.GetOngoingSyncStateSummaryResponse.err:type_name -> vm.Error + 1, // 28: vm.GetLastStateSummaryResponse.err:type_name -> vm.Error + 1, // 29: vm.ParseStateSummaryResponse.err:type_name -> vm.Error + 1, // 30: vm.GetStateSummaryResponse.err:type_name -> vm.Error + 2, // 31: vm.StateSummaryAcceptResponse.mode:type_name -> vm.StateSummaryAcceptResponse.Mode + 1, // 32: vm.StateSummaryAcceptResponse.err:type_name -> vm.Error + 3, // 33: vm.VM.Initialize:input_type -> vm.InitializeRequest + 6, // 34: vm.VM.SetState:input_type -> vm.SetStateRequest + 47, // 35: vm.VM.Shutdown:input_type -> google.protobuf.Empty + 47, // 36: vm.VM.CreateHandlers:input_type -> google.protobuf.Empty + 27, // 37: vm.VM.Connected:input_type -> vm.ConnectedRequest + 28, // 38: vm.VM.Disconnected:input_type -> vm.DisconnectedRequest + 10, // 39: vm.VM.BuildBlock:input_type -> vm.BuildBlockRequest + 12, // 40: vm.VM.ParseBlock:input_type -> vm.ParseBlockRequest + 14, // 41: vm.VM.GetBlock:input_type -> vm.GetBlockRequest + 16, // 42: vm.VM.SetPreference:input_type -> vm.SetPreferenceRequest + 47, // 43: vm.VM.Health:input_type -> google.protobuf.Empty + 47, // 44: vm.VM.Version:input_type -> google.protobuf.Empty + 23, // 45: vm.VM.AppRequest:input_type -> vm.AppRequestMsg + 24, // 46: vm.VM.AppRequestFailed:input_type -> vm.AppRequestFailedMsg + 25, // 47: vm.VM.AppResponse:input_type -> vm.AppResponseMsg + 26, // 48: vm.VM.AppGossip:input_type -> vm.AppGossipMsg + 47, // 49: vm.VM.Gather:input_type -> google.protobuf.Empty + 29, // 50: vm.VM.GetAncestors:input_type -> vm.GetAncestorsRequest + 31, // 51: vm.VM.BatchedParseBlock:input_type -> vm.BatchedParseBlockRequest + 33, // 52: vm.VM.GetBlockIDAtHeight:input_type -> vm.GetBlockIDAtHeightRequest + 47, // 53: vm.VM.StateSyncEnabled:input_type -> google.protobuf.Empty + 47, // 54: vm.VM.GetOngoingSyncStateSummary:input_type -> google.protobuf.Empty + 47, // 55: vm.VM.GetLastStateSummary:input_type -> google.protobuf.Empty + 39, // 56: vm.VM.ParseStateSummary:input_type -> vm.ParseStateSummaryRequest + 41, // 57: vm.VM.GetStateSummary:input_type -> vm.GetStateSummaryRequest + 17, // 58: vm.VM.BlockVerify:input_type -> vm.BlockVerifyRequest + 19, // 59: vm.VM.BlockAccept:input_type -> vm.BlockAcceptRequest + 20, // 60: vm.VM.BlockReject:input_type -> vm.BlockRejectRequest + 43, // 61: vm.VM.StateSummaryAccept:input_type -> vm.StateSummaryAcceptRequest + 5, // 62: vm.VM.Initialize:output_type -> vm.InitializeResponse + 7, // 63: vm.VM.SetState:output_type -> vm.SetStateResponse + 47, // 64: vm.VM.Shutdown:output_type -> google.protobuf.Empty + 8, // 65: vm.VM.CreateHandlers:output_type -> vm.CreateHandlersResponse + 47, // 66: vm.VM.Connected:output_type -> google.protobuf.Empty + 47, // 67: vm.VM.Disconnected:output_type -> google.protobuf.Empty + 11, // 68: vm.VM.BuildBlock:output_type -> vm.BuildBlockResponse + 13, // 69: vm.VM.ParseBlock:output_type -> vm.ParseBlockResponse + 15, // 70: vm.VM.GetBlock:output_type -> vm.GetBlockResponse + 47, // 71: vm.VM.SetPreference:output_type -> google.protobuf.Empty + 21, // 72: vm.VM.Health:output_type -> vm.HealthResponse + 22, // 73: vm.VM.Version:output_type -> vm.VersionResponse + 47, // 74: vm.VM.AppRequest:output_type -> google.protobuf.Empty + 47, // 75: vm.VM.AppRequestFailed:output_type -> google.protobuf.Empty + 47, // 76: vm.VM.AppResponse:output_type -> google.protobuf.Empty + 47, // 77: vm.VM.AppGossip:output_type -> google.protobuf.Empty + 35, // 78: vm.VM.Gather:output_type -> vm.GatherResponse + 30, // 79: vm.VM.GetAncestors:output_type -> vm.GetAncestorsResponse + 32, // 80: vm.VM.BatchedParseBlock:output_type -> vm.BatchedParseBlockResponse + 34, // 81: vm.VM.GetBlockIDAtHeight:output_type -> vm.GetBlockIDAtHeightResponse + 36, // 82: vm.VM.StateSyncEnabled:output_type -> vm.StateSyncEnabledResponse + 37, // 83: vm.VM.GetOngoingSyncStateSummary:output_type -> vm.GetOngoingSyncStateSummaryResponse + 38, // 84: vm.VM.GetLastStateSummary:output_type -> vm.GetLastStateSummaryResponse + 40, // 85: vm.VM.ParseStateSummary:output_type -> vm.ParseStateSummaryResponse + 42, // 86: vm.VM.GetStateSummary:output_type -> vm.GetStateSummaryResponse + 18, // 87: vm.VM.BlockVerify:output_type -> vm.BlockVerifyResponse + 47, // 88: vm.VM.BlockAccept:output_type -> google.protobuf.Empty + 47, // 89: vm.VM.BlockReject:output_type -> google.protobuf.Empty + 44, // 90: vm.VM.StateSummaryAccept:output_type -> vm.StateSummaryAcceptResponse + 62, // [62:91] is the sub-list for method output_type + 33, // [33:62] is the sub-list for method input_type + 33, // [33:33] is the sub-list for extension type_name + 33, // [33:33] is the sub-list for extension extendee + 0, // [0:33] is the sub-list for field type_name } func init() { file_vm_vm_proto_init() } @@ -4045,42 +3776,6 @@ func file_vm_vm_proto_init() { } } file_vm_vm_proto_msgTypes[24].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CrossChainAppRequestMsg); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_vm_vm_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CrossChainAppRequestFailedMsg); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_vm_vm_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { - switch v := v.(*CrossChainAppResponseMsg); i { - case 0: - return &v.state - case 1: - return &v.sizeCache - case 2: - return &v.unknownFields - default: - return nil - } - } - file_vm_vm_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ConnectedRequest); i { case 0: return &v.state @@ -4092,7 +3787,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[25].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DisconnectedRequest); i { case 0: return &v.state @@ -4104,7 +3799,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[26].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetAncestorsRequest); i { case 0: return &v.state @@ -4116,7 +3811,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[27].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetAncestorsResponse); i { case 0: return &v.state @@ -4128,7 +3823,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[28].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BatchedParseBlockRequest); i { case 0: return &v.state @@ -4140,7 +3835,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[29].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*BatchedParseBlockResponse); i { case 0: return &v.state @@ -4152,7 +3847,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[33].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[30].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetBlockIDAtHeightRequest); i { case 0: return &v.state @@ -4164,7 +3859,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[31].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetBlockIDAtHeightResponse); i { case 0: return &v.state @@ -4176,7 +3871,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[35].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[32].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GatherResponse); i { case 0: return &v.state @@ -4188,7 +3883,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[36].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[33].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StateSyncEnabledResponse); i { case 0: return &v.state @@ -4200,7 +3895,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[37].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[34].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetOngoingSyncStateSummaryResponse); i { case 0: return &v.state @@ -4212,7 +3907,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[38].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[35].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetLastStateSummaryResponse); i { case 0: return &v.state @@ -4224,7 +3919,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[39].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[36].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ParseStateSummaryRequest); i { case 0: return &v.state @@ -4236,7 +3931,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[40].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[37].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*ParseStateSummaryResponse); i { case 0: return &v.state @@ -4248,7 +3943,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[41].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[38].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetStateSummaryRequest); i { case 0: return &v.state @@ -4260,7 +3955,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[42].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[39].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*GetStateSummaryResponse); i { case 0: return &v.state @@ -4272,7 +3967,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[43].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[40].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StateSummaryAcceptRequest); i { case 0: return &v.state @@ -4284,7 +3979,7 @@ func file_vm_vm_proto_init() { return nil } } - file_vm_vm_proto_msgTypes[44].Exporter = func(v interface{}, i int) interface{} { + file_vm_vm_proto_msgTypes[41].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*StateSummaryAcceptResponse); i { case 0: return &v.state @@ -4305,7 +4000,7 @@ func file_vm_vm_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_vm_vm_proto_rawDesc, NumEnums: 3, - NumMessages: 45, + NumMessages: 42, NumExtensions: 0, NumServices: 1, }, diff --git a/proto/pb/vm/vm_grpc.pb.go b/proto/pb/vm/vm_grpc.pb.go index 4a67f13408ce..f1b43307faab 100644 --- a/proto/pb/vm/vm_grpc.pb.go +++ b/proto/pb/vm/vm_grpc.pb.go @@ -37,9 +37,6 @@ const ( VM_AppResponse_FullMethodName = "/vm.VM/AppResponse" VM_AppGossip_FullMethodName = "/vm.VM/AppGossip" VM_Gather_FullMethodName = "/vm.VM/Gather" - VM_CrossChainAppRequest_FullMethodName = "/vm.VM/CrossChainAppRequest" - VM_CrossChainAppRequestFailed_FullMethodName = "/vm.VM/CrossChainAppRequestFailed" - VM_CrossChainAppResponse_FullMethodName = "/vm.VM/CrossChainAppResponse" VM_GetAncestors_FullMethodName = "/vm.VM/GetAncestors" VM_BatchedParseBlock_FullMethodName = "/vm.VM/BatchedParseBlock" VM_GetBlockIDAtHeight_FullMethodName = "/vm.VM/GetBlockIDAtHeight" @@ -94,9 +91,6 @@ type VMClient interface { AppGossip(ctx context.Context, in *AppGossipMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) // Attempts to gather metrics from a VM. Gather(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*GatherResponse, error) - CrossChainAppRequest(ctx context.Context, in *CrossChainAppRequestMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) - CrossChainAppRequestFailed(ctx context.Context, in *CrossChainAppRequestFailedMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) - CrossChainAppResponse(ctx context.Context, in *CrossChainAppResponseMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) // BatchedChainVM GetAncestors(ctx context.Context, in *GetAncestorsRequest, opts ...grpc.CallOption) (*GetAncestorsResponse, error) BatchedParseBlock(ctx context.Context, in *BatchedParseBlockRequest, opts ...grpc.CallOption) (*BatchedParseBlockResponse, error) @@ -284,33 +278,6 @@ func (c *vMClient) Gather(ctx context.Context, in *emptypb.Empty, opts ...grpc.C return out, nil } -func (c *vMClient) CrossChainAppRequest(ctx context.Context, in *CrossChainAppRequestMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) { - out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, VM_CrossChainAppRequest_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *vMClient) CrossChainAppRequestFailed(ctx context.Context, in *CrossChainAppRequestFailedMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) { - out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, VM_CrossChainAppRequestFailed_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *vMClient) CrossChainAppResponse(ctx context.Context, in *CrossChainAppResponseMsg, opts ...grpc.CallOption) (*emptypb.Empty, error) { - out := new(emptypb.Empty) - err := c.cc.Invoke(ctx, VM_CrossChainAppResponse_FullMethodName, in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - func (c *vMClient) GetAncestors(ctx context.Context, in *GetAncestorsRequest, opts ...grpc.CallOption) (*GetAncestorsResponse, error) { out := new(GetAncestorsResponse) err := c.cc.Invoke(ctx, VM_GetAncestors_FullMethodName, in, out, opts...) @@ -459,9 +426,6 @@ type VMServer interface { AppGossip(context.Context, *AppGossipMsg) (*emptypb.Empty, error) // Attempts to gather metrics from a VM. Gather(context.Context, *emptypb.Empty) (*GatherResponse, error) - CrossChainAppRequest(context.Context, *CrossChainAppRequestMsg) (*emptypb.Empty, error) - CrossChainAppRequestFailed(context.Context, *CrossChainAppRequestFailedMsg) (*emptypb.Empty, error) - CrossChainAppResponse(context.Context, *CrossChainAppResponseMsg) (*emptypb.Empty, error) // BatchedChainVM GetAncestors(context.Context, *GetAncestorsRequest) (*GetAncestorsResponse, error) BatchedParseBlock(context.Context, *BatchedParseBlockRequest) (*BatchedParseBlockResponse, error) @@ -544,15 +508,6 @@ func (UnimplementedVMServer) AppGossip(context.Context, *AppGossipMsg) (*emptypb func (UnimplementedVMServer) Gather(context.Context, *emptypb.Empty) (*GatherResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Gather not implemented") } -func (UnimplementedVMServer) CrossChainAppRequest(context.Context, *CrossChainAppRequestMsg) (*emptypb.Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method CrossChainAppRequest not implemented") -} -func (UnimplementedVMServer) CrossChainAppRequestFailed(context.Context, *CrossChainAppRequestFailedMsg) (*emptypb.Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method CrossChainAppRequestFailed not implemented") -} -func (UnimplementedVMServer) CrossChainAppResponse(context.Context, *CrossChainAppResponseMsg) (*emptypb.Empty, error) { - return nil, status.Errorf(codes.Unimplemented, "method CrossChainAppResponse not implemented") -} func (UnimplementedVMServer) GetAncestors(context.Context, *GetAncestorsRequest) (*GetAncestorsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetAncestors not implemented") } @@ -908,60 +863,6 @@ func _VM_Gather_Handler(srv interface{}, ctx context.Context, dec func(interface return interceptor(ctx, in, info, handler) } -func _VM_CrossChainAppRequest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CrossChainAppRequestMsg) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(VMServer).CrossChainAppRequest(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: VM_CrossChainAppRequest_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(VMServer).CrossChainAppRequest(ctx, req.(*CrossChainAppRequestMsg)) - } - return interceptor(ctx, in, info, handler) -} - -func _VM_CrossChainAppRequestFailed_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CrossChainAppRequestFailedMsg) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(VMServer).CrossChainAppRequestFailed(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: VM_CrossChainAppRequestFailed_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(VMServer).CrossChainAppRequestFailed(ctx, req.(*CrossChainAppRequestFailedMsg)) - } - return interceptor(ctx, in, info, handler) -} - -func _VM_CrossChainAppResponse_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CrossChainAppResponseMsg) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(VMServer).CrossChainAppResponse(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: VM_CrossChainAppResponse_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(VMServer).CrossChainAppResponse(ctx, req.(*CrossChainAppResponseMsg)) - } - return interceptor(ctx, in, info, handler) -} - func _VM_GetAncestors_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(GetAncestorsRequest) if err := dec(in); err != nil { @@ -1253,18 +1154,6 @@ var VM_ServiceDesc = grpc.ServiceDesc{ MethodName: "Gather", Handler: _VM_Gather_Handler, }, - { - MethodName: "CrossChainAppRequest", - Handler: _VM_CrossChainAppRequest_Handler, - }, - { - MethodName: "CrossChainAppRequestFailed", - Handler: _VM_CrossChainAppRequestFailed_Handler, - }, - { - MethodName: "CrossChainAppResponse", - Handler: _VM_CrossChainAppResponse_Handler, - }, { MethodName: "GetAncestors", Handler: _VM_GetAncestors_Handler, diff --git a/proto/vm/vm.proto b/proto/vm/vm.proto index 8386bf572bfa..25d773fd1d40 100644 --- a/proto/vm/vm.proto +++ b/proto/vm/vm.proto @@ -47,10 +47,6 @@ service VM { rpc AppGossip(AppGossipMsg) returns (google.protobuf.Empty); // Attempts to gather metrics from a VM. rpc Gather(google.protobuf.Empty) returns (GatherResponse); - rpc CrossChainAppRequest(CrossChainAppRequestMsg) returns (google.protobuf.Empty); - rpc CrossChainAppRequestFailed(CrossChainAppRequestFailedMsg) returns (google.protobuf.Empty); - rpc CrossChainAppResponse(CrossChainAppResponseMsg) returns (google.protobuf.Empty); - // BatchedChainVM rpc GetAncestors(GetAncestorsRequest) returns (GetAncestorsResponse); rpc BatchedParseBlock(BatchedParseBlockRequest) returns (BatchedParseBlockResponse); @@ -278,37 +274,6 @@ message AppGossipMsg { bytes msg = 2; } -message CrossChainAppRequestMsg { - // The chain that sent us this request - bytes chain_id = 1; - // The ID of this request - uint32 request_id = 2; - // deadline for this request - google.protobuf.Timestamp deadline = 3; - // The request body - bytes request = 4; -} - -message CrossChainAppRequestFailedMsg { - // The chain that we failed to get a response from - bytes chain_id = 1; - // The ID of the request we sent and didn't get a response to - uint32 request_id = 2; - // Application-defined error code - sint32 error_code = 3; - // Application-defined error message - string error_message = 4; -} - -message CrossChainAppResponseMsg { - // The chain that we got a response from - bytes chain_id = 1; - // Request ID of request that this is in response to - uint32 request_id = 2; - // The response body - bytes response = 3; -} - message ConnectedRequest { bytes node_id = 1; // Client name (e.g avalanchego) diff --git a/scripts/mocks.mockgen.source.txt b/scripts/mocks.mockgen.source.txt index 61efc2240902..ba562d2e3c49 100644 --- a/scripts/mocks.mockgen.source.txt +++ b/scripts/mocks.mockgen.source.txt @@ -1,4 +1,4 @@ -snow/engine/common/sender.go=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,CrossChainAppSender,NetworkAppSender,Gossiper=snow/engine/common/mock_sender.go +snow/engine/common/sender.go=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,Gossiper=snow/engine/common/mock_sender.go snow/networking/router/router.go=InternalHandler=snow/networking/router/mock_router.go snow/networking/sender/external_sender.go==snow/networking/sender/mock_external_sender.go vms/avm/block/executor/manager.go==vms/avm/block/executor/mock_manager.go diff --git a/snow/engine/avalanche/vertex/mock_vm.go b/snow/engine/avalanche/vertex/mock_vm.go index 18903544bd6f..9687aa884e7c 100644 --- a/snow/engine/avalanche/vertex/mock_vm.go +++ b/snow/engine/avalanche/vertex/mock_vm.go @@ -148,48 +148,6 @@ func (mr *MockLinearizableVMMockRecorder) CreateHandlers(arg0 any) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateHandlers", reflect.TypeOf((*MockLinearizableVM)(nil).CreateHandlers), arg0) } -// CrossChainAppRequest mocks base method. -func (m *MockLinearizableVM) CrossChainAppRequest(arg0 context.Context, arg1 ids.ID, arg2 uint32, arg3 time.Time, arg4 []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CrossChainAppRequest", arg0, arg1, arg2, arg3, arg4) - ret0, _ := ret[0].(error) - return ret0 -} - -// CrossChainAppRequest indicates an expected call of CrossChainAppRequest. -func (mr *MockLinearizableVMMockRecorder) CrossChainAppRequest(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CrossChainAppRequest", reflect.TypeOf((*MockLinearizableVM)(nil).CrossChainAppRequest), arg0, arg1, arg2, arg3, arg4) -} - -// CrossChainAppRequestFailed mocks base method. -func (m *MockLinearizableVM) CrossChainAppRequestFailed(arg0 context.Context, arg1 ids.ID, arg2 uint32, arg3 *common.AppError) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CrossChainAppRequestFailed", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(error) - return ret0 -} - -// CrossChainAppRequestFailed indicates an expected call of CrossChainAppRequestFailed. -func (mr *MockLinearizableVMMockRecorder) CrossChainAppRequestFailed(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CrossChainAppRequestFailed", reflect.TypeOf((*MockLinearizableVM)(nil).CrossChainAppRequestFailed), arg0, arg1, arg2, arg3) -} - -// CrossChainAppResponse mocks base method. -func (m *MockLinearizableVM) CrossChainAppResponse(arg0 context.Context, arg1 ids.ID, arg2 uint32, arg3 []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CrossChainAppResponse", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(error) - return ret0 -} - -// CrossChainAppResponse indicates an expected call of CrossChainAppResponse. -func (mr *MockLinearizableVMMockRecorder) CrossChainAppResponse(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CrossChainAppResponse", reflect.TypeOf((*MockLinearizableVM)(nil).CrossChainAppResponse), arg0, arg1, arg2, arg3) -} - // Disconnected mocks base method. func (m *MockLinearizableVM) Disconnected(arg0 context.Context, arg1 ids.NodeID) error { m.ctrl.T.Helper() diff --git a/snow/engine/common/appsender/appsender_client.go b/snow/engine/common/appsender/appsender_client.go index dcf2ef3dc558..4477034f17cb 100644 --- a/snow/engine/common/appsender/appsender_client.go +++ b/snow/engine/common/appsender/appsender_client.go @@ -24,44 +24,6 @@ func NewClient(client appsenderpb.AppSenderClient) *Client { return &Client{client: client} } -func (c *Client) SendCrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, appRequestBytes []byte) error { - _, err := c.client.SendCrossChainAppRequest( - ctx, - &appsenderpb.SendCrossChainAppRequestMsg{ - ChainId: chainID[:], - RequestId: requestID, - Request: appRequestBytes, - }, - ) - return err -} - -func (c *Client) SendCrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, appResponseBytes []byte) error { - _, err := c.client.SendCrossChainAppResponse( - ctx, - &appsenderpb.SendCrossChainAppResponseMsg{ - ChainId: chainID[:], - RequestId: requestID, - Response: appResponseBytes, - }, - ) - return err -} - -func (c *Client) SendCrossChainAppError(ctx context.Context, chainID ids.ID, requestID uint32, errorCode int32, errorMessage string) error { - _, err := c.client.SendCrossChainAppError( - ctx, - &appsenderpb.SendCrossChainAppErrorMsg{ - ChainId: chainID[:], - RequestId: requestID, - ErrorCode: errorCode, - ErrorMessage: errorMessage, - }, - ) - - return err -} - func (c *Client) SendAppRequest(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, request []byte) error { nodeIDsBytes := make([][]byte, nodeIDs.Len()) i := 0 diff --git a/snow/engine/common/appsender/appsender_server.go b/snow/engine/common/appsender/appsender_server.go index 2a3734d89347..73092d3e0860 100644 --- a/snow/engine/common/appsender/appsender_server.go +++ b/snow/engine/common/appsender/appsender_server.go @@ -27,33 +27,6 @@ func NewServer(appSender common.AppSender) *Server { return &Server{appSender: appSender} } -func (s *Server) SendCrossChainAppRequest(ctx context.Context, msg *appsenderpb.SendCrossChainAppRequestMsg) (*emptypb.Empty, error) { - chainID, err := ids.ToID(msg.ChainId) - if err != nil { - return &emptypb.Empty{}, err - } - - return &emptypb.Empty{}, s.appSender.SendCrossChainAppRequest(ctx, chainID, msg.RequestId, msg.Request) -} - -func (s *Server) SendCrossChainAppResponse(ctx context.Context, msg *appsenderpb.SendCrossChainAppResponseMsg) (*emptypb.Empty, error) { - chainID, err := ids.ToID(msg.ChainId) - if err != nil { - return &emptypb.Empty{}, err - } - - return &emptypb.Empty{}, s.appSender.SendCrossChainAppResponse(ctx, chainID, msg.RequestId, msg.Response) -} - -func (s *Server) SendCrossChainAppError(ctx context.Context, msg *appsenderpb.SendCrossChainAppErrorMsg) (*emptypb.Empty, error) { - chainID, err := ids.ToID(msg.ChainId) - if err != nil { - return &emptypb.Empty{}, err - } - - return &emptypb.Empty{}, s.appSender.SendCrossChainAppError(ctx, chainID, msg.RequestId, msg.ErrorCode, msg.ErrorMessage) -} - func (s *Server) SendAppRequest(ctx context.Context, req *appsenderpb.SendAppRequestMsg) (*emptypb.Empty, error) { nodeIDs := set.NewSet[ids.NodeID](len(req.NodeIds)) for _, nodeIDBytes := range req.NodeIds { diff --git a/snow/engine/common/engine.go b/snow/engine/common/engine.go index cbd9c37dc10c..537e33c5f192 100644 --- a/snow/engine/common/engine.go +++ b/snow/engine/common/engine.go @@ -348,7 +348,7 @@ type ChitsHandler interface { ) error } -type NetworkAppHandler interface { +type AppHandler interface { AppRequestHandler AppResponseHandler AppGossipHandler @@ -415,66 +415,6 @@ type AppGossipHandler interface { ) error } -type CrossChainAppHandler interface { - CrossChainAppRequestHandler - CrossChainAppResponseHandler -} - -type CrossChainAppRequestHandler interface { - // Notify this engine of a request for a CrossChainAppResponse with the same - // requestID. - // - // The meaning of request, and what should be sent in response to it, is - // application (VM) specific. - // - // Guarantees surrounding the request are specific to the implementation of - // the requesting VM. For example, the request may or may not be guaranteed - // to be well-formed/valid depending on the implementation of the requesting - // VM. - CrossChainAppRequest( - ctx context.Context, - chainID ids.ID, - requestID uint32, - deadline time.Time, - request []byte, - ) error -} - -type CrossChainAppResponseHandler interface { - // Notify this engine of the response to a previously sent - // CrossChainAppRequest with the same requestID. - // - // The meaning of response is application (VM) specifc. - // - // Guarantees surrounding the response are specific to the implementation of - // the responding VM. For example, the response may or may not be guaranteed - // to be well-formed/valid depending on the implementation of the requesting - // VM. - CrossChainAppResponse( - ctx context.Context, - chainID ids.ID, - requestID uint32, - response []byte, - ) error - - // Notify this engine that a CrossChainAppRequest it issued has failed. - // - // This function will be called if a CrossChainAppRequest message with - // nodeID and requestID was previously sent by this engine and will not - // receive a response. - CrossChainAppRequestFailed( - ctx context.Context, - chainID ids.ID, - requestID uint32, - appErr *AppError, - ) error -} - -type AppHandler interface { - NetworkAppHandler - CrossChainAppHandler -} - type InternalHandler interface { // Notify this engine of peer changes. validators.Connector diff --git a/snow/engine/common/mock_sender.go b/snow/engine/common/mock_sender.go index d1d3d1a68e5c..737adba95ade 100644 --- a/snow/engine/common/mock_sender.go +++ b/snow/engine/common/mock_sender.go @@ -3,7 +3,7 @@ // // Generated by this command: // -// mockgen -source=snow/engine/common/sender.go -destination=snow/engine/common/mock_sender.go -package=common -exclude_interfaces=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,CrossChainAppSender,NetworkAppSender,Gossiper +// mockgen -source=snow/engine/common/sender.go -destination=snow/engine/common/mock_sender.go -package=common -exclude_interfaces=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,Gossiper // // Package common is a generated GoMock package. @@ -157,48 +157,6 @@ func (mr *MockSenderMockRecorder) SendChits(ctx, nodeID, requestID, preferredID, return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendChits", reflect.TypeOf((*MockSender)(nil).SendChits), ctx, nodeID, requestID, preferredID, preferredIDAtHeight, acceptedID) } -// SendCrossChainAppError mocks base method. -func (m *MockSender) SendCrossChainAppError(ctx context.Context, chainID ids.ID, requestID uint32, errorCode int32, errorMessage string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendCrossChainAppError", ctx, chainID, requestID, errorCode, errorMessage) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendCrossChainAppError indicates an expected call of SendCrossChainAppError. -func (mr *MockSenderMockRecorder) SendCrossChainAppError(ctx, chainID, requestID, errorCode, errorMessage any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCrossChainAppError", reflect.TypeOf((*MockSender)(nil).SendCrossChainAppError), ctx, chainID, requestID, errorCode, errorMessage) -} - -// SendCrossChainAppRequest mocks base method. -func (m *MockSender) SendCrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, appRequestBytes []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendCrossChainAppRequest", ctx, chainID, requestID, appRequestBytes) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendCrossChainAppRequest indicates an expected call of SendCrossChainAppRequest. -func (mr *MockSenderMockRecorder) SendCrossChainAppRequest(ctx, chainID, requestID, appRequestBytes any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCrossChainAppRequest", reflect.TypeOf((*MockSender)(nil).SendCrossChainAppRequest), ctx, chainID, requestID, appRequestBytes) -} - -// SendCrossChainAppResponse mocks base method. -func (m *MockSender) SendCrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, appResponseBytes []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendCrossChainAppResponse", ctx, chainID, requestID, appResponseBytes) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendCrossChainAppResponse indicates an expected call of SendCrossChainAppResponse. -func (mr *MockSenderMockRecorder) SendCrossChainAppResponse(ctx, chainID, requestID, appResponseBytes any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendCrossChainAppResponse", reflect.TypeOf((*MockSender)(nil).SendCrossChainAppResponse), ctx, chainID, requestID, appResponseBytes) -} - // SendGet mocks base method. func (m *MockSender) SendGet(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { m.ctrl.T.Helper() diff --git a/snow/engine/common/no_ops_handlers.go b/snow/engine/common/no_ops_handlers.go index 4458070e7696..0b2247ab3cde 100644 --- a/snow/engine/common/no_ops_handlers.go +++ b/snow/engine/common/no_ops_handlers.go @@ -268,37 +268,6 @@ func NewNoOpAppHandler(log logging.Logger) AppHandler { return &noOpAppHandler{log: log} } -func (nop *noOpAppHandler) CrossChainAppRequest(_ context.Context, chainID ids.ID, requestID uint32, _ time.Time, _ []byte) error { - nop.log.Debug("dropping request", - zap.String("reason", "unhandled by this gear"), - zap.Stringer("messageOp", message.CrossChainAppRequestOp), - zap.Stringer("chainID", chainID), - zap.Uint32("requestID", requestID), - ) - return nil -} - -func (nop *noOpAppHandler) CrossChainAppRequestFailed(_ context.Context, chainID ids.ID, requestID uint32, appErr *AppError) error { - nop.log.Debug("dropping request", - zap.String("reason", "unhandled by this gear"), - zap.Stringer("messageOp", message.CrossChainAppErrorOp), - zap.Stringer("chainID", chainID), - zap.Uint32("requestID", requestID), - zap.Error(appErr), - ) - return nil -} - -func (nop *noOpAppHandler) CrossChainAppResponse(_ context.Context, chainID ids.ID, requestID uint32, _ []byte) error { - nop.log.Debug("dropping request", - zap.String("reason", "unhandled by this gear"), - zap.Stringer("messageOp", message.CrossChainAppResponseOp), - zap.Stringer("chainID", chainID), - zap.Uint32("requestID", requestID), - ) - return nil -} - func (nop *noOpAppHandler) AppRequest(_ context.Context, nodeID ids.NodeID, requestID uint32, _ time.Time, _ []byte) error { nop.log.Debug("dropping request", zap.String("reason", "unhandled by this gear"), diff --git a/snow/engine/common/sender.go b/snow/engine/common/sender.go index 69b53a899568..583653753853 100644 --- a/snow/engine/common/sender.go +++ b/snow/engine/common/sender.go @@ -164,8 +164,8 @@ type QuerySender interface { ) } -// NetworkAppSender sends VM-level messages to nodes in the network. -type NetworkAppSender interface { +// AppSender sends VM-level messages to nodes in the network. +type AppSender interface { // Send an application-level request. // // The VM corresponding to this AppSender may receive either: @@ -191,37 +191,3 @@ type NetworkAppSender interface { appGossipBytes []byte, ) error } - -// CrossChainAppSender sends local VM-level messages to another VM. -type CrossChainAppSender interface { - // SendCrossChainAppRequest sends an application-level request to a - // specific chain. - // - // The VM corresponding to this CrossChainAppSender may receive either: - // * A CrossChainAppResponse from [chainID] with ID [requestID] - // * A CrossChainAppRequestFailed from [chainID] with ID [requestID] - // - // A nil return value guarantees that the VM corresponding to this - // CrossChainAppSender will eventually receive exactly one of the above - // messages. - // - // A non-nil return value guarantees that the VM corresponding to this - // CrossChainAppSender will receive at most one of the above messages. - SendCrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, appRequestBytes []byte) error - // SendCrossChainAppResponse sends an application-level response to a - // specific chain - // - // This response must be in response to a CrossChainAppRequest that the VM - // corresponding to this CrossChainAppSender received from [chainID] with ID - // [requestID]. - SendCrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, appResponseBytes []byte) error - // SendCrossChainAppError sends an application-level error to a CrossChainAppRequest - SendCrossChainAppError(ctx context.Context, chainID ids.ID, requestID uint32, errorCode int32, errorMessage string) error -} - -// AppSender sends application (VM) level messages. -// See also common.AppHandler. -type AppSender interface { - NetworkAppSender - CrossChainAppSender -} diff --git a/snow/engine/common/traced_engine.go b/snow/engine/common/traced_engine.go index f4fd4943f741..4574f0c3364a 100644 --- a/snow/engine/common/traced_engine.go +++ b/snow/engine/common/traced_engine.go @@ -311,38 +311,6 @@ func (e *tracedEngine) AppGossip(ctx context.Context, nodeID ids.NodeID, msg []b return e.engine.AppGossip(ctx, nodeID, msg) } -func (e *tracedEngine) CrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, request []byte) error { - ctx, span := e.tracer.Start(ctx, "tracedEngine.CrossChainAppRequest", oteltrace.WithAttributes( - attribute.Stringer("chainID", chainID), - attribute.Int64("requestID", int64(requestID)), - attribute.Int("requestLen", len(request)), - )) - defer span.End() - - return e.engine.CrossChainAppRequest(ctx, chainID, requestID, deadline, request) -} - -func (e *tracedEngine) CrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, response []byte) error { - ctx, span := e.tracer.Start(ctx, "tracedEngine.CrossChainAppResponse", oteltrace.WithAttributes( - attribute.Stringer("chainID", chainID), - attribute.Int64("requestID", int64(requestID)), - attribute.Int("responseLen", len(response)), - )) - defer span.End() - - return e.engine.CrossChainAppResponse(ctx, chainID, requestID, response) -} - -func (e *tracedEngine) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *AppError) error { - ctx, span := e.tracer.Start(ctx, "tracedEngine.CrossChainAppRequestFailed", oteltrace.WithAttributes( - attribute.Stringer("chainID", chainID), - attribute.Int64("requestID", int64(requestID)), - )) - defer span.End() - - return e.engine.CrossChainAppRequestFailed(ctx, chainID, requestID, appErr) -} - func (e *tracedEngine) Connected(ctx context.Context, nodeID ids.NodeID, nodeVersion *version.Application) error { ctx, span := e.tracer.Start(ctx, "tracedEngine.Connected", oteltrace.WithAttributes( attribute.Stringer("nodeID", nodeID), diff --git a/snow/engine/enginetest/engine.go b/snow/engine/enginetest/engine.go index 53f791f19b25..29c577f60325 100644 --- a/snow/engine/enginetest/engine.go +++ b/snow/engine/enginetest/engine.go @@ -98,10 +98,6 @@ type Engine struct { CantHealth, - CantCrossChainAppRequest, - CantCrossChainAppRequestFailed, - CantCrossChainAppResponse, - CantAppRequest, CantAppResponse, CantAppGossip, @@ -126,20 +122,17 @@ type Engine struct { GetStateSummaryFrontierF, GetStateSummaryFrontierFailedF, GetAcceptedStateSummaryFailedF, GetAcceptedFrontierF, GetFailedF, GetAncestorsFailedF, QueryFailedF, GetAcceptedFrontierFailedF, GetAcceptedFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32) error - AppRequestFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *common.AppError) error - StateSummaryFrontierF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, summary []byte) error - GetAcceptedStateSummaryF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, keys set.Set[uint64]) error - AcceptedStateSummaryF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, summaryIDs set.Set[ids.ID]) error - ConnectedF func(ctx context.Context, nodeID ids.NodeID, nodeVersion *version.Application) error - DisconnectedF func(ctx context.Context, nodeID ids.NodeID) error - HealthF func(context.Context) (interface{}, error) - GetVMF func() common.VM - AppRequestF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, msg []byte) error - AppResponseF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, msg []byte) error - AppGossipF func(ctx context.Context, nodeID ids.NodeID, msg []byte) error - CrossChainAppRequestF func(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, msg []byte) error - CrossChainAppResponseF func(ctx context.Context, chainID ids.ID, requestID uint32, msg []byte) error - CrossChainAppRequestFailedF func(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error + AppRequestFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *common.AppError) error + StateSummaryFrontierF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, summary []byte) error + GetAcceptedStateSummaryF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, keys set.Set[uint64]) error + AcceptedStateSummaryF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, summaryIDs set.Set[ids.ID]) error + ConnectedF func(ctx context.Context, nodeID ids.NodeID, nodeVersion *version.Application) error + DisconnectedF func(ctx context.Context, nodeID ids.NodeID) error + HealthF func(context.Context) (interface{}, error) + GetVMF func() common.VM + AppRequestF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, msg []byte) error + AppResponseF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, msg []byte) error + AppGossipF func(ctx context.Context, nodeID ids.NodeID, msg []byte) error } func (e *Engine) Default(cant bool) { @@ -181,9 +174,6 @@ func (e *Engine) Default(cant bool) { e.CantAppResponse = cant e.CantAppGossip = cant e.CantGetVM = cant - e.CantCrossChainAppRequest = cant - e.CantCrossChainAppRequestFailed = cant - e.CantCrossChainAppResponse = cant } func (e *Engine) Start(ctx context.Context, startReqID uint32) error { @@ -550,45 +540,6 @@ func (e *Engine) QueryFailed(ctx context.Context, nodeID ids.NodeID, requestID u return errQueryFailed } -func (e *Engine) CrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, request []byte) error { - if e.CrossChainAppRequestF != nil { - return e.CrossChainAppRequestF(ctx, chainID, requestID, deadline, request) - } - if !e.CantCrossChainAppRequest { - return nil - } - if e.T != nil { - require.FailNow(e.T, errCrossChainAppRequest.Error()) - } - return errCrossChainAppRequest -} - -func (e *Engine) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error { - if e.CrossChainAppRequestFailedF != nil { - return e.CrossChainAppRequestFailedF(ctx, chainID, requestID, appErr) - } - if !e.CantCrossChainAppRequestFailed { - return nil - } - if e.T != nil { - require.FailNow(e.T, errCrossChainAppRequestFailed.Error()) - } - return errCrossChainAppRequestFailed -} - -func (e *Engine) CrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, response []byte) error { - if e.CrossChainAppResponseF != nil { - return e.CrossChainAppResponseF(ctx, chainID, requestID, response) - } - if !e.CantCrossChainAppResponse { - return nil - } - if e.T != nil { - require.FailNow(e.T, errCrossChainAppResponse.Error()) - } - return errCrossChainAppResponse -} - func (e *Engine) AppRequest(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, request []byte) error { if e.AppRequestF != nil { return e.AppRequestF(ctx, nodeID, requestID, deadline, request) diff --git a/snow/engine/enginetest/sender.go b/snow/engine/enginetest/sender.go index 02a57caf4b6f..5bc7f100c058 100644 --- a/snow/engine/enginetest/sender.go +++ b/snow/engine/enginetest/sender.go @@ -36,8 +36,7 @@ type Sender struct { CantSendGet, CantSendGetAncestors, CantSendPut, CantSendAncestors, CantSendPullQuery, CantSendPushQuery, CantSendChits, CantSendAppRequest, CantSendAppResponse, CantSendAppError, - CantSendAppGossip, - CantSendCrossChainAppRequest, CantSendCrossChainAppResponse, CantSendCrossChainAppError bool + CantSendAppGossip bool SendGetStateSummaryFrontierF func(context.Context, set.Set[ids.NodeID], uint32) SendStateSummaryFrontierF func(context.Context, ids.NodeID, uint32, []byte) @@ -58,9 +57,6 @@ type Sender struct { SendAppResponseF func(context.Context, ids.NodeID, uint32, []byte) error SendAppErrorF func(context.Context, ids.NodeID, uint32, int32, string) error SendAppGossipF func(context.Context, common.SendConfig, []byte) error - SendCrossChainAppRequestF func(context.Context, ids.ID, uint32, []byte) - SendCrossChainAppResponseF func(context.Context, ids.ID, uint32, []byte) - SendCrossChainAppErrorF func(context.Context, ids.ID, uint32, int32, string) } // Default set the default callable value to [cant] @@ -83,8 +79,6 @@ func (s *Sender) Default(cant bool) { s.CantSendAppRequest = cant s.CantSendAppResponse = cant s.CantSendAppGossip = cant - s.CantSendCrossChainAppRequest = cant - s.CantSendCrossChainAppResponse = cant } // SendGetStateSummaryFrontier calls SendGetStateSummaryFrontierF if it was @@ -252,42 +246,6 @@ func (s *Sender) SendChits(ctx context.Context, vdr ids.NodeID, requestID uint32 } } -// SendCrossChainAppRequest calls SendCrossChainAppRequestF if it was -// initialized. If it wasn't initialized and this function shouldn't be called -// and testing was initialized, then testing will fail. -func (s *Sender) SendCrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, appRequestBytes []byte) error { - if s.SendCrossChainAppRequestF != nil { - s.SendCrossChainAppRequestF(ctx, chainID, requestID, appRequestBytes) - } else if s.CantSendCrossChainAppRequest && s.T != nil { - require.FailNow(s.T, "Unexpectedly called SendCrossChainAppRequest") - } - return nil -} - -// SendCrossChainAppResponse calls SendCrossChainAppResponseF if it was -// initialized. If it wasn't initialized and this function shouldn't be called -// and testing was initialized, then testing will fail. -func (s *Sender) SendCrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, appResponseBytes []byte) error { - if s.SendCrossChainAppResponseF != nil { - s.SendCrossChainAppResponseF(ctx, chainID, requestID, appResponseBytes) - } else if s.CantSendCrossChainAppResponse && s.T != nil { - require.FailNow(s.T, "Unexpectedly called SendCrossChainAppResponse") - } - return nil -} - -// SendCrossChainAppError calls SendCrossChainAppErrorF if it was -// initialized. If it wasn't initialized and this function shouldn't be called -// and testing was initialized, then testing will fail. -func (s *Sender) SendCrossChainAppError(ctx context.Context, chainID ids.ID, requestID uint32, errorCode int32, errorMessage string) error { - if s.SendCrossChainAppErrorF != nil { - s.SendCrossChainAppErrorF(ctx, chainID, requestID, errorCode, errorMessage) - } else if s.CantSendCrossChainAppError && s.T != nil { - require.FailNow(s.T, "Unexpectedly called SendCrossChainAppError") - } - return nil -} - // SendAppRequest calls SendAppRequestF if it was initialized. If it wasn't // initialized and this function shouldn't be called and testing was // initialized, then testing will fail. @@ -347,10 +305,9 @@ func (s *Sender) SendAppGossip( // SenderStub is a stub sender that returns values received on method-specific channels. type SenderStub struct { SentAppRequest, SentAppResponse, - SentAppGossip, - SentCrossChainAppRequest, SentCrossChainAppResponse chan []byte + SentAppGossip chan []byte - SentAppError, SentCrossChainAppError chan *common.AppError + SentAppError chan *common.AppError } func (f SenderStub) SendAppRequest(_ context.Context, _ set.Set[ids.NodeID], _ uint32, bytes []byte) error { @@ -391,33 +348,3 @@ func (f SenderStub) SendAppGossip(_ context.Context, _ common.SendConfig, bytes f.SentAppGossip <- bytes return nil } - -func (f SenderStub) SendCrossChainAppRequest(_ context.Context, _ ids.ID, _ uint32, bytes []byte) error { - if f.SentCrossChainAppRequest == nil { - return nil - } - - f.SentCrossChainAppRequest <- bytes - return nil -} - -func (f SenderStub) SendCrossChainAppResponse(_ context.Context, _ ids.ID, _ uint32, bytes []byte) error { - if f.SentCrossChainAppResponse == nil { - return nil - } - - f.SentCrossChainAppResponse <- bytes - return nil -} - -func (f SenderStub) SendCrossChainAppError(_ context.Context, _ ids.ID, _ uint32, errorCode int32, errorMessage string) error { - if f.SentCrossChainAppError == nil { - return nil - } - - f.SentCrossChainAppError <- &common.AppError{ - Code: errorCode, - Message: errorMessage, - } - return nil -} diff --git a/snow/engine/enginetest/vm.go b/snow/engine/enginetest/vm.go index d6c5f4d0feb3..f3c430e58404 100644 --- a/snow/engine/enginetest/vm.go +++ b/snow/engine/enginetest/vm.go @@ -20,21 +20,18 @@ import ( ) var ( - errInitialize = errors.New("unexpectedly called Initialize") - errSetState = errors.New("unexpectedly called SetState") - errShutdown = errors.New("unexpectedly called Shutdown") - errCreateHandlers = errors.New("unexpectedly called CreateHandlers") - errHealthCheck = errors.New("unexpectedly called HealthCheck") - errConnected = errors.New("unexpectedly called Connected") - errDisconnected = errors.New("unexpectedly called Disconnected") - errVersion = errors.New("unexpectedly called Version") - errAppRequest = errors.New("unexpectedly called AppRequest") - errAppResponse = errors.New("unexpectedly called AppResponse") - errAppRequestFailed = errors.New("unexpectedly called AppRequestFailed") - errAppGossip = errors.New("unexpectedly called AppGossip") - errCrossChainAppRequest = errors.New("unexpectedly called CrossChainAppRequest") - errCrossChainAppResponse = errors.New("unexpectedly called CrossChainAppResponse") - errCrossChainAppRequestFailed = errors.New("unexpectedly called CrossChainAppRequestFailed") + errInitialize = errors.New("unexpectedly called Initialize") + errSetState = errors.New("unexpectedly called SetState") + errShutdown = errors.New("unexpectedly called Shutdown") + errCreateHandlers = errors.New("unexpectedly called CreateHandlers") + errHealthCheck = errors.New("unexpectedly called HealthCheck") + errConnected = errors.New("unexpectedly called Connected") + errDisconnected = errors.New("unexpectedly called Disconnected") + errVersion = errors.New("unexpectedly called Version") + errAppRequest = errors.New("unexpectedly called AppRequest") + errAppResponse = errors.New("unexpectedly called AppResponse") + errAppRequestFailed = errors.New("unexpectedly called AppRequestFailed") + errAppGossip = errors.New("unexpectedly called AppGossip") _ common.VM = (*VM)(nil) ) @@ -46,24 +43,20 @@ type VM struct { CantInitialize, CantSetState, CantShutdown, CantCreateHandlers, CantHealthCheck, CantConnected, CantDisconnected, CantVersion, - CantAppRequest, CantAppResponse, CantAppGossip, CantAppRequestFailed, - CantCrossChainAppRequest, CantCrossChainAppResponse, CantCrossChainAppRequestFailed bool - - InitializeF func(ctx context.Context, chainCtx *snow.Context, db database.Database, genesisBytes []byte, upgradeBytes []byte, configBytes []byte, msgChan chan<- common.Message, fxs []*common.Fx, appSender common.AppSender) error - SetStateF func(ctx context.Context, state snow.State) error - ShutdownF func(context.Context) error - CreateHandlersF func(context.Context) (map[string]http.Handler, error) - ConnectedF func(ctx context.Context, nodeID ids.NodeID, nodeVersion *version.Application) error - DisconnectedF func(ctx context.Context, nodeID ids.NodeID) error - HealthCheckF func(context.Context) (interface{}, error) - AppRequestF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, msg []byte) error - AppResponseF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, msg []byte) error - AppGossipF func(ctx context.Context, nodeID ids.NodeID, msg []byte) error - AppRequestFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *common.AppError) error - VersionF func(context.Context) (string, error) - CrossChainAppRequestF func(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, msg []byte) error - CrossChainAppResponseF func(ctx context.Context, chainID ids.ID, requestID uint32, msg []byte) error - CrossChainAppRequestFailedF func(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error + CantAppRequest, CantAppResponse, CantAppGossip, CantAppRequestFailed bool + + InitializeF func(ctx context.Context, chainCtx *snow.Context, db database.Database, genesisBytes []byte, upgradeBytes []byte, configBytes []byte, msgChan chan<- common.Message, fxs []*common.Fx, appSender common.AppSender) error + SetStateF func(ctx context.Context, state snow.State) error + ShutdownF func(context.Context) error + CreateHandlersF func(context.Context) (map[string]http.Handler, error) + ConnectedF func(ctx context.Context, nodeID ids.NodeID, nodeVersion *version.Application) error + DisconnectedF func(ctx context.Context, nodeID ids.NodeID) error + HealthCheckF func(context.Context) (interface{}, error) + AppRequestF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, msg []byte) error + AppResponseF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, msg []byte) error + AppGossipF func(ctx context.Context, nodeID ids.NodeID, msg []byte) error + AppRequestFailedF func(ctx context.Context, nodeID ids.NodeID, requestID uint32, appErr *common.AppError) error + VersionF func(context.Context) (string, error) } func (vm *VM) Default(cant bool) { @@ -79,9 +72,6 @@ func (vm *VM) Default(cant bool) { vm.CantVersion = cant vm.CantConnected = cant vm.CantDisconnected = cant - vm.CantCrossChainAppRequest = cant - vm.CantCrossChainAppRequestFailed = cant - vm.CantCrossChainAppResponse = cant } func (vm *VM) Initialize( @@ -212,45 +202,6 @@ func (vm *VM) AppGossip(ctx context.Context, nodeID ids.NodeID, msg []byte) erro return errAppGossip } -func (vm *VM) CrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, request []byte) error { - if vm.CrossChainAppRequestF != nil { - return vm.CrossChainAppRequestF(ctx, chainID, requestID, deadline, request) - } - if !vm.CantCrossChainAppRequest { - return nil - } - if vm.T != nil { - require.FailNow(vm.T, errCrossChainAppRequest.Error()) - } - return errCrossChainAppRequest -} - -func (vm *VM) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error { - if vm.CrossChainAppRequestFailedF != nil { - return vm.CrossChainAppRequestFailedF(ctx, chainID, requestID, appErr) - } - if !vm.CantCrossChainAppRequestFailed { - return nil - } - if vm.T != nil { - require.FailNow(vm.T, errCrossChainAppRequestFailed.Error()) - } - return errCrossChainAppRequestFailed -} - -func (vm *VM) CrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, response []byte) error { - if vm.CrossChainAppResponseF != nil { - return vm.CrossChainAppResponseF(ctx, chainID, requestID, response) - } - if !vm.CantCrossChainAppResponse { - return nil - } - if vm.T != nil { - require.FailNow(vm.T, errCrossChainAppResponse.Error()) - } - return errCrossChainAppResponse -} - func (vm *VM) Connected(ctx context.Context, id ids.NodeID, nodeVersion *version.Application) error { if vm.ConnectedF != nil { return vm.ConnectedF(ctx, id, nodeVersion) diff --git a/snow/engine/snowman/block/mock_chain_vm.go b/snow/engine/snowman/block/mock_chain_vm.go index c927282c1f93..4e7d7d7387fd 100644 --- a/snow/engine/snowman/block/mock_chain_vm.go +++ b/snow/engine/snowman/block/mock_chain_vm.go @@ -147,48 +147,6 @@ func (mr *MockChainVMMockRecorder) CreateHandlers(arg0 any) *gomock.Call { return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateHandlers", reflect.TypeOf((*MockChainVM)(nil).CreateHandlers), arg0) } -// CrossChainAppRequest mocks base method. -func (m *MockChainVM) CrossChainAppRequest(arg0 context.Context, arg1 ids.ID, arg2 uint32, arg3 time.Time, arg4 []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CrossChainAppRequest", arg0, arg1, arg2, arg3, arg4) - ret0, _ := ret[0].(error) - return ret0 -} - -// CrossChainAppRequest indicates an expected call of CrossChainAppRequest. -func (mr *MockChainVMMockRecorder) CrossChainAppRequest(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CrossChainAppRequest", reflect.TypeOf((*MockChainVM)(nil).CrossChainAppRequest), arg0, arg1, arg2, arg3, arg4) -} - -// CrossChainAppRequestFailed mocks base method. -func (m *MockChainVM) CrossChainAppRequestFailed(arg0 context.Context, arg1 ids.ID, arg2 uint32, arg3 *common.AppError) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CrossChainAppRequestFailed", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(error) - return ret0 -} - -// CrossChainAppRequestFailed indicates an expected call of CrossChainAppRequestFailed. -func (mr *MockChainVMMockRecorder) CrossChainAppRequestFailed(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CrossChainAppRequestFailed", reflect.TypeOf((*MockChainVM)(nil).CrossChainAppRequestFailed), arg0, arg1, arg2, arg3) -} - -// CrossChainAppResponse mocks base method. -func (m *MockChainVM) CrossChainAppResponse(arg0 context.Context, arg1 ids.ID, arg2 uint32, arg3 []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CrossChainAppResponse", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(error) - return ret0 -} - -// CrossChainAppResponse indicates an expected call of CrossChainAppResponse. -func (mr *MockChainVMMockRecorder) CrossChainAppResponse(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CrossChainAppResponse", reflect.TypeOf((*MockChainVM)(nil).CrossChainAppResponse), arg0, arg1, arg2, arg3) -} - // Disconnected mocks base method. func (m *MockChainVM) Disconnected(arg0 context.Context, arg1 ids.NodeID) error { m.ctrl.T.Helper() diff --git a/snow/networking/handler/handler.go b/snow/networking/handler/handler.go index 1eb42ca0dcdc..28582c600018 100644 --- a/snow/networking/handler/handler.go +++ b/snow/networking/handler/handler.go @@ -286,8 +286,7 @@ func (h *handler) Start(ctx context.Context, recoverPanic bool) { // Push the message onto the handler's queue func (h *handler) Push(ctx context.Context, msg Message) { switch msg.Op() { - case message.AppRequestOp, message.AppErrorOp, message.AppResponseOp, message.AppGossipOp, - message.CrossChainAppRequestOp, message.CrossChainAppErrorOp, message.CrossChainAppResponseOp: + case message.AppRequestOp, message.AppErrorOp, message.AppResponseOp, message.AppGossipOp: h.asyncMessageQueue.Push(ctx, msg) default: h.syncMessageQueue.Push(ctx, msg) @@ -881,36 +880,6 @@ func (h *handler) executeAsyncMsg(ctx context.Context, msg Message) error { case *p2ppb.AppGossip: return engine.AppGossip(ctx, nodeID, m.AppBytes) - case *message.CrossChainAppRequest: - return engine.CrossChainAppRequest( - ctx, - m.SourceChainID, - m.RequestID, - msg.Expiration(), - m.Message, - ) - - case *message.CrossChainAppResponse: - return engine.CrossChainAppResponse( - ctx, - m.SourceChainID, - m.RequestID, - m.Message, - ) - - case *message.CrossChainAppRequestFailed: - err := &common.AppError{ - Code: m.ErrorCode, - Message: m.ErrorMessage, - } - - return engine.CrossChainAppRequestFailed( - ctx, - m.SourceChainID, - m.RequestID, - err, - ) - default: return fmt.Errorf( "attempt to submit unhandled async msg %s from %s", diff --git a/snow/networking/router/chain_router_test.go b/snow/networking/router/chain_router_test.go index dadbec2d93d7..8dcdef0a2e74 100644 --- a/snow/networking/router/chain_router_test.go +++ b/snow/networking/router/chain_router_test.go @@ -504,8 +504,7 @@ func TestRouterTimeout(t *testing.T) { calledGetAncestorsFailed, calledGetFailed, calledQueryFailed, - calledAppRequestFailed, - calledCrossChainAppRequestFailed bool + calledAppRequestFailed bool wg = sync.WaitGroup{} ) @@ -603,11 +602,6 @@ func TestRouterTimeout(t *testing.T) { calledAppRequestFailed = true return nil } - bootstrapper.CrossChainAppRequestFailedF = func(context.Context, ids.ID, uint32, *common.AppError) error { - defer wg.Done() - calledCrossChainAppRequestFailed = true - return nil - } ctx.State.Set(snow.EngineState{ Type: p2ppb.EngineType_ENGINE_TYPE_SNOWMAN, State: snow.Bootstrapping, // assumed bootstrapping is ongoing @@ -788,28 +782,6 @@ func TestRouterTimeout(t *testing.T) { ) } - { - wg.Add(1) - requestID++ - chainRouter.RegisterRequest( - context.Background(), - nodeID, - ctx.ChainID, - ctx.ChainID, - requestID, - message.CrossChainAppResponseOp, - message.InternalCrossChainAppError( - nodeID, - ctx.ChainID, - ctx.ChainID, - requestID, - common.ErrTimeout.Code, - common.ErrTimeout.Message, - ), - p2ppb.EngineType_ENGINE_TYPE_SNOWMAN, - ) - } - wg.Wait() chainRouter.lock.Lock() @@ -823,7 +795,6 @@ func TestRouterTimeout(t *testing.T) { require.True(calledGetFailed) require.True(calledQueryFailed) require.True(calledAppRequestFailed) - require.True(calledCrossChainAppRequestFailed) } func TestRouterHonorsRequestedEngine(t *testing.T) { @@ -1010,18 +981,6 @@ func TestRouterClearTimeouts(t *testing.T) { responseMsg: message.InboundAppError(ids.EmptyNodeID, ids.Empty, requestID, 1234, "custom error"), timeoutMsg: message.InboundAppError(ids.EmptyNodeID, ids.Empty, requestID, 123, "error"), }, - { - name: "CrossChainAppResponse", - responseOp: message.CrossChainAppResponseOp, - responseMsg: message.InternalCrossChainAppResponse(ids.EmptyNodeID, ids.Empty, ids.Empty, requestID, []byte("responseMsg")), - timeoutMsg: message.InternalCrossChainAppError(ids.EmptyNodeID, ids.Empty, ids.Empty, requestID, 123, "error"), - }, - { - name: "CrossChainAppError", - responseOp: message.CrossChainAppResponseOp, - responseMsg: message.InternalCrossChainAppError(ids.EmptyNodeID, ids.Empty, ids.Empty, requestID, 1234, "custom error"), - timeoutMsg: message.InternalCrossChainAppError(ids.EmptyNodeID, ids.Empty, ids.Empty, requestID, 123, "error"), - }, } for _, tt := range tests { @@ -1592,94 +1551,6 @@ func TestAppRequest(t *testing.T) { } } -// Tests that a response, peer error, or a timeout clears the timeout and calls -// the handler -func TestCrossChainAppRequest(t *testing.T) { - wantRequestID := uint32(123) - wantResponse := []byte("response") - - errFoo := common.AppError{ - Code: 456, - Message: "foo", - } - - tests := []struct { - name string - responseOp message.Op - timeoutMsg message.InboundMessage - inboundMsg message.InboundMessage - }{ - { - name: "CrossChainAppRequest - chain response", - responseOp: message.CrossChainAppResponseOp, - timeoutMsg: message.InternalCrossChainAppError(ids.EmptyNodeID, ids.Empty, ids.Empty, wantRequestID, errFoo.Code, errFoo.Message), - inboundMsg: message.InternalCrossChainAppResponse(ids.EmptyNodeID, ids.Empty, ids.Empty, wantRequestID, wantResponse), - }, - { - name: "CrossChainAppRequest - chain error", - responseOp: message.CrossChainAppResponseOp, - timeoutMsg: message.InternalCrossChainAppError(ids.EmptyNodeID, ids.Empty, ids.Empty, wantRequestID, errFoo.Code, errFoo.Message), - inboundMsg: message.InternalCrossChainAppError(ids.EmptyNodeID, ids.Empty, ids.Empty, wantRequestID, errFoo.Code, errFoo.Message), - }, - { - name: "CrossChainAppRequest - timeout", - responseOp: message.CrossChainAppResponseOp, - timeoutMsg: message.InternalCrossChainAppError(ids.EmptyNodeID, ids.Empty, ids.Empty, wantRequestID, errFoo.Code, errFoo.Message), - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - require := require.New(t) - - wg := &sync.WaitGroup{} - chainRouter, engine := newChainRouterTest(t) - - wg.Add(1) - if tt.inboundMsg == nil || tt.inboundMsg.Op() == message.CrossChainAppErrorOp { - engine.CrossChainAppRequestFailedF = func(_ context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error { - defer wg.Done() - chainRouter.lock.Lock() - require.Zero(chainRouter.timedRequests.Len()) - chainRouter.lock.Unlock() - - require.Equal(ids.Empty, chainID) - require.Equal(wantRequestID, requestID) - require.Equal(errFoo.Code, appErr.Code) - require.Equal(errFoo.Message, appErr.Message) - - return nil - } - } else if tt.inboundMsg.Op() == message.CrossChainAppResponseOp { - engine.CrossChainAppResponseF = func(_ context.Context, chainID ids.ID, requestID uint32, msg []byte) error { - defer wg.Done() - chainRouter.lock.Lock() - require.Zero(chainRouter.timedRequests.Len()) - chainRouter.lock.Unlock() - - require.Equal(ids.Empty, chainID) - require.Equal(wantRequestID, requestID) - require.Equal(wantResponse, msg) - - return nil - } - } - - ctx := context.Background() - chainRouter.RegisterRequest(ctx, ids.EmptyNodeID, ids.Empty, ids.Empty, wantRequestID, tt.responseOp, tt.timeoutMsg, engineType) - chainRouter.lock.Lock() - require.Equal(1, chainRouter.timedRequests.Len()) - chainRouter.lock.Unlock() - - if tt.inboundMsg != nil { - chainRouter.HandleInbound(ctx, tt.inboundMsg) - } - - wg.Wait() - }) - } -} - func newChainRouterTest(t *testing.T) (*ChainRouter, *enginetest.Engine) { // Create a timeout manager tm, err := timeout.NewManager( diff --git a/snow/networking/sender/sender.go b/snow/networking/sender/sender.go index e4e36bd3ebbb..b8742fae0ff4 100644 --- a/snow/networking/sender/sender.go +++ b/snow/networking/sender/sender.go @@ -1212,70 +1212,6 @@ func (s *sender) SendChits( } } -func (s *sender) SendCrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, appRequestBytes []byte) error { - ctx = context.WithoutCancel(ctx) - - // The failed message is treated as if it was sent by the requested chain - failedMsg := message.InternalCrossChainAppError( - s.ctx.NodeID, - chainID, - s.ctx.ChainID, - requestID, - common.ErrTimeout.Code, - common.ErrTimeout.Message, - ) - s.router.RegisterRequest( - ctx, - s.ctx.NodeID, - s.ctx.ChainID, - chainID, - requestID, - message.CrossChainAppResponseOp, - failedMsg, - p2p.EngineType_ENGINE_TYPE_UNSPECIFIED, - ) - - inMsg := message.InternalCrossChainAppRequest( - s.ctx.NodeID, - s.ctx.ChainID, - chainID, - requestID, - s.timeouts.TimeoutDuration(), - appRequestBytes, - ) - go s.router.HandleInbound(ctx, inMsg) - return nil -} - -func (s *sender) SendCrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, appResponseBytes []byte) error { - ctx = context.WithoutCancel(ctx) - - inMsg := message.InternalCrossChainAppResponse( - s.ctx.NodeID, - s.ctx.ChainID, - chainID, - requestID, - appResponseBytes, - ) - go s.router.HandleInbound(ctx, inMsg) - return nil -} - -func (s *sender) SendCrossChainAppError(ctx context.Context, chainID ids.ID, requestID uint32, errorCode int32, errorMessage string) error { - ctx = context.WithoutCancel(ctx) - - inMsg := message.InternalCrossChainAppError( - s.ctx.NodeID, - s.ctx.ChainID, - chainID, - requestID, - errorCode, - errorMessage, - ) - go s.router.HandleInbound(ctx, inMsg) - return nil -} - func (s *sender) SendAppRequest(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, appRequestBytes []byte) error { ctx = context.WithoutCancel(ctx) diff --git a/snow/networking/sender/sender_test.go b/snow/networking/sender/sender_test.go index 215de3c56fb5..fb1565865034 100644 --- a/snow/networking/sender/sender_test.go +++ b/snow/networking/sender/sender_test.go @@ -219,17 +219,6 @@ func TestTimeout(t *testing.T) { return nil } - bootstrapper.CrossChainAppRequestFailedF = func(ctx context.Context, chainID ids.ID, _ uint32, _ *common.AppError) error { - require.NoError(ctx.Err()) - - failedLock.Lock() - defer failedLock.Unlock() - - failedChains.Add(chainID) - wg.Done() - return nil - } - sendAll := func() { { nodeIDs := set.Of(ids.GenerateTestNodeID()) @@ -294,13 +283,6 @@ func TestTimeout(t *testing.T) { requestID++ require.NoError(sender.SendAppRequest(cancelledCtx, nodeIDs, requestID, nil)) } - { - chainID := ids.GenerateTestID() - chains.Add(chainID) - wg.Add(1) - requestID++ - require.NoError(sender.SendCrossChainAppRequest(cancelledCtx, chainID, requestID, nil)) - } } // Send messages to disconnected peers diff --git a/snow/networking/sender/traced_sender.go b/snow/networking/sender/traced_sender.go index 0e25602c84c3..6fadee7f909d 100644 --- a/snow/networking/sender/traced_sender.go +++ b/snow/networking/sender/traced_sender.go @@ -191,40 +191,6 @@ func (s *tracedSender) SendChits(ctx context.Context, nodeID ids.NodeID, request s.sender.SendChits(ctx, nodeID, requestID, preferredID, preferredIDAtHeight, acceptedID) } -func (s *tracedSender) SendCrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, appRequestBytes []byte) error { - ctx, span := s.tracer.Start(ctx, "tracedSender.SendCrossChainAppRequest", oteltrace.WithAttributes( - attribute.Stringer("chainID", chainID), - attribute.Int64("requestID", int64(requestID)), - attribute.Int("requestLen", len(appRequestBytes)), - )) - defer span.End() - - return s.sender.SendCrossChainAppRequest(ctx, chainID, requestID, appRequestBytes) -} - -func (s *tracedSender) SendCrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, appResponseBytes []byte) error { - ctx, span := s.tracer.Start(ctx, "tracedSender.SendCrossChainAppResponse", oteltrace.WithAttributes( - attribute.Stringer("chainID", chainID), - attribute.Int64("requestID", int64(requestID)), - attribute.Int("responseLen", len(appResponseBytes)), - )) - defer span.End() - - return s.sender.SendCrossChainAppResponse(ctx, chainID, requestID, appResponseBytes) -} - -func (s *tracedSender) SendCrossChainAppError(ctx context.Context, chainID ids.ID, requestID uint32, errorCode int32, errorMessage string) error { - ctx, span := s.tracer.Start(ctx, "tracedSender.SendCrossChainAppError", oteltrace.WithAttributes( - attribute.Stringer("chainID", chainID), - attribute.Int64("requestID", int64(requestID)), - attribute.Int64("errorCode", int64(errorCode)), - attribute.String("errorMessage", errorMessage), - )) - defer span.End() - - return s.sender.SendCrossChainAppError(ctx, chainID, requestID, errorCode, errorMessage) -} - func (s *tracedSender) SendAppRequest(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, appRequestBytes []byte) error { ctx, span := s.tracer.Start(ctx, "tracedSender.SendAppRequest", oteltrace.WithAttributes( attribute.Int64("requestID", int64(requestID)), diff --git a/tests/upgrade/upgrade_test.go b/tests/upgrade/upgrade_test.go index 374af3385f83..de8f292a1d1a 100644 --- a/tests/upgrade/upgrade_test.go +++ b/tests/upgrade/upgrade_test.go @@ -61,7 +61,7 @@ var _ = ginkgo.Describe("[Upgrade]", func() { cChainGenesisStr := network.Genesis.CChainGenesis require.NoError(json.Unmarshal([]byte(cChainGenesisStr), cChainGenesis)) unscheduledActivationTime := uint64(upgrade.UnscheduledActivationTime.Unix()) - cChainGenesis.Config.EUpgradeTime = &unscheduledActivationTime + cChainGenesis.Config.EtnaTime = &unscheduledActivationTime cChainGenesisBytes, err := json.Marshal(cChainGenesis) require.NoError(err) network.Genesis.CChainGenesis = string(cChainGenesisBytes) diff --git a/vms/avm/network/atomic.go b/vms/avm/network/atomic.go index 0774ed36603e..395f09fb8e2c 100644 --- a/vms/avm/network/atomic.go +++ b/vms/avm/network/atomic.go @@ -30,53 +30,6 @@ func NewAtomic(h common.AppHandler) Atomic { return a } -func (a *atomic) CrossChainAppRequest( - ctx context.Context, - chainID ids.ID, - requestID uint32, - deadline time.Time, - msg []byte, -) error { - h := a.handler.Get() - return h.CrossChainAppRequest( - ctx, - chainID, - requestID, - deadline, - msg, - ) -} - -func (a *atomic) CrossChainAppRequestFailed( - ctx context.Context, - chainID ids.ID, - requestID uint32, - appErr *common.AppError, -) error { - h := a.handler.Get() - return h.CrossChainAppRequestFailed( - ctx, - chainID, - requestID, - appErr, - ) -} - -func (a *atomic) CrossChainAppResponse( - ctx context.Context, - chainID ids.ID, - requestID uint32, - msg []byte, -) error { - h := a.handler.Get() - return h.CrossChainAppResponse( - ctx, - chainID, - requestID, - msg, - ) -} - func (a *atomic) AppRequest( ctx context.Context, nodeID ids.NodeID, diff --git a/vms/rpcchainvm/vm_client.go b/vms/rpcchainvm/vm_client.go index 1c4d491ce4d3..c5a358df8edd 100644 --- a/vms/rpcchainvm/vm_client.go +++ b/vms/rpcchainvm/vm_client.go @@ -517,43 +517,6 @@ func (vm *VMClient) Version(ctx context.Context) (string, error) { return resp.Version, nil } -func (vm *VMClient) CrossChainAppRequest(ctx context.Context, chainID ids.ID, requestID uint32, deadline time.Time, request []byte) error { - _, err := vm.client.CrossChainAppRequest( - ctx, - &vmpb.CrossChainAppRequestMsg{ - ChainId: chainID[:], - RequestId: requestID, - Deadline: grpcutils.TimestampFromTime(deadline), - Request: request, - }, - ) - return err -} - -func (vm *VMClient) CrossChainAppRequestFailed(ctx context.Context, chainID ids.ID, requestID uint32, appErr *common.AppError) error { - msg := &vmpb.CrossChainAppRequestFailedMsg{ - ChainId: chainID[:], - RequestId: requestID, - ErrorCode: appErr.Code, - ErrorMessage: appErr.Message, - } - - _, err := vm.client.CrossChainAppRequestFailed(ctx, msg) - return err -} - -func (vm *VMClient) CrossChainAppResponse(ctx context.Context, chainID ids.ID, requestID uint32, response []byte) error { - _, err := vm.client.CrossChainAppResponse( - ctx, - &vmpb.CrossChainAppResponseMsg{ - ChainId: chainID[:], - RequestId: requestID, - Response: response, - }, - ) - return err -} - func (vm *VMClient) AppRequest(ctx context.Context, nodeID ids.NodeID, requestID uint32, deadline time.Time, request []byte) error { _, err := vm.client.AppRequest( ctx, diff --git a/vms/rpcchainvm/vm_server.go b/vms/rpcchainvm/vm_server.go index cc46d819cccd..a5a9266a2434 100644 --- a/vms/rpcchainvm/vm_server.go +++ b/vms/rpcchainvm/vm_server.go @@ -518,39 +518,6 @@ func (vm *VMServer) Version(ctx context.Context, _ *emptypb.Empty) (*vmpb.Versio }, err } -func (vm *VMServer) CrossChainAppRequest(ctx context.Context, msg *vmpb.CrossChainAppRequestMsg) (*emptypb.Empty, error) { - chainID, err := ids.ToID(msg.ChainId) - if err != nil { - return nil, err - } - deadline, err := grpcutils.TimestampAsTime(msg.Deadline) - if err != nil { - return nil, err - } - return &emptypb.Empty{}, vm.vm.CrossChainAppRequest(ctx, chainID, msg.RequestId, deadline, msg.Request) -} - -func (vm *VMServer) CrossChainAppRequestFailed(ctx context.Context, msg *vmpb.CrossChainAppRequestFailedMsg) (*emptypb.Empty, error) { - chainID, err := ids.ToID(msg.ChainId) - if err != nil { - return nil, err - } - - appErr := &common.AppError{ - Code: msg.ErrorCode, - Message: msg.ErrorMessage, - } - return &emptypb.Empty{}, vm.vm.CrossChainAppRequestFailed(ctx, chainID, msg.RequestId, appErr) -} - -func (vm *VMServer) CrossChainAppResponse(ctx context.Context, msg *vmpb.CrossChainAppResponseMsg) (*emptypb.Empty, error) { - chainID, err := ids.ToID(msg.ChainId) - if err != nil { - return nil, err - } - return &emptypb.Empty{}, vm.vm.CrossChainAppResponse(ctx, chainID, msg.RequestId, msg.Response) -} - func (vm *VMServer) AppRequest(ctx context.Context, req *vmpb.AppRequestMsg) (*emptypb.Empty, error) { nodeID, err := ids.ToNodeID(req.NodeId) if err != nil { From 208eff710396c6496358d876f9a989d1dbb45b3a Mon Sep 17 00:00:00 2001 From: felipemadero Date: Tue, 13 Aug 2024 22:38:00 -0300 Subject: [PATCH 13/69] wallet: obtain subnet owners by using P-Chain's getSubnet API call (#3247) --- tests/e2e/p/owner_retrieval.go | 96 +++++++++++++++++++ tests/fixture/tmpnet/subnet.go | 12 +-- vms/example/xsvm/cmd/chain/create/cmd.go | 10 +- vms/platformvm/client.go | 23 +++++ wallet/chain/p/backend.go | 17 +--- wallet/chain/p/builder_test.go | 21 ++-- .../add-permissioned-subnet-validator/main.go | 9 +- .../primary/examples/create-chain/main.go | 9 +- .../examples/remove-subnet-validator/main.go | 9 +- wallet/subnet/primary/wallet.go | 31 ++---- 10 files changed, 159 insertions(+), 78 deletions(-) create mode 100644 tests/e2e/p/owner_retrieval.go diff --git a/tests/e2e/p/owner_retrieval.go b/tests/e2e/p/owner_retrieval.go new file mode 100644 index 000000000000..6ce2dbe3dd08 --- /dev/null +++ b/tests/e2e/p/owner_retrieval.go @@ -0,0 +1,96 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package p + +import ( + "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/tests/fixture/e2e" + "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/vms/platformvm" + "github.com/ava-labs/avalanchego/vms/secp256k1fx" + + ginkgo "github.com/onsi/ginkgo/v2" +) + +var _ = e2e.DescribePChain("[P-Chain Wallet]", func() { + tc := e2e.NewTestContext() + require := require.New(tc) + + ginkgo.It("should support retrieving subnet owners", func() { + env := e2e.GetEnv(tc) + + nodeURI := env.GetRandomNodeURI() + pChainClient := platformvm.NewClient(nodeURI.URI) + + keychain := env.NewKeychain(1) + baseWallet := e2e.NewWallet(tc, keychain, nodeURI) + pWallet := baseWallet.P() + + owner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + keychain.Keys[0].Address(), + }, + } + + tc.By("creating a permissioned subnet") + subnetTx, err := pWallet.IssueCreateSubnetTx( + owner, + tc.WithDefaultContext(), + ) + subnetID := subnetTx.ID() + require.NoError(err) + require.NotEqual(subnetID, constants.PrimaryNetworkID) + + tc.By("verifying owner", func() { + subnetOwners, err := platformvm.GetSubnetOwners( + pChainClient, + tc.DefaultContext(), + subnetID, + ) + require.NoError(err) + subnetOwnerInterface, found := subnetOwners[subnetID] + require.True(found) + subnetOwner, ok := subnetOwnerInterface.(*secp256k1fx.OutputOwners) + require.True(ok) + require.Equal(owner.Locktime, subnetOwner.Locktime) + require.Equal(owner.Threshold, subnetOwner.Threshold) + require.Equal(owner.Addrs, subnetOwner.Addrs) + }) + + newKeychain := env.NewKeychain(1) + newOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + newKeychain.Keys[0].Address(), + }, + } + + tc.By("changing subnet owner") + _, err = pWallet.IssueTransferSubnetOwnershipTx( + subnetID, + newOwner, + tc.WithDefaultContext(), + ) + require.NoError(err) + + tc.By("verifying new owner", func() { + subnetOwners, err := platformvm.GetSubnetOwners( + pChainClient, + tc.DefaultContext(), + subnetID, + ) + require.NoError(err) + subnetOwnerInterface, found := subnetOwners[subnetID] + require.True(found) + subnetOwner, ok := subnetOwnerInterface.(*secp256k1fx.OutputOwners) + require.True(ok) + require.Equal(newOwner.Locktime, subnetOwner.Locktime) + require.Equal(newOwner.Threshold, subnetOwner.Threshold) + require.Equal(newOwner.Addrs, subnetOwner.Addrs) + }) + }) +}) diff --git a/tests/fixture/tmpnet/subnet.go b/tests/fixture/tmpnet/subnet.go index bb48c5260e21..fd021facd172 100644 --- a/tests/fixture/tmpnet/subnet.go +++ b/tests/fixture/tmpnet/subnet.go @@ -87,16 +87,16 @@ func (s *Subnet) GetWallet(ctx context.Context, uri string) (primary.Wallet, err // Only fetch the subnet transaction if a subnet ID is present. This won't be true when // the wallet is first used to create the subnet. - txIDs := set.Set[ids.ID]{} + subnetIDs := []ids.ID{} if s.SubnetID != ids.Empty { - txIDs.Add(s.SubnetID) + subnetIDs = append(subnetIDs, s.SubnetID) } return primary.MakeWallet(ctx, &primary.WalletConfig{ - URI: uri, - AVAXKeychain: keychain, - EthKeychain: keychain, - PChainTxsToFetch: txIDs, + URI: uri, + AVAXKeychain: keychain, + EthKeychain: keychain, + SubnetIDs: subnetIDs, }) } diff --git a/vms/example/xsvm/cmd/chain/create/cmd.go b/vms/example/xsvm/cmd/chain/create/cmd.go index a08edf507117..bd33ea13db6a 100644 --- a/vms/example/xsvm/cmd/chain/create/cmd.go +++ b/vms/example/xsvm/cmd/chain/create/cmd.go @@ -9,8 +9,8 @@ import ( "github.com/spf13/cobra" + "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/example/xsvm/genesis" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary" @@ -42,10 +42,10 @@ func createFunc(c *cobra.Command, args []string) error { // that [uri] is hosting. walletSyncStartTime := time.Now() wallet, err := primary.MakeWallet(ctx, &primary.WalletConfig{ - URI: config.URI, - AVAXKeychain: kc, - EthKeychain: kc, - PChainTxsToFetch: set.Of(config.SubnetID), + URI: config.URI, + AVAXKeychain: kc, + EthKeychain: kc, + SubnetIDs: []ids.ID{config.SubnetID}, }) if err != nil { return err diff --git a/vms/platformvm/client.go b/vms/platformvm/client.go index 95377ce96758..a631176f5e46 100644 --- a/vms/platformvm/client.go +++ b/vms/platformvm/client.go @@ -16,7 +16,9 @@ import ( "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/rpc" + "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/status" + "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) var _ Client = (*client)(nil) @@ -543,3 +545,24 @@ func AwaitTxAccepted( } } } + +// GetSubnetOwners returns a map of subnet ID to current subnet's owner +func GetSubnetOwners( + c Client, + ctx context.Context, + subnetIDs ...ids.ID, +) (map[ids.ID]fx.Owner, error) { + subnetOwners := map[ids.ID]fx.Owner{} + for _, subnetID := range subnetIDs { + subnetInfo, err := c.GetSubnet(ctx, subnetID) + if err != nil { + return nil, err + } + subnetOwners[subnetID] = &secp256k1fx.OutputOwners{ + Locktime: subnetInfo.Locktime, + Threshold: subnetInfo.Threshold, + Addrs: subnetInfo.ControlKeys, + } + } + return subnetOwners, nil +} diff --git a/wallet/chain/p/backend.go b/wallet/chain/p/backend.go index ed8e6a4f8830..8a1cd6b7806c 100644 --- a/wallet/chain/p/backend.go +++ b/wallet/chain/p/backend.go @@ -38,22 +38,7 @@ type backend struct { subnetOwner map[ids.ID]fx.Owner // subnetID -> owner } -func NewBackend(context *builder.Context, utxos common.ChainUTXOs, subnetTxs map[ids.ID]*txs.Tx) Backend { - subnetOwner := make(map[ids.ID]fx.Owner) - for txID, tx := range subnetTxs { // first get owners from the CreateSubnetTx - createSubnetTx, ok := tx.Unsigned.(*txs.CreateSubnetTx) - if !ok { - continue - } - subnetOwner[txID] = createSubnetTx.Owner - } - for _, tx := range subnetTxs { // then check for TransferSubnetOwnershipTx - transferSubnetOwnershipTx, ok := tx.Unsigned.(*txs.TransferSubnetOwnershipTx) - if !ok { - continue - } - subnetOwner[transferSubnetOwnershipTx.Subnet] = transferSubnetOwnershipTx.Owner - } +func NewBackend(context *builder.Context, utxos common.ChainUTXOs, subnetOwner map[ids.ID]fx.Owner) Backend { return &backend{ ChainUTXOs: utxos, context: context, diff --git a/wallet/chain/p/builder_test.go b/wallet/chain/p/builder_test.go index 97ae0992025b..6885a3b4fc9e 100644 --- a/wallet/chain/p/builder_test.go +++ b/wallet/chain/p/builder_test.go @@ -17,6 +17,7 @@ import ( "github.com/ava-labs/avalanchego/utils/set" "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/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" @@ -75,12 +76,8 @@ var ( }, } - subnets = map[ids.ID]*txs.Tx{ - subnetID: { - Unsigned: &txs.CreateSubnetTx{ - Owner: subnetOwner, - }, - }, + subnetOwners = map[ids.ID]fx.Owner{ + subnetID: subnetOwner, } primaryNetworkPermissionlessStaker = &txs.SubnetValidator{ @@ -217,7 +214,7 @@ func TestAddSubnetValidatorTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnets) + backend = NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -249,7 +246,7 @@ func TestRemoveSubnetValidatorTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnets) + backend = NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -290,7 +287,7 @@ func TestCreateChainTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnets) + backend = NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -330,7 +327,7 @@ func TestCreateSubnetTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnets) + backend = NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -362,7 +359,7 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnets) + backend = NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -489,7 +486,7 @@ func TestTransformSubnetTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnets) + backend = NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) diff --git a/wallet/subnet/primary/examples/add-permissioned-subnet-validator/main.go b/wallet/subnet/primary/examples/add-permissioned-subnet-validator/main.go index 33695b35f649..055abdf21221 100644 --- a/wallet/subnet/primary/examples/add-permissioned-subnet-validator/main.go +++ b/wallet/subnet/primary/examples/add-permissioned-subnet-validator/main.go @@ -11,7 +11,6 @@ import ( "github.com/ava-labs/avalanchego/api/info" "github.com/ava-labs/avalanchego/genesis" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -46,10 +45,10 @@ func main() { // [uri] is hosting and registers [subnetID]. walletSyncStartTime := time.Now() wallet, err := primary.MakeWallet(ctx, &primary.WalletConfig{ - URI: uri, - AVAXKeychain: kc, - EthKeychain: kc, - PChainTxsToFetch: set.Of(subnetID), + URI: uri, + AVAXKeychain: kc, + EthKeychain: kc, + SubnetIDs: []ids.ID{subnetID}, }) if err != nil { log.Fatalf("failed to initialize wallet: %s\n", err) diff --git a/wallet/subnet/primary/examples/create-chain/main.go b/wallet/subnet/primary/examples/create-chain/main.go index c626086bce89..9e32490d9aef 100644 --- a/wallet/subnet/primary/examples/create-chain/main.go +++ b/wallet/subnet/primary/examples/create-chain/main.go @@ -12,7 +12,6 @@ import ( "github.com/ava-labs/avalanchego/genesis" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary" @@ -52,10 +51,10 @@ func main() { // [uri] is hosting and registers [subnetID]. walletSyncStartTime := time.Now() wallet, err := primary.MakeWallet(ctx, &primary.WalletConfig{ - URI: uri, - AVAXKeychain: kc, - EthKeychain: kc, - PChainTxsToFetch: set.Of(subnetID), + URI: uri, + AVAXKeychain: kc, + EthKeychain: kc, + SubnetIDs: []ids.ID{subnetID}, }) if err != nil { log.Fatalf("failed to initialize wallet: %s\n", err) diff --git a/wallet/subnet/primary/examples/remove-subnet-validator/main.go b/wallet/subnet/primary/examples/remove-subnet-validator/main.go index 50639943b630..2916d63bb3cb 100644 --- a/wallet/subnet/primary/examples/remove-subnet-validator/main.go +++ b/wallet/subnet/primary/examples/remove-subnet-validator/main.go @@ -10,7 +10,6 @@ import ( "github.com/ava-labs/avalanchego/genesis" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary" ) @@ -38,10 +37,10 @@ func main() { // [uri] is hosting and registers [subnetID]. walletSyncStartTime := time.Now() wallet, err := primary.MakeWallet(ctx, &primary.WalletConfig{ - URI: uri, - AVAXKeychain: kc, - EthKeychain: kc, - PChainTxsToFetch: set.Of(subnetID), + URI: uri, + AVAXKeychain: kc, + EthKeychain: kc, + SubnetIDs: []ids.ID{subnetID}, }) if err != nil { log.Fatalf("failed to initialize wallet: %s\n", err) diff --git a/wallet/subnet/primary/wallet.go b/wallet/subnet/primary/wallet.go index 179e9351ccca..d2c9f4d45050 100644 --- a/wallet/subnet/primary/wallet.go +++ b/wallet/subnet/primary/wallet.go @@ -9,8 +9,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/keychain" - "github.com/ava-labs/avalanchego/utils/set" - "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm" "github.com/ava-labs/avalanchego/wallet/chain/c" "github.com/ava-labs/avalanchego/wallet/chain/p" "github.com/ava-labs/avalanchego/wallet/chain/x" @@ -73,12 +72,9 @@ type WalletConfig struct { // Keys to use for signing all transactions. AVAXKeychain keychain.Keychain // required EthKeychain c.EthKeychain // required - // Set of P-chain transactions that the wallet should know about to be able - // to generate transactions. - PChainTxs map[ids.ID]*txs.Tx // optional - // Set of P-chain transactions that the wallet should fetch to be able to + // Subnet IDs that the wallet should know about to be able to // generate transactions. - PChainTxsToFetch set.Set[ids.ID] // optional + SubnetIDs []ids.ID // optional } // MakeWallet returns a wallet that supports issuing transactions to the chains @@ -104,25 +100,12 @@ func MakeWallet(ctx context.Context, config *WalletConfig) (Wallet, error) { return nil, err } - pChainTxs := config.PChainTxs - if pChainTxs == nil { - pChainTxs = make(map[ids.ID]*txs.Tx) - } - - for txID := range config.PChainTxsToFetch { - txBytes, err := avaxState.PClient.GetTx(ctx, txID) - if err != nil { - return nil, err - } - tx, err := txs.Parse(txs.Codec, txBytes) - if err != nil { - return nil, err - } - pChainTxs[txID] = tx + subnetOwners, err := platformvm.GetSubnetOwners(avaxState.PClient, ctx, config.SubnetIDs...) + if err != nil { + return nil, err } - pUTXOs := common.NewChainUTXOs(constants.PlatformChainID, avaxState.UTXOs) - pBackend := p.NewBackend(avaxState.PCTX, pUTXOs, pChainTxs) + pBackend := p.NewBackend(avaxState.PCTX, pUTXOs, subnetOwners) pBuilder := pbuilder.New(avaxAddrs, avaxState.PCTX, pBackend) pSigner := psigner.New(config.AVAXKeychain, pBackend) From 2eef6414145725a796c5fb4e92d5c529ddd7ce7f Mon Sep 17 00:00:00 2001 From: marun Date: Tue, 13 Aug 2024 18:46:27 -0700 Subject: [PATCH 14/69] [antithesis] Add tmpnet support to workloads to simplify development (#3215) --- .github/workflows/ci.yml | 17 +++ scripts/lib_build_antithesis_images.sh | 1 + tests/antithesis/README.md | 16 ++- tests/antithesis/avalanchego/main.go | 61 +++++----- tests/antithesis/compose.go | 8 +- tests/antithesis/config.go | 140 ++++++++++++++++------- tests/antithesis/node_health.go | 2 +- tests/antithesis/xsvm/main.go | 63 +++++----- tests/fixture/e2e/flags.go | 20 +++- tests/fixture/e2e/ginkgo_test_context.go | 8 +- tests/fixture/tmpnet/node_process.go | 3 +- tests/notify_context.go | 26 +++++ tests/simple_test_context.go | 118 +++++++++++++++++++ tests/test_context.go | 7 +- 14 files changed, 368 insertions(+), 122 deletions(-) create mode 100644 tests/notify_context.go create mode 100644 tests/simple_test_context.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e2d2a87d7199..ffc4a0ae5530 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -206,6 +206,13 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/setup-go-for-project + - name: Build AvalancheGo Binary + shell: bash + run: ./scripts/build.sh -r + - name: Check that the avalanchego workload is sane + shell: bash + run: go run ./tests/antithesis/avalanchego --avalanchego-path=./build/avalanchego --duration=60s - name: Check image build for avalanchego test setup shell: bash run: bash -x scripts/tests.build_antithesis_images.sh @@ -216,6 +223,16 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 + - uses: ./.github/actions/setup-go-for-project + - name: Build AvalancheGo Binary + shell: bash + run: ./scripts/build.sh -r + - name: Build xsvm binary + shell: bash + run: ./scripts/build_xsvm.sh + - name: Check that the xsvm workload is sane + shell: bash + run: go run ./tests/antithesis/xsvm --avalanchego-path=./build/avalanchego --duration=60s - name: Check image build for xsvm test setup shell: bash run: bash -x scripts/tests.build_antithesis_images.sh diff --git a/scripts/lib_build_antithesis_images.sh b/scripts/lib_build_antithesis_images.sh index 3c809128b582..0ab36a0bcdf3 100644 --- a/scripts/lib_build_antithesis_images.sh +++ b/scripts/lib_build_antithesis_images.sh @@ -108,6 +108,7 @@ function gen_antithesis_compose_config { # Ensure the target path is empty before generating the compose config rm -r "${target_path:?}" fi + mkdir -p "${target_path}" # Define the env vars for the compose config generation local compose_env="TARGET_PATH=${target_path} IMAGE_TAG=${image_tag} ${extra_compose_args}" diff --git a/tests/antithesis/README.md b/tests/antithesis/README.md index 34b0d449a1f6..c515dc3e8631 100644 --- a/tests/antithesis/README.md +++ b/tests/antithesis/README.md @@ -69,7 +69,7 @@ test setup. ## Troubleshooting a test setup -### Running a workload directly +### Running a workload with an existing network The workload of the 'avalanchego' test setup can be invoked against an arbitrary network: @@ -86,6 +86,20 @@ chain needs to be provided to the workload: $ AVAWL_URIS=... CHAIN_IDS="2S9ypz...AzMj9" go run ./tests/antithesis/xsvm ``` +### Running a workload with a tmpnet network + +Just like with e2e tests, running an antithesis workload against a +tmpnet network requires specifying an avalanchego path (either as an +argument or an env var): + +```bash +$ go run ./tests/antithesis/avalanchego --avalanchego-path=/path/to/avalanchego +``` + +All tmpnet flags are supported (e.g. `--reuse-network`, +`--stop-network`, `--restart-network`, `--node-count`). See the +[tmpnet documentation](../fixture/tmpnet/README.md) for more details. + ### Running a workload with docker compose v2 Running the test script for a given test setup with the `DEBUG` flag diff --git a/tests/antithesis/avalanchego/main.go b/tests/antithesis/avalanchego/main.go index 7c68ed3fbd23..52c19ed3027a 100644 --- a/tests/antithesis/avalanchego/main.go +++ b/tests/antithesis/avalanchego/main.go @@ -8,16 +8,18 @@ import ( "crypto/rand" "log" "math/big" - "os" "time" "github.com/antithesishq/antithesis-sdk-go/assert" "github.com/antithesishq/antithesis-sdk-go/lifecycle" + "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/genesis" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/tests" "github.com/ava-labs/avalanchego/tests/antithesis" + "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/set" @@ -40,15 +42,17 @@ import ( const NumKeys = 5 func main() { - c, err := antithesis.NewConfig(os.Args) - if err != nil { - log.Fatalf("invalid config: %s", err) - } - - ctx := context.Background() - if err := antithesis.AwaitHealthyNodes(ctx, c.URIs); err != nil { - log.Fatalf("failed to await healthy nodes: %s", err) - } + tc := tests.NewTestContext() + defer tc.Cleanup() + require := require.New(tc) + + c := antithesis.NewConfig( + tc, + &tmpnet.Network{ + Owner: "antithesis-avalanchego", + }, + ) + ctx := tests.DefaultNotifyContext(c.Duration, tc.DeferCleanup) kc := secp256k1fx.NewKeychain(genesis.EWOQKey) walletSyncStartTime := time.Now() @@ -57,9 +61,7 @@ func main() { AVAXKeychain: kc, EthKeychain: kc, }) - if err != nil { - log.Fatalf("failed to initialize wallet: %s", err) - } + require.NoError(err, "failed to initialize wallet") log.Printf("synced wallet in %s", time.Since(walletSyncStartTime)) genesisWorkload := &workload{ @@ -80,9 +82,7 @@ func main() { ) for i := 1; i < NumKeys; i++ { key, err := secp256k1.NewPrivateKey() - if err != nil { - log.Fatalf("failed to generate key: %s", err) - } + require.NoError(err, "failed to generate key") var ( addr = key.Address() @@ -102,11 +102,10 @@ func main() { }, }, }}) - if err != nil { - log.Fatalf("failed to issue initial funding X-chain baseTx: %s", err) - } + require.NoError(err, "failed to issue initial funding X-chain baseTx") log.Printf("issued initial funding X-chain baseTx %s in %s", baseTx.ID(), time.Since(baseStartTime)) + // TODO(marun) Enable cleanup of these contexts genesisWorkload.confirmXChainTx(ctx, baseTx) uri := c.URIs[i%len(c.URIs)] @@ -117,9 +116,7 @@ func main() { AVAXKeychain: kc, EthKeychain: kc, }) - if err != nil { - log.Fatalf("failed to initialize wallet: %s", err) - } + require.NoError(err, "failed to initialize wallet") log.Printf("synced wallet in %s", time.Since(walletSyncStartTime)) workloads[i] = &workload{ @@ -151,6 +148,10 @@ type workload struct { func (w *workload) run(ctx context.Context) { timer := timerpkg.StoppedTimer() + tc := tests.NewTestContext() + defer tc.Cleanup() + require := require.New(tc) + var ( xWallet = w.wallet.X() xBuilder = xWallet.Builder() @@ -158,13 +159,9 @@ func (w *workload) run(ctx context.Context) { pBuilder = pWallet.Builder() ) xBalances, err := xBuilder.GetFTBalance() - if err != nil { - log.Fatalf("failed to fetch X-chain balances: %s", err) - } + require.NoError(err, "failed to fetch X-chain balances") pBalances, err := pBuilder.GetBalance() - if err != nil { - log.Fatalf("failed to fetch P-chain balances: %s", err) - } + require.NoError(err, "failed to fetch P-chain balances") var ( xContext = xBuilder.Context() avaxAssetID = xContext.AVAXAssetID @@ -180,9 +177,7 @@ func (w *workload) run(ctx context.Context) { for { val, err := rand.Int(rand.Reader, big.NewInt(5)) - if err != nil { - log.Fatalf("failed to read randomness: %s", err) - } + require.NoError(err, "failed to read randomness") flowID := val.Int64() log.Printf("wallet %d executing flow %d", w.id, flowID) @@ -200,9 +195,7 @@ func (w *workload) run(ctx context.Context) { } val, err = rand.Int(rand.Reader, big.NewInt(int64(time.Second))) - if err != nil { - log.Fatalf("failed to read randomness: %s", err) - } + require.NoError(err, "failed to read randomness") timer.Reset(time.Duration(val.Int64())) select { diff --git a/tests/antithesis/compose.go b/tests/antithesis/compose.go index 72d91c04e905..85ecf3952c3e 100644 --- a/tests/antithesis/compose.go +++ b/tests/antithesis/compose.go @@ -47,12 +47,12 @@ func GenerateComposeConfig(network *tmpnet.Network, baseImageName string) error // Subnet testing requires creating an initial db state for the bootstrap node if len(network.Subnets) > 0 { - avalancheGoPath := os.Getenv("AVALANCHEGO_PATH") + avalancheGoPath := os.Getenv(tmpnet.AvalancheGoPathEnvName) if len(avalancheGoPath) == 0 { return errAvalancheGoEvVarNotSet } - pluginDir := os.Getenv("AVALANCHEGO_PLUGIN_DIR") + pluginDir := os.Getenv(tmpnet.AvalancheGoPluginDirEnvName) if len(pluginDir) == 0 { return errPluginDirEnvVarNotSet } @@ -230,7 +230,7 @@ func newComposeProject(network *tmpnet.Network, nodeImageName string, workloadIm } workloadEnv := types.Mapping{ - "AVAWL_URIS": strings.Join(uris, " "), + envVarName(URIsKey): strings.Join(uris, " "), } chainIDs := []string{} for _, subnet := range network.Subnets { @@ -239,7 +239,7 @@ func newComposeProject(network *tmpnet.Network, nodeImageName string, workloadIm } } if len(chainIDs) > 0 { - workloadEnv["AVAWL_CHAIN_IDS"] = strings.Join(chainIDs, " ") + workloadEnv[envVarName(ChainIDsKey)] = strings.Join(chainIDs, " ") } workloadName := "workload" diff --git a/tests/antithesis/config.go b/tests/antithesis/config.go index 471b12bb2c17..5d5ea03334d4 100644 --- a/tests/antithesis/config.go +++ b/tests/antithesis/config.go @@ -4,72 +4,128 @@ package antithesis import ( - "errors" - "fmt" + "flag" + "os" + "strings" + "time" - "github.com/spf13/pflag" - "github.com/spf13/viper" + "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/config" - "github.com/ava-labs/avalanchego/wallet/subnet/primary" + "github.com/ava-labs/avalanchego/tests" + "github.com/ava-labs/avalanchego/tests/fixture/e2e" + "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" ) const ( URIsKey = "uris" ChainIDsKey = "chain-ids" + DurationKey = "duration" - FlagsName = "workload" EnvPrefix = "avawl" ) -var ( - errNoURIs = errors.New("at least one URI must be provided") - errNoArguments = errors.New("no arguments") -) - type Config struct { URIs []string ChainIDs []string + Duration time.Duration } -func NewConfig(arguments []string) (*Config, error) { - v, err := parseFlags(arguments) - if err != nil { - return nil, err - } +type SubnetsForNodesFunc func(nodes ...*tmpnet.Node) []*tmpnet.Subnet - c := &Config{ - URIs: v.GetStringSlice(URIsKey), - ChainIDs: v.GetStringSlice(ChainIDsKey), - } - return c, c.Verify() +func NewConfig(tc tests.TestContext, defaultNetwork *tmpnet.Network) *Config { + return NewConfigWithSubnets(tc, defaultNetwork, nil) } -func (c *Config) Verify() error { - if len(c.URIs) == 0 { - return errNoURIs +func NewConfigWithSubnets(tc tests.TestContext, defaultNetwork *tmpnet.Network, getSubnets SubnetsForNodesFunc) *Config { + // tmpnet configuration + flagVars := e2e.RegisterFlags() + + var ( + duration time.Duration + uris CSV + // Accept a list of chain IDs, assume they each belong to a separate subnet + // TODO(marun) Revisit how chain IDs are provided when 1:n subnet:chain configuration is required. + chainIDs CSV + ) + flag.DurationVar(&duration, DurationKey, 0, "[optional] the duration to execute the workload for") + flag.Var(&uris, URIsKey, "[optional] URIs of nodes that the workload can communicate with") + flag.Var(&chainIDs, ChainIDsKey, "[optional] IDs of chains to target for testing") + + flag.Parse() + + // Env vars take priority over flags + envURIs := os.Getenv(envVarName(URIsKey)) + if len(envURIs) > 0 { + // CSV.Set doesn't actually return an error + _ = uris.Set(envURIs) + } + envChainIDs := os.Getenv(envVarName(ChainIDsKey)) + if len(envChainIDs) > 0 { + // CSV.Set doesn't actually return an error + _ = uris.Set(envChainIDs) } - return nil -} -func parseFlags(arguments []string) (*viper.Viper, error) { - if len(arguments) == 0 { - return nil, errNoArguments + // Use the network configuration provided + if len(uris) != 0 { + require.NoError(tc, awaitHealthyNodes(tc.DefaultContext(), uris), "failed to see healthy nodes") + return &Config{ + URIs: uris, + ChainIDs: chainIDs, + Duration: duration, + } } - fs := pflag.NewFlagSet(FlagsName, pflag.ContinueOnError) - fs.StringSlice(URIsKey, []string{primary.LocalAPIURI}, "URIs of nodes that the workload can communicate with") - fs.StringSlice(ChainIDsKey, []string{}, "IDs of chains to target for testing") - if err := fs.Parse(arguments[1:]); err != nil { - return nil, fmt.Errorf("failed parsing CLI flags: %w", err) + // Create a new network + return configForNewNetwork(tc, defaultNetwork, getSubnets, flagVars, duration) +} + +// configForNewNetwork creates a new network and returns the resulting config. +func configForNewNetwork( + tc tests.TestContext, + defaultNetwork *tmpnet.Network, + getSubnets SubnetsForNodesFunc, + flagVars *e2e.FlagVars, + duration time.Duration, +) *Config { + if defaultNetwork.Nodes == nil { + defaultNetwork.Nodes = tmpnet.NewNodesOrPanic(flagVars.NodeCount()) + } + if defaultNetwork.Subnets == nil && getSubnets != nil { + defaultNetwork.Subnets = getSubnets(defaultNetwork.Nodes...) } - v := viper.New() - v.AutomaticEnv() - v.SetEnvKeyReplacer(config.DashesToUnderscores) - v.SetEnvPrefix(EnvPrefix) - if err := v.BindPFlags(fs); err != nil { - return nil, fmt.Errorf("failed binding pflags: %w", err) + testEnv := e2e.NewTestEnvironment(tc, flagVars, defaultNetwork) + + c := &Config{ + Duration: duration, + } + c.URIs = make(CSV, len(testEnv.URIs)) + for i, nodeURI := range testEnv.URIs { + c.URIs[i] = nodeURI.URI + } + network := testEnv.GetNetwork() + c.ChainIDs = make(CSV, len(network.Subnets)) + for i, subnet := range network.Subnets { + c.ChainIDs[i] = subnet.Chains[0].ChainID.String() } - return v, nil + + return c +} + +// CSV is a custom type that implements the flag.Value interface +type CSV []string + +// String returns the string representation of the CSV type +func (c *CSV) String() string { + return strings.Join(*c, ",") +} + +// Set splits the input string by commas and sets the CSV type +func (c *CSV) Set(value string) error { + *c = strings.Split(value, ",") + return nil +} + +func envVarName(key string) string { + return strings.ToUpper(EnvPrefix + "_" + key) } diff --git a/tests/antithesis/node_health.go b/tests/antithesis/node_health.go index 039442398a73..4015f3c9cf23 100644 --- a/tests/antithesis/node_health.go +++ b/tests/antithesis/node_health.go @@ -13,7 +13,7 @@ import ( ) // Waits for the nodes at the provided URIs to report healthy. -func AwaitHealthyNodes(ctx context.Context, uris []string) error { +func awaitHealthyNodes(ctx context.Context, uris []string) error { for _, uri := range uris { if err := awaitHealthyNode(ctx, uri); err != nil { return err diff --git a/tests/antithesis/xsvm/main.go b/tests/antithesis/xsvm/main.go index bb59f769127d..a51a3e88f505 100644 --- a/tests/antithesis/xsvm/main.go +++ b/tests/antithesis/xsvm/main.go @@ -8,15 +8,18 @@ import ( "crypto/rand" "log" "math/big" - "os" "time" "github.com/antithesishq/antithesis-sdk-go/assert" "github.com/antithesishq/antithesis-sdk-go/lifecycle" + "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/genesis" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/tests" "github.com/ava-labs/avalanchego/tests/antithesis" + "github.com/ava-labs/avalanchego/tests/fixture/subnet" + "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" @@ -33,23 +36,29 @@ const ( ) func main() { - c, err := antithesis.NewConfig(os.Args) - if err != nil { - log.Fatalf("invalid config: %s", err) - } - - ctx := context.Background() - if err := antithesis.AwaitHealthyNodes(ctx, c.URIs); err != nil { - log.Fatalf("failed to await healthy nodes: %s", err) - } - - if len(c.ChainIDs) != 1 { - log.Fatalf("expected 1 chainID, saw %d", len(c.ChainIDs)) - } + tc := tests.NewTestContext() + defer tc.Cleanup() + require := require.New(tc) + + c := antithesis.NewConfigWithSubnets( + tc, + &tmpnet.Network{ + Owner: "antithesis-xsvm", + }, + func(nodes ...*tmpnet.Node) []*tmpnet.Subnet { + return []*tmpnet.Subnet{ + subnet.NewXSVMOrPanic("xsvm", genesis.VMRQKey, nodes...), + } + }, + ) + ctx := tests.DefaultNotifyContext(c.Duration, tc.DeferCleanup) + + require.Len(c.ChainIDs, 1) + log.Printf("CHAIN IDS: %v", c.ChainIDs) chainID, err := ids.FromString(c.ChainIDs[0]) - if err != nil { - log.Fatalf("failed to parse chainID: %s", err) - } + require.NoError(err, "failed to parse chainID") + + log.Printf("Using uris %v and chainID %s", c.URIs, chainID) genesisWorkload := &workload{ id: 0, @@ -65,9 +74,7 @@ func main() { initialAmount := 100 * units.KiloAvax for i := 1; i < NumKeys; i++ { key, err := secp256k1.NewPrivateKey() - if err != nil { - log.Fatalf("failed to generate key: %s", err) - } + require.NoError(err, "failed to generate key") var ( addr = key.Address() @@ -84,9 +91,7 @@ func main() { PrivateKey: genesisWorkload.key, }, ) - if err != nil { - log.Fatalf("failed to issue initial funding transfer: %s", err) - } + require.NoError(err, "failed to issue initial funding transfer") log.Printf("issued initial funding transfer %s in %s", transferTxStatus.TxID, time.Since(baseStartTime)) genesisWorkload.confirmTransferTx(ctx, transferTxStatus) @@ -122,13 +127,15 @@ type workload struct { func (w *workload) run(ctx context.Context) { timer := timerpkg.StoppedTimer() + tc := tests.NewTestContext() + defer tc.Cleanup() + require := require.New(tc) + uri := w.uris[w.id%len(w.uris)] client := api.NewClient(uri, w.chainID.String()) balance, err := client.Balance(ctx, w.key.Address(), w.chainID) - if err != nil { - log.Fatalf("failed to fetch balance: %s", err) - } + require.NoError(err, "failed to fetch balance") log.Printf("worker %d starting with a balance of %d", w.id, balance) assert.Reachable("worker starting", map[string]any{ "worker": w.id, @@ -157,9 +164,7 @@ func (w *workload) run(ctx context.Context) { } val, err := rand.Int(rand.Reader, big.NewInt(int64(time.Second))) - if err != nil { - log.Fatalf("failed to read randomness: %s", err) - } + require.NoError(err, "failed to read randomness") timer.Reset(time.Duration(val.Int64())) select { diff --git a/tests/fixture/e2e/flags.go b/tests/fixture/e2e/flags.go index 2b7fc8a3b6a8..05d698ce6262 100644 --- a/tests/fixture/e2e/flags.go +++ b/tests/fixture/e2e/flags.go @@ -71,19 +71,33 @@ func (v *FlagVars) ActivateEtna() bool { return v.activateEtna } +func getEnvWithDefault(envVar, defaultVal string) string { + val := os.Getenv(envVar) + if len(val) == 0 { + return defaultVal + } + return val +} + func RegisterFlags() *FlagVars { vars := FlagVars{} flag.StringVar( &vars.avalancheGoExecPath, "avalanchego-path", os.Getenv(tmpnet.AvalancheGoPathEnvName), - fmt.Sprintf("avalanchego executable path (required if not using an existing network). Also possible to configure via the %s env variable.", tmpnet.AvalancheGoPathEnvName), + fmt.Sprintf( + "[optional] avalanchego executable path if creating a new network. Also possible to configure via the %s env variable.", + tmpnet.AvalancheGoPathEnvName, + ), ) flag.StringVar( &vars.pluginDir, "plugin-dir", - os.ExpandEnv("$HOME/.avalanchego/plugins"), - "[optional] the dir containing VM plugins.", + getEnvWithDefault(tmpnet.AvalancheGoPluginDirEnvName, os.ExpandEnv("$HOME/.avalanchego/plugins")), + fmt.Sprintf( + "[optional] the dir containing VM plugins. Also possible to configure via the %s env variable.", + tmpnet.AvalancheGoPluginDirEnvName, + ), ) flag.StringVar( &vars.networkDir, diff --git a/tests/fixture/e2e/ginkgo_test_context.go b/tests/fixture/e2e/ginkgo_test_context.go index ff3fa7b468a6..39592ae30ce9 100644 --- a/tests/fixture/e2e/ginkgo_test_context.go +++ b/tests/fixture/e2e/ginkgo_test_context.go @@ -35,8 +35,12 @@ func (*GinkgoTestContext) GetWriter() io.Writer { return ginkgo.GinkgoWriter } -func (*GinkgoTestContext) DeferCleanup(args ...interface{}) { - ginkgo.DeferCleanup(args...) +func (*GinkgoTestContext) Cleanup() { + // No-op - ginkgo does this automatically +} + +func (*GinkgoTestContext) DeferCleanup(cleanup func()) { + ginkgo.DeferCleanup(cleanup) } func (*GinkgoTestContext) By(text string, callback ...func()) { diff --git a/tests/fixture/tmpnet/node_process.go b/tests/fixture/tmpnet/node_process.go index 8636d2953fdf..d7d95a697dd5 100644 --- a/tests/fixture/tmpnet/node_process.go +++ b/tests/fixture/tmpnet/node_process.go @@ -26,7 +26,8 @@ import ( ) const ( - AvalancheGoPathEnvName = "AVALANCHEGO_PATH" + AvalancheGoPathEnvName = "AVALANCHEGO_PATH" + AvalancheGoPluginDirEnvName = "AVALANCHEGO_PLUGIN_DIR" defaultNodeInitTimeout = 10 * time.Second ) diff --git a/tests/notify_context.go b/tests/notify_context.go new file mode 100644 index 000000000000..3b20a740b3d8 --- /dev/null +++ b/tests/notify_context.go @@ -0,0 +1,26 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package tests + +import ( + "context" + "os/signal" + "syscall" + "time" +) + +// DefaultNotifyContext returns a context that is marked done when signals indicating +// process termination are received. If a non-zero duration is provided, the parent to the +// notify context will be a context with a timeout for that duration. +func DefaultNotifyContext(duration time.Duration, cleanup func(func())) context.Context { + parentContext := context.Background() + if duration > 0 { + var cancel context.CancelFunc + parentContext, cancel = context.WithTimeout(parentContext, duration) + cleanup(cancel) + } + ctx, stop := signal.NotifyContext(parentContext, syscall.SIGTERM, syscall.SIGINT) + cleanup(stop) + return ctx +} diff --git a/tests/simple_test_context.go b/tests/simple_test_context.go new file mode 100644 index 000000000000..3be2c050f6e4 --- /dev/null +++ b/tests/simple_test_context.go @@ -0,0 +1,118 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package tests + +import ( + "context" + "fmt" + "io" + "log" + "os" + "time" + + "github.com/onsi/ginkgo/v2/formatter" + "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" +) + +const failNowMessage = "SimpleTestContext.FailNow called" + +type SimpleTestContext struct { + cleanupFuncs []func() + cleanupCalled bool +} + +func NewTestContext() *SimpleTestContext { + return &SimpleTestContext{} +} + +func (*SimpleTestContext) Errorf(format string, args ...interface{}) { + log.Printf("error: "+format, args...) +} + +func (*SimpleTestContext) FailNow() { + panic(failNowMessage) +} + +func (*SimpleTestContext) GetWriter() io.Writer { + return os.Stdout +} + +// Cleanup is intended to be deferred by the caller to ensure cleanup is performed even +// in the event that a panic occurs. +func (tc *SimpleTestContext) Cleanup() { + if tc.cleanupCalled { + return + } + tc.cleanupCalled = true + + // Only exit non-zero if a cleanup caused a panic + exitNonZero := false + + var panicData any + if r := recover(); r != nil { + errorString, ok := r.(string) + if !ok || errorString != failNowMessage { + // Retain the panic data to raise after cleanup + panicData = r + } else { + exitNonZero = true + } + } + + for _, cleanupFunc := range tc.cleanupFuncs { + func() { + // Ensure a failed cleanup doesn't prevent subsequent cleanup functions from running + defer func() { + if r := recover(); r != nil { + exitNonZero = true + fmt.Println("Recovered from panic during cleanup:", r) + } + }() + cleanupFunc() + }() + } + + if panicData != nil { + panic(panicData) + } + if exitNonZero { + os.Exit(1) + } +} + +func (tc *SimpleTestContext) DeferCleanup(cleanup func()) { + tc.cleanupFuncs = append(tc.cleanupFuncs, cleanup) +} + +func (tc *SimpleTestContext) By(_ string, _ ...func()) { + tc.Errorf("By not yet implemented") + tc.FailNow() +} + +// TODO(marun) Enable color output equivalent to GinkgoTestContext.Outf +func (*SimpleTestContext) Outf(format string, args ...interface{}) { + s := formatter.F(format, args...) + log.Print(s) +} + +// Helper simplifying use of a timed context by canceling the context on ginkgo teardown. +func (tc *SimpleTestContext) ContextWithTimeout(duration time.Duration) context.Context { + return ContextWithTimeout(tc, duration) +} + +// Helper simplifying use of a timed context configured with the default timeout. +func (tc *SimpleTestContext) DefaultContext() context.Context { + return DefaultContext(tc) +} + +// Helper simplifying use via an option of a timed context configured with the default timeout. +func (tc *SimpleTestContext) WithDefaultContext() common.Option { + return WithDefaultContext(tc) +} + +func (tc *SimpleTestContext) Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msg string) { + require.Eventually(tc, condition, waitFor, tick, msg) +} diff --git a/tests/test_context.go b/tests/test_context.go index 2ddacf555a48..54ed9120a414 100644 --- a/tests/test_context.go +++ b/tests/test_context.go @@ -20,11 +20,8 @@ type TestContext interface { // Ensures compatibility with ginkgo.By By(text string, callback ...func()) - // Ensures compatibility with ginkgo.DeferCleanup - // - // TODO(marun) Ensure registered cleanup functions are called at - // the end of the registering test. - DeferCleanup(args ...interface{}) + // Provides a simple alternative to ginkgo.DeferCleanup + DeferCleanup(cleanup func()) // Enables color output to stdout Outf(format string, args ...interface{}) From 6d897324b6c63a2f84bc292f10a7f21991892275 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Wed, 14 Aug 2024 22:38:32 -0400 Subject: [PATCH 15/69] Refactor e2e tests for P-chain tests (#3295) --- tests/e2e/c/dynamic_fees.go | 8 +- tests/e2e/c/interchain_workflow.go | 14 +- tests/e2e/p/interchain_workflow.go | 75 ++++---- tests/e2e/p/staking_rewards.go | 292 +++++++++++++++-------------- tests/e2e/p/validator_sets.go | 47 ++--- tests/e2e/p/workflow.go | 272 +++++++++++++-------------- tests/e2e/vms/xsvm.go | 6 +- tests/e2e/x/interchain_workflow.go | 6 +- tests/fixture/e2e/helpers.go | 8 + 9 files changed, 371 insertions(+), 357 deletions(-) diff --git a/tests/e2e/c/dynamic_fees.go b/tests/e2e/c/dynamic_fees.go index ea3921bcf5f0..6b554087a996 100644 --- a/tests/e2e/c/dynamic_fees.go +++ b/tests/e2e/c/dynamic_fees.go @@ -16,7 +16,6 @@ import ( "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" ginkgo "github.com/onsi/ginkgo/v2" ) @@ -142,9 +141,10 @@ var _ = e2e.DescribeCChain("[Dynamic Fees]", func() { tc.By("sending funds at the current gas price", func() { // Create a recipient address - recipientKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - recipientEthAddress := evm.GetEthAddress(recipientKey) + var ( + recipientKey = e2e.NewPrivateKey(tc) + recipientEthAddress = evm.GetEthAddress(recipientKey) + ) // Create transaction nonce, err := ethClient.AcceptedNonceAt(tc.DefaultContext(), ethAddress) diff --git a/tests/e2e/c/interchain_workflow.go b/tests/e2e/c/interchain_workflow.go index 3ec8b0b6e478..c50f75df34de 100644 --- a/tests/e2e/c/interchain_workflow.go +++ b/tests/e2e/c/interchain_workflow.go @@ -13,7 +13,6 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -39,11 +38,12 @@ var _ = e2e.DescribeCChain("[Interchain Workflow]", func() { ethClient := e2e.NewEthClient(tc, nodeURI) tc.By("allocating a pre-funded key to send from and a recipient key to deliver to") - senderKey := env.AllocatePreFundedKey() - senderEthAddress := evm.GetEthAddress(senderKey) - recipientKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - recipientEthAddress := evm.GetEthAddress(recipientKey) + var ( + senderKey = env.AllocatePreFundedKey() + senderEthAddress = evm.GetEthAddress(senderKey) + recipientKey = e2e.NewPrivateKey(tc) + recipientEthAddress = evm.GetEthAddress(recipientKey) + ) tc.By("sending funds from one address to another on the C-Chain", func() { // Create transaction @@ -150,7 +150,7 @@ var _ = e2e.DescribeCChain("[Interchain Workflow]", func() { }) tc.By("importing AVAX from the C-Chain to the P-Chain", func() { - _, err = pWallet.IssueImportTx( + _, err := pWallet.IssueImportTx( cContext.BlockchainID, &recipientOwner, tc.WithDefaultContext(), diff --git a/tests/e2e/p/interchain_workflow.go b/tests/e2e/p/interchain_workflow.go index e0be6c45be4c..fae886168103 100644 --- a/tests/e2e/p/interchain_workflow.go +++ b/tests/e2e/p/interchain_workflow.go @@ -17,7 +17,6 @@ import ( "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" @@ -30,18 +29,21 @@ import ( ) var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainLabel), func() { - tc := e2e.NewTestContext() - require := require.New(tc) - - const ( - transferAmount = 10 * units.Avax - weight = 2_000 * units.Avax // Used for both validation and delegation + var ( + tc = e2e.NewTestContext() + require = require.New(tc) ) ginkgo.It("should ensure that funds can be transferred from the P-Chain to the X-Chain and the C-Chain", func() { - env := e2e.GetEnv(tc) + const ( + transferAmount = 10 * units.Avax + weight = 2_000 * units.Avax // Used for both validation and delegation + ) - network := env.GetNetwork() + var ( + env = e2e.GetEnv(tc) + network = env.GetNetwork() + ) tc.By("checking that the network has a compatible minimum stake duration", func() { minStakeDuration := cast.ToDuration(network.DefaultFlags[config.MinStakeDurationKey]) @@ -49,26 +51,31 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL }) tc.By("creating wallet with a funded key to send from and recipient key to deliver to") - recipientKey, err := secp256k1.NewPrivateKey() - require.NoError(err) + recipientKey := e2e.NewPrivateKey(tc) keychain := env.NewKeychain(1) keychain.Add(recipientKey) - nodeURI := env.GetRandomNodeURI() - baseWallet := e2e.NewWallet(tc, keychain, nodeURI) - xWallet := baseWallet.X() - cWallet := baseWallet.C() - pWallet := baseWallet.P() - - xBuilder := xWallet.Builder() - xContext := xBuilder.Context() - pBuilder := pWallet.Builder() - pContext := pBuilder.Context() - cBuilder := cWallet.Builder() - cContext := cBuilder.Context() + + var ( + nodeURI = env.GetRandomNodeURI() + baseWallet = e2e.NewWallet(tc, keychain, nodeURI) + + xWallet = baseWallet.X() + xBuilder = xWallet.Builder() + xContext = xBuilder.Context() + + pWallet = baseWallet.P() + pBuilder = pWallet.Builder() + pContext = pBuilder.Context() + + cWallet = baseWallet.C() + cBuilder = cWallet.Builder() + cContext = cBuilder.Context() + + avaxAssetID = xContext.AVAXAssetID + ) tc.By("defining common configuration") recipientEthAddress := evm.GetEthAddress(recipientKey) - avaxAssetID := xContext.AVAXAssetID // Use the same owner for sending to X-Chain and importing funds to P-Chain recipientOwner := secp256k1fx.OutputOwners{ Threshold: 1, @@ -106,14 +113,16 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL // Adding a validator should not break interchain transfer. endTime := time.Now().Add(30 * time.Second) tc.By("adding the new node as a validator", func() { - rewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - const ( delegationPercent = 0.10 // 10% delegationShare = reward.PercentDenominator * delegationPercent ) + var ( + rewardKey = e2e.NewPrivateKey(tc) + rewardAddr = rewardKey.Address() + ) + _, err = pWallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -127,11 +136,11 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL pContext.AVAXAssetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{rewardKey.Address()}, + Addrs: []ids.ShortID{rewardAddr}, }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{rewardKey.Address()}, + Addrs: []ids.ShortID{rewardAddr}, }, delegationShare, tc.WithDefaultContext(), @@ -141,8 +150,10 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL // Adding a delegator should not break interchain transfer. tc.By("adding a delegator to the new node", func() { - rewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) + var ( + rewardKey = e2e.NewPrivateKey(tc) + rewardAddr = rewardKey.Address() + ) _, err = pWallet.IssueAddPermissionlessDelegatorTx( &txs.SubnetValidator{ @@ -156,7 +167,7 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL pContext.AVAXAssetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{rewardKey.Address()}, + Addrs: []ids.ShortID{rewardAddr}, }, tc.WithDefaultContext(), ) diff --git a/tests/e2e/p/staking_rewards.go b/tests/e2e/p/staking_rewards.go index 2eff3f212a71..6f25531fa8a3 100644 --- a/tests/e2e/p/staking_rewards.go +++ b/tests/e2e/p/staking_rewards.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/api/info" "github.com/ava-labs/avalanchego/config" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/tests" "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/constants" @@ -27,19 +28,26 @@ import ( ginkgo "github.com/onsi/ginkgo/v2" ) -const ( - targetDelegationPeriod = 15 * time.Second - targetValidationPeriod = 30 * time.Second -) - var _ = ginkgo.Describe("[Staking Rewards]", func() { - tc := e2e.NewTestContext() - require := require.New(tc) + var ( + tc = e2e.NewTestContext() + require = require.New(tc) + ) ginkgo.It("should ensure that validator node uptime determines whether a staking reward is issued", func() { - env := e2e.GetEnv(tc) + const ( + targetDelegationPeriod = 15 * time.Second + targetValidationPeriod = 30 * time.Second + + delegationPercent = 0.10 // 10% + delegationShare = reward.PercentDenominator * delegationPercent + weight = 2_000 * units.Avax + ) - network := env.GetNetwork() + var ( + env = e2e.GetEnv(tc) + network = env.GetNetwork() + ) tc.By("checking that the network has a compatible minimum stake duration", func() { minStakeDuration := cast.ToDuration(network.DefaultFlags[config.MinStakeDurationKey]) @@ -68,68 +76,56 @@ var _ = ginkgo.Describe("[Staking Rewards]", func() { betaNodeID, betaPOP, err := betaInfoClient.GetNodeID(tc.DefaultContext()) require.NoError(err) - tc.By("generating reward keys") - - alphaValidationRewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - alphaDelegationRewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - - betaValidationRewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - betaDelegationRewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - - gammaDelegationRewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - - deltaDelegationRewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) + tc.By("creating keychain and P-Chain wallet") + var ( + alphaValidationRewardKey = e2e.NewPrivateKey(tc) + alphaDelegationRewardKey = e2e.NewPrivateKey(tc) + betaValidationRewardKey = e2e.NewPrivateKey(tc) + betaDelegationRewardKey = e2e.NewPrivateKey(tc) + gammaDelegationRewardKey = e2e.NewPrivateKey(tc) + deltaDelegationRewardKey = e2e.NewPrivateKey(tc) + + rewardKeys = []*secp256k1.PrivateKey{ + alphaValidationRewardKey, + alphaDelegationRewardKey, + betaValidationRewardKey, + betaDelegationRewardKey, + gammaDelegationRewardKey, + deltaDelegationRewardKey, + } - rewardKeys := []*secp256k1.PrivateKey{ - alphaValidationRewardKey, - alphaDelegationRewardKey, - betaValidationRewardKey, - betaDelegationRewardKey, - gammaDelegationRewardKey, - deltaDelegationRewardKey, - } + keychain = secp256k1fx.NewKeychain(rewardKeys...) + ) - tc.By("creating keychain and P-Chain wallet") - keychain := secp256k1fx.NewKeychain(rewardKeys...) fundedKey := env.AllocatePreFundedKey() keychain.Add(fundedKey) - nodeURI := tmpnet.NodeURI{ - NodeID: alphaNodeID, - URI: alphaNode.URI, - } - baseWallet := e2e.NewWallet(tc, keychain, nodeURI) - pWallet := baseWallet.P() - pBuilder := pWallet.Builder() - pContext := pBuilder.Context() + var ( + nodeURI = tmpnet.NodeURI{ + NodeID: alphaNodeID, + URI: alphaNode.URI, + } + baseWallet = e2e.NewWallet(tc, keychain, nodeURI) + pWallet = baseWallet.P() + pBuilder = pWallet.Builder() + pContext = pBuilder.Context() - const ( - delegationPercent = 0.10 // 10% - delegationShare = reward.PercentDenominator * delegationPercent - weight = 2_000 * units.Avax + pvmClient = platformvm.NewClient(alphaNode.URI) ) - pvmClient := platformvm.NewClient(alphaNode.URI) - - tc.By("retrieving supply before inserting validators") - supplyAtValidatorsStart, _, err := pvmClient.GetCurrentSupply(tc.DefaultContext(), constants.PrimaryNetworkID) + tc.By("retrieving supply before adding alpha node as a validator") + supplyAtAlphaNodeStart, _, err := pvmClient.GetCurrentSupply(tc.DefaultContext(), constants.PrimaryNetworkID) require.NoError(err) - alphaValidatorsEndTime := time.Now().Add(targetValidationPeriod) - tc.Outf("alpha node validation period ending at: %v\n", alphaValidatorsEndTime) - tc.By("adding alpha node as a validator", func() { + endTime := time.Now().Add(targetValidationPeriod) + tc.Outf("validation period ending at: %v\n", endTime) + _, err := pWallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: alphaNodeID, - End: uint64(alphaValidatorsEndTime.Unix()), + End: uint64(endTime.Unix()), Wght: weight, }, Subnet: constants.PrimaryNetworkID, @@ -179,19 +175,19 @@ var _ = ginkgo.Describe("[Staking Rewards]", func() { require.NoError(err) }) - tc.By("retrieving supply before inserting delegators") - supplyAtDelegatorsStart, _, err := pvmClient.GetCurrentSupply(tc.DefaultContext(), constants.PrimaryNetworkID) + tc.By("retrieving supply before adding gamma as a delegator") + supplyAtGammaDelegatorStart, _, err := pvmClient.GetCurrentSupply(tc.DefaultContext(), constants.PrimaryNetworkID) require.NoError(err) - gammaDelegatorEndTime := time.Now().Add(targetDelegationPeriod) - tc.Outf("gamma delegation period ending at: %v\n", gammaDelegatorEndTime) + tc.By("adding gamma as a delegator to the alpha node", func() { + endTime := time.Now().Add(targetDelegationPeriod) + tc.Outf("delegation period ending at: %v\n", endTime) - tc.By("adding gamma as delegator to the alpha node", func() { _, err := pWallet.IssueAddPermissionlessDelegatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: alphaNodeID, - End: uint64(gammaDelegatorEndTime.Unix()), + End: uint64(endTime.Unix()), Wght: weight, }, Subnet: constants.PrimaryNetworkID, @@ -206,15 +202,15 @@ var _ = ginkgo.Describe("[Staking Rewards]", func() { require.NoError(err) }) - deltaDelegatorEndTime := time.Now().Add(targetDelegationPeriod) - tc.Outf("delta delegation period ending at: %v\n", deltaDelegatorEndTime) - tc.By("adding delta as delegator to the beta node", func() { + endTime := time.Now().Add(targetDelegationPeriod) + tc.Outf("delegation period ending at: %v\n", endTime) + _, err := pWallet.IssueAddPermissionlessDelegatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: betaNodeID, - End: uint64(deltaDelegatorEndTime.Unix()), + End: uint64(endTime.Unix()), Wght: weight, }, Subnet: constants.PrimaryNetworkID, @@ -229,84 +225,104 @@ var _ = ginkgo.Describe("[Staking Rewards]", func() { require.NoError(err) }) - tc.By("stopping beta node to prevent it and its delegator from receiving a validation reward") - require.NoError(betaNode.Stop(tc.DefaultContext())) + tc.By("stopping beta node to prevent it and its delegator from receiving a validation reward", func() { + require.NoError(betaNode.Stop(tc.DefaultContext())) + }) tc.By("retrieving staking periods from the chain") - data, err := pvmClient.GetCurrentValidators(tc.DefaultContext(), constants.PlatformChainID, []ids.NodeID{alphaNodeID}) + currentValidators, err := pvmClient.GetCurrentValidators(tc.DefaultContext(), constants.PlatformChainID, []ids.NodeID{alphaNodeID}) require.NoError(err) - require.Len(data, 1) - actualAlphaValidationPeriod := time.Duration(data[0].EndTime-data[0].StartTime) * time.Second - delegatorData := data[0].Delegators[0] - actualGammaDelegationPeriod := time.Duration(delegatorData.EndTime-delegatorData.StartTime) * time.Second - - tc.By("waiting until all validation periods are over") - // The beta validator was the last added and so has the latest end time. The - // delegation periods are shorter than the validation periods. - time.Sleep(time.Until(betaValidatorEndTime)) - - tc.By("waiting until the alpha and beta nodes are no longer validators") - tc.Eventually(func() bool { - validators, err := pvmClient.GetCurrentValidators(tc.DefaultContext(), constants.PrimaryNetworkID, nil) - require.NoError(err) - for _, validator := range validators { - if validator.NodeID == alphaNodeID || validator.NodeID == betaNodeID { - return false + require.Len(currentValidators, 1) + alphaValidator := currentValidators[0] + require.Len(alphaValidator.Delegators, 1) + gammaDelegator := alphaValidator.Delegators[0] + actualAlphaValidationPeriod := time.Duration(alphaValidator.EndTime-alphaValidator.StartTime) * time.Second + actualGammaDelegationPeriod := time.Duration(gammaDelegator.EndTime-gammaDelegator.StartTime) * time.Second + + tc.By("waiting until the alpha and beta nodes are no longer validators", func() { + // The beta validator was the last added and so has the latest end + // time. The delegation periods are shorter than the validation + // periods. + time.Sleep(time.Until(betaValidatorEndTime)) + + // To avoid racy behavior, we confirm that the nodes are no longer + // validators before advancing. + tc.Eventually(func() bool { + validators, err := pvmClient.GetCurrentValidators(tc.DefaultContext(), constants.PrimaryNetworkID, nil) + require.NoError(err) + for _, validator := range validators { + if validator.NodeID == alphaNodeID || validator.NodeID == betaNodeID { + return false + } } + return true + }, e2e.DefaultTimeout, e2e.DefaultPollingInterval, "nodes failed to stop validating before timeout") + }) + + tc.By("checking expected rewards against actual rewards", func() { + var ( + adminClient = admin.NewClient(nodeURI.URI) + rewardConfig = getRewardConfig(tc, adminClient) + calculator = reward.NewCalculator(rewardConfig) + + expectedValidationReward = calculator.Calculate(actualAlphaValidationPeriod, weight, supplyAtAlphaNodeStart) + + potentialDelegationReward = calculator.Calculate(actualGammaDelegationPeriod, weight, supplyAtGammaDelegatorStart) + expectedDelegationFee, expectedDelegatorReward = reward.Split(potentialDelegationReward, delegationShare) + ) + + rewardBalances := make(map[ids.ShortID]uint64, len(rewardKeys)) + for _, rewardKey := range rewardKeys { + var ( + keychain = secp256k1fx.NewKeychain(rewardKey) + baseWallet = e2e.NewWallet(tc, keychain, nodeURI) + pWallet = baseWallet.P() + pBuilder = pWallet.Builder() + ) + + balances, err := pBuilder.GetBalance() + require.NoError(err) + rewardBalances[rewardKey.Address()] = balances[pContext.AVAXAssetID] } - return true - }, e2e.DefaultTimeout, e2e.DefaultPollingInterval, "nodes failed to stop validating before timeout ") - - tc.By("retrieving reward configuration for the network") - // TODO(marun) Enable GetConfig to return *node.Config - // directly. Currently, due to a circular dependency issue, a - // map-based equivalent is used for which manual unmarshaling - // is required. - adminClient := admin.NewClient(env.GetRandomNodeURI().URI) - rawNodeConfigMap, err := adminClient.GetConfig(tc.DefaultContext()) - require.NoError(err) - nodeConfigMap, ok := rawNodeConfigMap.(map[string]interface{}) - require.True(ok) - stakingConfigMap, ok := nodeConfigMap["stakingConfig"].(map[string]interface{}) - require.True(ok) - rawRewardConfig := stakingConfigMap["rewardConfig"] - rewardConfig := reward.Config{} - require.NoError(mapstructure.Decode(rawRewardConfig, &rewardConfig)) - - tc.By("retrieving reward address balances") - rewardBalances := make(map[ids.ShortID]uint64, len(rewardKeys)) - for _, rewardKey := range rewardKeys { - keychain := secp256k1fx.NewKeychain(rewardKey) - baseWallet := e2e.NewWallet(tc, keychain, nodeURI) - pWallet := baseWallet.P() - balances, err := pWallet.Builder().GetBalance() - require.NoError(err) - rewardBalances[rewardKey.Address()] = balances[pContext.AVAXAssetID] - } - require.Len(rewardBalances, len(rewardKeys)) - - tc.By("determining expected validation and delegation rewards") - calculator := reward.NewCalculator(rewardConfig) - expectedValidationReward := calculator.Calculate(actualAlphaValidationPeriod, weight, supplyAtValidatorsStart) - potentialDelegationReward := calculator.Calculate(actualGammaDelegationPeriod, weight, supplyAtDelegatorsStart) - expectedDelegationFee, expectedDelegatorReward := reward.Split(potentialDelegationReward, delegationShare) - - tc.By("checking expected rewards against actual rewards") - expectedRewardBalances := map[ids.ShortID]uint64{ - alphaValidationRewardKey.Address(): expectedValidationReward, - alphaDelegationRewardKey.Address(): expectedDelegationFee, - betaValidationRewardKey.Address(): 0, // Validator didn't meet uptime requirement - betaDelegationRewardKey.Address(): 0, // Validator didn't meet uptime requirement - gammaDelegationRewardKey.Address(): expectedDelegatorReward, - deltaDelegationRewardKey.Address(): 0, // Validator didn't meet uptime requirement - } - for address := range expectedRewardBalances { - require.Equal(expectedRewardBalances[address], rewardBalances[address]) - } - - tc.By("stopping alpha to free up resources for a bootstrap check") - require.NoError(alphaNode.Stop(tc.DefaultContext())) + + require.Equal( + map[ids.ShortID]uint64{ + alphaValidationRewardKey.Address(): expectedValidationReward, + alphaDelegationRewardKey.Address(): expectedDelegationFee, + betaValidationRewardKey.Address(): 0, // Validator didn't meet uptime requirement + betaDelegationRewardKey.Address(): 0, // Validator didn't meet uptime requirement + gammaDelegationRewardKey.Address(): expectedDelegatorReward, + deltaDelegationRewardKey.Address(): 0, // Validator didn't meet uptime requirement + }, + rewardBalances, + ) + }) + + tc.By("stopping alpha to free up resources for a bootstrap check", func() { + require.NoError(alphaNode.Stop(tc.DefaultContext())) + }) _ = e2e.CheckBootstrapIsPossible(tc, network) }) }) + +// TODO(marun) Enable GetConfig to return *node.Config directly. Currently, due +// to a circular dependency issue, a map-based equivalent is used for which +// manual unmarshaling is required. +func getRewardConfig(tc tests.TestContext, client admin.Client) reward.Config { + require := require.New(tc) + + rawNodeConfigMap, err := client.GetConfig(tc.DefaultContext()) + require.NoError(err) + nodeConfigMap, ok := rawNodeConfigMap.(map[string]interface{}) + require.True(ok) + stakingConfigMap, ok := nodeConfigMap["stakingConfig"].(map[string]interface{}) + require.True(ok) + + var rewardConfig reward.Config + require.NoError(mapstructure.Decode( + stakingConfigMap["rewardConfig"], + &rewardConfig, + )) + return rewardConfig +} diff --git a/tests/e2e/p/validator_sets.go b/tests/e2e/p/validator_sets.go index d13e056929c2..5dc7345cadd6 100644 --- a/tests/e2e/p/validator_sets.go +++ b/tests/e2e/p/validator_sets.go @@ -13,9 +13,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/tests/fixture/e2e" - "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/platformvm" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -24,39 +22,42 @@ import ( ) var _ = e2e.DescribePChain("[Validator Sets]", func() { - tc := e2e.NewTestContext() - require := require.New(tc) + var ( + tc = e2e.NewTestContext() + require = require.New(tc) + ) ginkgo.It("should be identical for every height for all nodes in the network", func() { - env := e2e.GetEnv(tc) - - network := env.GetNetwork() + var ( + env = e2e.GetEnv(tc) + network = env.GetNetwork() + ) tc.By("creating wallet with a funded key to source delegated funds from") - keychain := env.NewKeychain(1) - nodeURI := env.GetRandomNodeURI() - baseWallet := e2e.NewWallet(tc, keychain, nodeURI) - pWallet := baseWallet.P() - - pBuilder := pWallet.Builder() - pContext := pBuilder.Context() + var ( + keychain = env.NewKeychain(1) + nodeURI = env.GetRandomNodeURI() + baseWallet = e2e.NewWallet(tc, keychain, nodeURI) + pWallet = baseWallet.P() + pBuilder = pWallet.Builder() + pContext = pBuilder.Context() + avaxAssetID = pContext.AVAXAssetID + ) const delegatorCount = 15 tc.By(fmt.Sprintf("adding %d delegators", delegatorCount), func() { - rewardKey, err := secp256k1.NewPrivateKey() - require.NoError(err) - avaxAssetID := pContext.AVAXAssetID - startTime := time.Now().Add(tmpnet.DefaultValidatorStartTimeDiff) - endTime := startTime.Add(time.Second * 360) - // This is the default flag value for MinDelegatorStake. - weight := genesis.LocalParams.StakingConfig.MinDelegatorStake + var ( + rewardKey = e2e.NewPrivateKey(tc) + endTime = time.Now().Add(time.Second * 360) + // This is the default flag value for MinDelegatorStake. + weight = genesis.LocalParams.StakingConfig.MinDelegatorStake + ) for i := 0; i < delegatorCount; i++ { - _, err = pWallet.IssueAddPermissionlessDelegatorTx( + _, err := pWallet.IssueAddPermissionlessDelegatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeURI.NodeID, - Start: uint64(startTime.Unix()), End: uint64(endTime.Unix()), Wght: weight, }, diff --git a/tests/e2e/p/workflow.go b/tests/e2e/p/workflow.go index fc539010ed53..243e7efc4451 100644 --- a/tests/e2e/p/workflow.go +++ b/tests/e2e/p/workflow.go @@ -8,7 +8,6 @@ import ( "github.com/stretchr/testify/require" - "github.com/ava-labs/avalanchego/api/info" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/utils" @@ -25,177 +24,160 @@ import ( ) // PChainWorkflow is an integration test for normal P-Chain operations -// - Issues an Add Validator and an Add Delegator using the funding address -// - Exports AVAX from the P-Chain funding address to the X-Chain created address -// - Exports AVAX from the X-Chain created address to the P-Chain created address -// - Checks the expected value of the funding address +// - Issues an AddPermissionlessValidatorTx +// - Issues an AddPermissionlessDelegatorTx +// - Issues an ExportTx on the P-chain and verifies the expected balances +// - Issues an ImportTx on the X-chain and verifies the expected balances var _ = e2e.DescribePChain("[Workflow]", func() { - tc := e2e.NewTestContext() - require := require.New(tc) - - ginkgo.It("P-chain main operations", - func() { - env := e2e.GetEnv(tc) - - nodeURI := env.GetRandomNodeURI() - keychain := env.NewKeychain(2) - baseWallet := e2e.NewWallet(tc, keychain, nodeURI) - - pWallet := baseWallet.P() - pBuilder := pWallet.Builder() - pContext := pBuilder.Context() - avaxAssetID := pContext.AVAXAssetID - xWallet := baseWallet.X() - xBuilder := xWallet.Builder() - xContext := xBuilder.Context() - pChainClient := platformvm.NewClient(nodeURI.URI) - - tc.Outf("{{blue}} fetching minimal stake amounts {{/}}\n") - minValStake, minDelStake, err := pChainClient.GetMinStake(tc.DefaultContext(), constants.PlatformChainID) - require.NoError(err) - tc.Outf("{{green}} minimal validator stake: %d {{/}}\n", minValStake) - tc.Outf("{{green}} minimal delegator stake: %d {{/}}\n", minDelStake) - - tc.Outf("{{blue}} fetching tx fee {{/}}\n") - infoClient := info.NewClient(nodeURI.URI) - fees, err := infoClient.GetTxFee(tc.DefaultContext()) - require.NoError(err) - txFees := uint64(fees.TxFee) - tc.Outf("{{green}} txFee: %d {{/}}\n", txFees) + var ( + tc = e2e.NewTestContext() + require = require.New(tc) + ) + ginkgo.It("P-chain main operations", func() { + const ( // amount to transfer from P to X chain - toTransfer := 1 * units.Avax - - pShortAddr := keychain.Keys[0].Address() - xTargetAddr := keychain.Keys[1].Address() - tc.By("check selected keys have sufficient funds", func() { - pBalances, err := pWallet.Builder().GetBalance() - pBalance := pBalances[avaxAssetID] - minBalance := minValStake + txFees + minDelStake + txFees + toTransfer + txFees - require.NoError(err) - require.GreaterOrEqual(pBalance, minBalance) - }) - - // Use a random node ID to ensure that repeated test runs - // will succeed against a network that persists across runs. - validatorID, err := ids.ToNodeID(utils.RandomBytes(ids.NodeIDLen)) - require.NoError(err) + toTransfer = 1 * units.Avax + delegationFeeShares uint32 = 20000 // TODO: retrieve programmatically + ) - vdr := &txs.SubnetValidator{ - Validator: txs.Validator{ - NodeID: validatorID, - End: uint64(time.Now().Add(72 * time.Hour).Unix()), - Wght: minValStake, - }, - Subnet: constants.PrimaryNetworkID, + var ( + env = e2e.GetEnv(tc) + + nodeURI = env.GetRandomNodeURI() + keychain = env.NewKeychain(2) + + rewardAddr = keychain.Keys[0].Address() + rewardOwner = &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{rewardAddr}, } - rewardOwner := &secp256k1fx.OutputOwners{ + + transferAddr = keychain.Keys[1].Address() + transferOwner = secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{pShortAddr}, + Addrs: []ids.ShortID{transferAddr}, } - shares := uint32(20000) // TODO: retrieve programmatically + baseWallet = e2e.NewWallet(tc, keychain, nodeURI) + + pWallet = baseWallet.P() + pBuilder = pWallet.Builder() + pContext = pBuilder.Context() + + xWallet = baseWallet.X() + xBuilder = xWallet.Builder() + xContext = xBuilder.Context() + + avaxAssetID = pContext.AVAXAssetID + ) + + tc.Outf("{{blue}} fetching minimal stake amounts {{/}}\n") + pChainClient := platformvm.NewClient(nodeURI.URI) + minValStake, minDelStake, err := pChainClient.GetMinStake( + tc.DefaultContext(), + constants.PlatformChainID, + ) + require.NoError(err) + tc.Outf("{{green}} minimal validator stake: %d {{/}}\n", minValStake) + tc.Outf("{{green}} minimal delegator stake: %d {{/}}\n", minDelStake) + + // Use a random node ID to ensure that repeated test runs will succeed + // against a network that persists across runs. + validatorID, err := ids.ToNodeID(utils.RandomBytes(ids.NodeIDLen)) + require.NoError(err) + + vdr := &txs.SubnetValidator{ + Validator: txs.Validator{ + NodeID: validatorID, + End: uint64(time.Now().Add(72 * time.Hour).Unix()), + Wght: minValStake, + }, + Subnet: constants.PrimaryNetworkID, + } + + tc.By("issuing an AddPermissionlessValidatorTx", func() { sk, err := bls.NewSecretKey() require.NoError(err) pop := signer.NewProofOfPossession(sk) - tc.By("issue add validator tx", func() { - _, err := pWallet.IssueAddPermissionlessValidatorTx( - vdr, - pop, - avaxAssetID, - rewardOwner, - rewardOwner, - shares, - tc.WithDefaultContext(), - ) - require.NoError(err) - }) - - tc.By("issue add delegator tx", func() { - _, err := pWallet.IssueAddPermissionlessDelegatorTx( - vdr, - avaxAssetID, - rewardOwner, - tc.WithDefaultContext(), - ) - require.NoError(err) - }) - - // retrieve initial balances - pBalances, err := pWallet.Builder().GetBalance() + _, err = pWallet.IssueAddPermissionlessValidatorTx( + vdr, + pop, + avaxAssetID, + rewardOwner, + rewardOwner, + delegationFeeShares, + tc.WithDefaultContext(), + ) require.NoError(err) - pStartBalance := pBalances[avaxAssetID] - tc.Outf("{{blue}} P-chain balance before P->X export: %d {{/}}\n", pStartBalance) + }) - xBalances, err := xWallet.Builder().GetFTBalance() + tc.By("issuing an AddPermissionlessDelegatorTx", func() { + _, err := pWallet.IssueAddPermissionlessDelegatorTx( + vdr, + avaxAssetID, + rewardOwner, + tc.WithDefaultContext(), + ) require.NoError(err) - xStartBalance := xBalances[avaxAssetID] - tc.Outf("{{blue}} X-chain balance before P->X export: %d {{/}}\n", xStartBalance) + }) - outputOwner := secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ - xTargetAddr, - }, - } - output := &secp256k1fx.TransferOutput{ - Amt: toTransfer, - OutputOwners: outputOwner, - } + tc.By("issuing an ExportTx on the P-chain", func() { + balances, err := pBuilder.GetBalance() + require.NoError(err) + + initialAVAXBalance := balances[avaxAssetID] + tc.Outf("{{blue}} P-chain balance before P->X export: %d {{/}}\n", initialAVAXBalance) - tc.By("export avax from P to X chain", func() { - _, err := pWallet.IssueExportTx( - xContext.BlockchainID, - []*avax.TransferableOutput{ - { - Asset: avax.Asset{ - ID: avaxAssetID, - }, - Out: output, + _, err = pWallet.IssueExportTx( + xContext.BlockchainID, + []*avax.TransferableOutput{ + { + Asset: avax.Asset{ + ID: avaxAssetID, + }, + Out: &secp256k1fx.TransferOutput{ + Amt: toTransfer, + OutputOwners: transferOwner, }, }, - tc.WithDefaultContext(), - ) - require.NoError(err) - }) + }, + tc.WithDefaultContext(), + ) + require.NoError(err) - // check balances post export - pBalances, err = pWallet.Builder().GetBalance() + balances, err = pBuilder.GetBalance() require.NoError(err) - pPreImportBalance := pBalances[avaxAssetID] - tc.Outf("{{blue}} P-chain balance after P->X export: %d {{/}}\n", pPreImportBalance) - xBalances, err = xWallet.Builder().GetFTBalance() + finalAVAXBalance := balances[avaxAssetID] + tc.Outf("{{blue}} P-chain balance after P->X export: %d {{/}}\n", finalAVAXBalance) + + require.Equal(initialAVAXBalance-toTransfer-pContext.StaticFeeConfig.TxFee, finalAVAXBalance) + }) + + tc.By("issuing an ImportTx on the X-Chain", func() { + balances, err := xBuilder.GetFTBalance() require.NoError(err) - xPreImportBalance := xBalances[avaxAssetID] - tc.Outf("{{blue}} X-chain balance after P->X export: %d {{/}}\n", xPreImportBalance) - - require.Equal(xPreImportBalance, xStartBalance) // import not performed yet - require.Equal(pPreImportBalance, pStartBalance-toTransfer-txFees) - - tc.By("import avax from P into X chain", func() { - _, err := xWallet.IssueImportTx( - constants.PlatformChainID, - &outputOwner, - tc.WithDefaultContext(), - ) - require.NoError(err) - }) - - // check balances post import - pBalances, err = pWallet.Builder().GetBalance() + + initialAVAXBalance := balances[avaxAssetID] + tc.Outf("{{blue}} X-chain balance before P->X import: %d {{/}}\n", initialAVAXBalance) + + _, err = xWallet.IssueImportTx( + constants.PlatformChainID, + &transferOwner, + tc.WithDefaultContext(), + ) require.NoError(err) - pFinalBalance := pBalances[avaxAssetID] - tc.Outf("{{blue}} P-chain balance after P->X import: %d {{/}}\n", pFinalBalance) - xBalances, err = xWallet.Builder().GetFTBalance() + balances, err = xBuilder.GetFTBalance() require.NoError(err) - xFinalBalance := xBalances[avaxAssetID] - tc.Outf("{{blue}} X-chain balance after P->X import: %d {{/}}\n", xFinalBalance) - require.Equal(xFinalBalance, xPreImportBalance+toTransfer-txFees) // import not performed yet - require.Equal(pFinalBalance, pPreImportBalance) + finalAVAXBalance := balances[avaxAssetID] + tc.Outf("{{blue}} X-chain balance after P->X import: %d {{/}}\n", finalAVAXBalance) + + require.Equal(initialAVAXBalance+toTransfer-xContext.BaseTxFee, finalAVAXBalance) }) + }) }) diff --git a/tests/e2e/vms/xsvm.go b/tests/e2e/vms/xsvm.go index 562df5edb014..22add7550b5d 100644 --- a/tests/e2e/vms/xsvm.go +++ b/tests/e2e/vms/xsvm.go @@ -74,8 +74,7 @@ var _ = ginkgo.Describe("[XSVM]", func() { destinationAPINode := destinationValidators[0] tc.Outf(" issuing transactions for destination subnet on %s (%s)\n", destinationAPINode.NodeID, destinationAPINode.URI) - destinationKey, err := secp256k1.NewPrivateKey() - require.NoError(err) + destinationKey := e2e.NewPrivateKey(tc) tc.By("checking that the funded key has sufficient funds for the export") sourceClient := api.NewClient(sourceAPINode.URI, sourceChain.ChainID.String()) @@ -115,8 +114,7 @@ var _ = ginkgo.Describe("[XSVM]", func() { tc.By(fmt.Sprintf("issuing transaction on chain %s on subnet %s to activate snowman++ consensus", destinationChain.ChainID, destinationSubnet.SubnetID)) - recipientKey, err := secp256k1.NewPrivateKey() - require.NoError(err) + recipientKey := e2e.NewPrivateKey(tc) transferTxStatus, err := transfer.Transfer( tc.DefaultContext(), &transfer.Config{ diff --git a/tests/e2e/x/interchain_workflow.go b/tests/e2e/x/interchain_workflow.go index 3d5933ab54e7..6918a56ebe64 100644 --- a/tests/e2e/x/interchain_workflow.go +++ b/tests/e2e/x/interchain_workflow.go @@ -12,7 +12,6 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" @@ -34,8 +33,7 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL nodeURI := env.GetRandomNodeURI() tc.By("creating wallet with a funded key to send from and recipient key to deliver to") - recipientKey, err := secp256k1.NewPrivateKey() - require.NoError(err) + recipientKey := e2e.NewPrivateKey(tc) keychain := env.NewKeychain(1) keychain.Add(recipientKey) baseWallet := e2e.NewWallet(tc, keychain, nodeURI) @@ -76,7 +74,7 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL } tc.By("sending funds from one address to another on the X-Chain", func() { - _, err = xWallet.IssueBaseTx( + _, err := xWallet.IssueBaseTx( []*avax.TransferableOutput{{ Asset: avax.Asset{ ID: avaxAssetID, diff --git a/tests/fixture/e2e/helpers.go b/tests/fixture/e2e/helpers.go index 18de668fcbfa..571322fe4523 100644 --- a/tests/fixture/e2e/helpers.go +++ b/tests/fixture/e2e/helpers.go @@ -21,6 +21,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/tests" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" + "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" @@ -49,6 +50,13 @@ const ( PrivateNetworksDirName = "private_networks" ) +// NewPrivateKey returns a new private key. +func NewPrivateKey(tc tests.TestContext) *secp256k1.PrivateKey { + key, err := secp256k1.NewPrivateKey() + require.NoError(tc, err) + return key +} + // Create a new wallet for the provided keychain against the specified node URI. func NewWallet(tc tests.TestContext, keychain *secp256k1fx.Keychain, nodeURI tmpnet.NodeURI) primary.Wallet { tc.Outf("{{blue}} initializing a new wallet for node %s with URI: %s {{/}}\n", nodeURI.NodeID, nodeURI.URI) From 35b58d0d2766ce724b3913da2b921a22b923a8a1 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Wed, 14 Aug 2024 23:16:05 -0400 Subject: [PATCH 16/69] Fix e2e tests to support dynamic fees (#3296) --- tests/e2e/p/staking_rewards.go | 10 ++-------- tests/e2e/p/workflow.go | 14 +++++++++----- tests/fixture/e2e/helpers.go | 11 +++++++++++ 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/tests/e2e/p/staking_rewards.go b/tests/e2e/p/staking_rewards.go index 6f25531fa8a3..049f9ee14e35 100644 --- a/tests/e2e/p/staking_rewards.go +++ b/tests/e2e/p/staking_rewards.go @@ -94,14 +94,8 @@ var _ = ginkgo.Describe("[Staking Rewards]", func() { deltaDelegationRewardKey, } - keychain = secp256k1fx.NewKeychain(rewardKeys...) - ) - - fundedKey := env.AllocatePreFundedKey() - keychain.Add(fundedKey) - - var ( - nodeURI = tmpnet.NodeURI{ + keychain = env.NewKeychain(1) + nodeURI = tmpnet.NodeURI{ NodeID: alphaNodeID, URI: alphaNode.URI, } diff --git a/tests/e2e/p/workflow.go b/tests/e2e/p/workflow.go index 243e7efc4451..333b0c013705 100644 --- a/tests/e2e/p/workflow.go +++ b/tests/e2e/p/workflow.go @@ -62,9 +62,10 @@ var _ = e2e.DescribePChain("[Workflow]", func() { baseWallet = e2e.NewWallet(tc, keychain, nodeURI) - pWallet = baseWallet.P() - pBuilder = pWallet.Builder() - pContext = pBuilder.Context() + pWallet = baseWallet.P() + pBuilder = pWallet.Builder() + pContext = pBuilder.Context() + pFeeCalculator = e2e.NewPChainFeeCalculatorFromContext(pContext) xWallet = baseWallet.X() xBuilder = xWallet.Builder() @@ -131,7 +132,7 @@ var _ = e2e.DescribePChain("[Workflow]", func() { initialAVAXBalance := balances[avaxAssetID] tc.Outf("{{blue}} P-chain balance before P->X export: %d {{/}}\n", initialAVAXBalance) - _, err = pWallet.IssueExportTx( + exportTx, err := pWallet.IssueExportTx( xContext.BlockchainID, []*avax.TransferableOutput{ { @@ -148,13 +149,16 @@ var _ = e2e.DescribePChain("[Workflow]", func() { ) require.NoError(err) + exportFee, err := pFeeCalculator.CalculateFee(exportTx.Unsigned) + require.NoError(err) + balances, err = pBuilder.GetBalance() require.NoError(err) finalAVAXBalance := balances[avaxAssetID] tc.Outf("{{blue}} P-chain balance after P->X export: %d {{/}}\n", finalAVAXBalance) - require.Equal(initialAVAXBalance-toTransfer-pContext.StaticFeeConfig.TxFee, finalAVAXBalance) + require.Equal(initialAVAXBalance-toTransfer-exportFee, finalAVAXBalance) }) tc.By("issuing an ImportTx on the X-Chain", func() { diff --git a/tests/fixture/e2e/helpers.go b/tests/fixture/e2e/helpers.go index 571322fe4523..d0e9bf23399b 100644 --- a/tests/fixture/e2e/helpers.go +++ b/tests/fixture/e2e/helpers.go @@ -22,7 +22,9 @@ import ( "github.com/ava-labs/avalanchego/tests" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/wallet/chain/p/builder" "github.com/ava-labs/avalanchego/wallet/subnet/primary" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) @@ -242,3 +244,12 @@ func StartNetwork( require.NoError(network.Stop(ctx)) }) } + +// NewPChainFeeCalculatorFromContext returns either a static or dynamic fee +// calculator depending on the provided context. +func NewPChainFeeCalculatorFromContext(context *builder.Context) fee.Calculator { + if context.GasPrice != 0 { + return fee.NewDynamicCalculator(context.ComplexityWeights, context.GasPrice) + } + return fee.NewStaticCalculator(context.StaticFeeConfig) +} From 9a2aa856fd8900a14fbeb8f487df01b641f6caac Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 15 Aug 2024 05:53:56 -0400 Subject: [PATCH 17/69] Improve error message of dynamic fee calculations (#3297) --- vms/platformvm/txs/fee/dynamic_calculator.go | 33 +++++++++++++++++--- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/vms/platformvm/txs/fee/dynamic_calculator.go b/vms/platformvm/txs/fee/dynamic_calculator.go index 1cd385dafb9b..6754e5c85ae2 100644 --- a/vms/platformvm/txs/fee/dynamic_calculator.go +++ b/vms/platformvm/txs/fee/dynamic_calculator.go @@ -4,11 +4,20 @@ package fee import ( + "errors" + "fmt" + "github.com/ava-labs/avalanchego/vms/components/fee" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) -var _ Calculator = (*dynamicCalculator)(nil) +var ( + _ Calculator = (*dynamicCalculator)(nil) + + ErrCalculatingComplexity = errors.New("error calculating complexity") + ErrCalculatingGas = errors.New("error calculating gas") + ErrCalculatingCost = errors.New("error calculating cost") +) func NewDynamicCalculator( weights fee.Dimensions, @@ -28,11 +37,27 @@ type dynamicCalculator struct { func (c *dynamicCalculator) CalculateFee(tx txs.UnsignedTx) (uint64, error) { complexity, err := TxComplexity(tx) if err != nil { - return 0, err + return 0, fmt.Errorf("%w: %w", ErrCalculatingComplexity, err) } gas, err := complexity.ToGas(c.weights) if err != nil { - return 0, err + return 0, fmt.Errorf( + "%w with complexity (%v) and weights (%v): %w", + ErrCalculatingGas, + complexity, + c.weights, + err, + ) + } + fee, err := gas.Cost(c.price) + if err != nil { + return 0, fmt.Errorf( + "%w with gas (%d) and price (%d): %w", + ErrCalculatingCost, + gas, + c.price, + err, + ) } - return gas.Cost(c.price) + return fee, nil } From 50b8d65f445a576219cb45bb19b66a2179c3296d Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 15 Aug 2024 05:55:38 -0400 Subject: [PATCH 18/69] Reduce dynamic fees variability to ease testing (#3298) --- genesis/genesis_fuji.go | 2 +- genesis/genesis_local.go | 2 +- genesis/genesis_mainnet.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/genesis/genesis_fuji.go b/genesis/genesis_fuji.go index c47e691cc3f2..a267765e03ae 100644 --- a/genesis/genesis_fuji.go +++ b/genesis/genesis_fuji.go @@ -45,7 +45,7 @@ var ( MaxGasPerSecond: 1_000, TargetGasPerSecond: 500, MinGasPrice: 1, - ExcessConversionConstant: 1, + ExcessConversionConstant: 5_000, }, }, StakingConfig: StakingConfig{ diff --git a/genesis/genesis_local.go b/genesis/genesis_local.go index 095e664d249a..f5bbf5c4c7b7 100644 --- a/genesis/genesis_local.go +++ b/genesis/genesis_local.go @@ -63,7 +63,7 @@ var ( MaxGasPerSecond: 1_000, TargetGasPerSecond: 500, MinGasPrice: 1, - ExcessConversionConstant: 1, + ExcessConversionConstant: 5_000, }, }, StakingConfig: StakingConfig{ diff --git a/genesis/genesis_mainnet.go b/genesis/genesis_mainnet.go index e0e7228bb150..790a8e007630 100644 --- a/genesis/genesis_mainnet.go +++ b/genesis/genesis_mainnet.go @@ -45,7 +45,7 @@ var ( MaxGasPerSecond: 1_000, TargetGasPerSecond: 500, MinGasPrice: 1, - ExcessConversionConstant: 1, + ExcessConversionConstant: 5_000, }, }, StakingConfig: StakingConfig{ From 9e77ecc0003dd29439715905f3f113863cb7ae76 Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Thu, 15 Aug 2024 17:10:27 +0300 Subject: [PATCH 19/69] deprecate uptime apis (#3226) Co-authored-by: Alberto Benegiamo Co-authored-by: Stephen Buttolph --- api/info/service.go | 18 ++++++++++----- api/info/service.md | 4 ++-- network/metrics.go | 11 +++++----- network/peer/info.go | 2 +- proto/p2p/p2p.proto | 2 +- proto/pb/p2p/p2p.pb.go | 2 +- vms/platformvm/api/static_service.go | 22 +++++++++++-------- .../client_permissionless_validator.go | 10 ++++++--- vms/platformvm/service.md | 8 +++---- 9 files changed, 47 insertions(+), 32 deletions(-) diff --git a/api/info/service.go b/api/info/service.go index 86ed20bccaaa..4958e3cf9b48 100644 --- a/api/info/service.go +++ b/api/info/service.go @@ -314,15 +314,23 @@ type UptimeResponse struct { } type UptimeRequest struct { - // if omitted, defaults to primary network + // Deprecated: SubnetID in UptimeRequest is deprecated. + // Uptime API will be available only for Primary Network Validators. SubnetID ids.ID `json:"subnetID"` } func (i *Info) Uptime(_ *http.Request, args *UptimeRequest, reply *UptimeResponse) error { - i.log.Debug("API called", - zap.String("service", "info"), - zap.String("method", "uptime"), - ) + if args.SubnetID != constants.PrimaryNetworkID { + i.log.Warn("Deprecated API called", + zap.String("service", "info"), + zap.String("method", "uptime"), + ) + } else { + i.log.Debug("API called", + zap.String("service", "info"), + zap.String("method", "uptime"), + ) + } result, err := i.networking.NodeUptime(args.SubnetID) if err != nil { diff --git a/api/info/service.md b/api/info/service.md index d7e70e269dff..49479802430b 100644 --- a/api/info/service.md +++ b/api/info/service.md @@ -542,7 +542,7 @@ info.peers({ - `lastReceived` is the timestamp of last message received from the peer. - `benched` shows chain IDs that the peer is being benched. - `observedUptime` is this node's primary network uptime, observed by the peer. -- `observedSubnetUptime` is a map of Subnet IDs to this node's Subnet uptimes, observed by the peer. +- `observedSubnetUptime` (Deprecated) is a map of Subnet IDs to this node's Subnet uptimes, observed by the peer. **Example Call:** @@ -632,7 +632,7 @@ info.uptime({ } ``` -- `subnetID` is the Subnet to get the uptime of. If not provided, returns the uptime of the node on +- `subnetID` (Deprecated) is the Subnet to get the uptime of. If not provided, returns the uptime of the node on the primary network. - `rewardingStakePercentage` is the percent of stake which thinks this node is above the uptime diff --git a/network/metrics.go b/network/metrics.go index 9702e821b246..a4b333e6daea 100644 --- a/network/metrics.go +++ b/network/metrics.go @@ -34,13 +34,12 @@ type metrics struct { numUselessPeerListBytes prometheus.Counter nodeUptimeWeightedAverage prometheus.Gauge nodeUptimeRewardingStake prometheus.Gauge - nodeSubnetUptimeWeightedAverage *prometheus.GaugeVec - nodeSubnetUptimeRewardingStake *prometheus.GaugeVec + nodeSubnetUptimeWeightedAverage *prometheus.GaugeVec // Deprecated + nodeSubnetUptimeRewardingStake *prometheus.GaugeVec // Deprecated peerConnectedLifetimeAverage prometheus.Gauge - - lock sync.RWMutex - peerConnectedStartTimes map[ids.NodeID]float64 - peerConnectedStartTimesSum float64 + lock sync.RWMutex + peerConnectedStartTimes map[ids.NodeID]float64 + peerConnectedStartTimesSum float64 } func newMetrics( diff --git a/network/peer/info.go b/network/peer/info.go index 928c47ff26ee..843abc4c96fe 100644 --- a/network/peer/info.go +++ b/network/peer/info.go @@ -20,7 +20,7 @@ type Info struct { LastSent time.Time `json:"lastSent"` LastReceived time.Time `json:"lastReceived"` ObservedUptime json.Uint32 `json:"observedUptime"` - ObservedSubnetUptimes map[ids.ID]json.Uint32 `json:"observedSubnetUptimes"` + ObservedSubnetUptimes map[ids.ID]json.Uint32 `json:"observedSubnetUptimes"` // Deprecated TrackedSubnets set.Set[ids.ID] `json:"trackedSubnets"` SupportedACPs set.Set[uint32] `json:"supportedACPs"` ObjectedACPs set.Set[uint32] `json:"objectedACPs"` diff --git a/proto/p2p/p2p.proto b/proto/p2p/p2p.proto index 221a037f524f..7935ef6e44a5 100644 --- a/proto/p2p/p2p.proto +++ b/proto/p2p/p2p.proto @@ -64,7 +64,7 @@ message Message { message Ping { // Uptime percentage on the primary network [0, 100] uint32 uptime = 1; - // Uptime percentage on subnets + // Deprecated repeated SubnetUptime subnet_uptimes = 2; } diff --git a/proto/pb/p2p/p2p.pb.go b/proto/pb/p2p/p2p.pb.go index 5ca017be18bf..df754b0e2d74 100644 --- a/proto/pb/p2p/p2p.pb.go +++ b/proto/pb/p2p/p2p.pb.go @@ -498,7 +498,7 @@ type Ping struct { // Uptime percentage on the primary network [0, 100] Uptime uint32 `protobuf:"varint,1,opt,name=uptime,proto3" json:"uptime,omitempty"` - // Uptime percentage on subnets + // Deprecated SubnetUptimes []*SubnetUptime `protobuf:"bytes,2,rep,name=subnet_uptimes,json=subnetUptimes,proto3" json:"subnet_uptimes,omitempty"` } diff --git a/vms/platformvm/api/static_service.go b/vms/platformvm/api/static_service.go index 418b447114c7..46f02bd46ba9 100644 --- a/vms/platformvm/api/static_service.go +++ b/vms/platformvm/api/static_service.go @@ -115,15 +115,19 @@ type PermissionlessValidator struct { ValidationRewardOwner *Owner `json:"validationRewardOwner,omitempty"` // The owner of the rewards from delegations during the validation period, // if applicable. - DelegationRewardOwner *Owner `json:"delegationRewardOwner,omitempty"` - PotentialReward *json.Uint64 `json:"potentialReward,omitempty"` - AccruedDelegateeReward *json.Uint64 `json:"accruedDelegateeReward,omitempty"` - DelegationFee json.Float32 `json:"delegationFee"` - ExactDelegationFee *json.Uint32 `json:"exactDelegationFee,omitempty"` - Uptime *json.Float32 `json:"uptime,omitempty"` - Connected bool `json:"connected"` - Staked []UTXO `json:"staked,omitempty"` - Signer *signer.ProofOfPossession `json:"signer,omitempty"` + DelegationRewardOwner *Owner `json:"delegationRewardOwner,omitempty"` + PotentialReward *json.Uint64 `json:"potentialReward,omitempty"` + AccruedDelegateeReward *json.Uint64 `json:"accruedDelegateeReward,omitempty"` + DelegationFee json.Float32 `json:"delegationFee"` + ExactDelegationFee *json.Uint32 `json:"exactDelegationFee,omitempty"` + // Uptime is deprecated for Subnet Validators. + // It will be available only for Primary Network Validators. + Uptime *json.Float32 `json:"uptime,omitempty"` + // Connected is deprecated for Subnet Validators. + // It will be available only for Primary Network Validators. + Connected bool `json:"connected"` + Staked []UTXO `json:"staked,omitempty"` + Signer *signer.ProofOfPossession `json:"signer,omitempty"` // The delegators delegating to this validator DelegatorCount *json.Uint64 `json:"delegatorCount,omitempty"` diff --git a/vms/platformvm/client_permissionless_validator.go b/vms/platformvm/client_permissionless_validator.go index 3974f770658d..b2e48b0cce2a 100644 --- a/vms/platformvm/client_permissionless_validator.go +++ b/vms/platformvm/client_permissionless_validator.go @@ -44,9 +44,13 @@ type ClientPermissionlessValidator struct { PotentialReward *uint64 AccruedDelegateeReward *uint64 DelegationFee float32 - Uptime *float32 - Connected *bool - Signer *signer.ProofOfPossession + // Uptime is deprecated for Subnet Validators. + // It will be available only for Primary Network Validators. + Uptime *float32 + // Connected is deprecated for Subnet Validators. + // It will be available only for Primary Network Validators. + Connected *bool + Signer *signer.ProofOfPossession // The delegators delegating to this validator DelegatorCount *uint64 DelegatorWeight *uint64 diff --git a/vms/platformvm/service.md b/vms/platformvm/service.md index caa040103533..f4cd28cd35f1 100644 --- a/vms/platformvm/service.md +++ b/vms/platformvm/service.md @@ -696,8 +696,8 @@ platform.getCurrentValidators({ - `delegationFeeRate` is the percent fee this validator charges when others delegate stake to them. Omitted if `subnetID` is not a PoS Subnet. - `uptime` is the % of time the queried node has reported the peer as online and validating the - Subnet. Omitted if `subnetID` is not a PoS Subnet. - - `connected` is if the node is connected and tracks the Subnet. + Subnet. Omitted if `subnetID` is not a PoS Subnet. (Deprecated: uptime is deprecated for Subnet Validators. It will be available only for Primary Network Validators.) + - `connected` is if the node is connected and tracks the Subnet. (Deprecated: connected is deprecated for Subnet Validators. It will be available only for Primary Network Validators.) - `signer` is the node's BLS public key and proof of possession. Omitted if the validator doesn't have a BLS public key. - `delegatorCount` is the number of delegators on this validator. @@ -1222,11 +1222,11 @@ platform.getSubnet({ ``` - `subnetID` is the ID of the Subnet to get information about. If omitted, fails. -- `threshold` signatures from addresses in `controlKeys` are needed to make changes to +- `threshold` signatures from addresses in `controlKeys` are needed to make changes to a permissioned subnet. If the Subnet is a PoS Subnet, then `threshold` will be `0` and `controlKeys` will be empty. - changes can not be made into the subnet until `locktime` is in the past. -- `subnetTransformationTxID` is the ID of the transaction that changed the subnet into a elastic one, +- `subnetTransformationTxID` is the ID of the transaction that changed the subnet into a elastic one, for when this change was performed. **Example Call:** From aececb0df3cbac8adbcf52c7c330ce01f877b3d4 Mon Sep 17 00:00:00 2001 From: marun Date: Thu, 15 Aug 2024 09:51:38 -0700 Subject: [PATCH 20/69] [antithesis] Fix broken flag handling and improve image testing (#3299) --- .golangci.yml | 14 ++++---------- scripts/lib_test_antithesis_images.sh | 20 ++++++++++++-------- tests/antithesis/compose.go | 12 +++++------- tests/antithesis/config.go | 18 ++++++++++-------- 4 files changed, 31 insertions(+), 33 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index f7a313a1d596..8e70442cce97 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -170,16 +170,10 @@ linters-settings: disabled: false # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unhandled-error - name: unhandled-error - disabled: false - arguments: - - "fmt\\.Fprint" - - "fmt\\.Fprintf" - - "fmt\\.Fprintln" - - "fmt\\.Print" - - "fmt\\.Printf" - - "fmt\\.Println" - - "math/rand\\.Read" - - "strings\\.Builder\\.WriteString" + # prefer the errcheck linter since it can be disabled directly with nolint directive + # but revive's disable directive (e.g. //revive:disable:unhandled-error) is not + # supported when run under golangci_lint + disabled: true # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md#unused-parameter - name: unused-parameter disabled: false diff --git a/scripts/lib_test_antithesis_images.sh b/scripts/lib_test_antithesis_images.sh index eb01bbdcc810..6a6627f71890 100644 --- a/scripts/lib_test_antithesis_images.sh +++ b/scripts/lib_test_antithesis_images.sh @@ -46,13 +46,17 @@ docker cp "${CONTAINER_NAME}":/docker-compose.yml "${COMPOSE_FILE}" # Copy the volume paths out of the container docker cp "${CONTAINER_NAME}":/volumes "${TMPDIR}/" -# Run the docker compose project for 30 seconds without error. Local -# network bootstrap is ~6s, but github workers can be much slower. -${COMPOSE_CMD} up -d -sleep 30 -if ${COMPOSE_CMD} ps -q | xargs docker inspect -f '{{ .State.Status }}' | grep -v 'running'; then - echo "An error occurred." +# Wait for up to TIMEOUT for the workload to emit HEALTHY_MESSAGE to indicate that all nodes are +# reporting healthy. This indicates that the workload has been correctly configured. Subsequent +# validation will need to be tailored to a given workload implementation. + +TIMEOUT=30s +HEALTHY_MESSAGE="all nodes reported healthy" + +if timeout "${TIMEOUT}" bash -c "${COMPOSE_CMD} up 2>&1 | grep -m 1 '${HEALTHY_MESSAGE}'"; then + echo "Saw log containing '${HEALTHY_MESSAGE}'" + echo "Successfully invoked the antithesis test setup configured by ${IMAGE_NAME}:${IMAGE_TAG}" +else + echo "Failed to see log containing '${HEALTHY_MESSAGE}' within ${TIMEOUT}" exit 1 fi - -echo "Successfully invoked the antithesis test setup configured by ${IMAGE_NAME}:${IMAGE_TAG}" diff --git a/tests/antithesis/compose.go b/tests/antithesis/compose.go index 85ecf3952c3e..f11ac0288ea2 100644 --- a/tests/antithesis/compose.go +++ b/tests/antithesis/compose.go @@ -9,7 +9,6 @@ import ( "os" "path/filepath" "strconv" - "strings" "github.com/compose-spec/compose-go/types" "gopkg.in/yaml.v3" @@ -129,7 +128,7 @@ func newComposeProject(network *tmpnet.Network, nodeImageName string, workloadIm baseNetworkAddress := "10.0.20" services := make(types.Services, len(network.Nodes)+1) - uris := make([]string, len(network.Nodes)) + uris := make(CSV, len(network.Nodes)) var ( bootstrapIP string bootstrapIDs string @@ -230,16 +229,16 @@ func newComposeProject(network *tmpnet.Network, nodeImageName string, workloadIm } workloadEnv := types.Mapping{ - envVarName(URIsKey): strings.Join(uris, " "), + envVarName(EnvPrefix, URIsKey): uris.String(), } - chainIDs := []string{} + chainIDs := CSV{} for _, subnet := range network.Subnets { for _, chain := range subnet.Chains { chainIDs = append(chainIDs, chain.ChainID.String()) } } if len(chainIDs) > 0 { - workloadEnv[envVarName(ChainIDsKey)] = strings.Join(chainIDs, " ") + workloadEnv[envVarName(EnvPrefix, ChainIDsKey)] = chainIDs.String() } workloadName := "workload" @@ -277,8 +276,7 @@ func newComposeProject(network *tmpnet.Network, nodeImageName string, workloadIm func keyMapToEnvVarMap(keyMap types.Mapping) types.Mapping { envVarMap := make(types.Mapping, len(keyMap)) for key, val := range keyMap { - // e.g. network-id -> AVAGO_NETWORK_ID - envVar := strings.ToUpper(config.EnvPrefix + "_" + config.DashesToUnderscores.Replace(key)) + envVar := envVarName(config.EnvPrefix, key) envVarMap[envVar] = val } return envVarMap diff --git a/tests/antithesis/config.go b/tests/antithesis/config.go index 5d5ea03334d4..b7d006e769c5 100644 --- a/tests/antithesis/config.go +++ b/tests/antithesis/config.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/config" "github.com/ava-labs/avalanchego/tests" "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" @@ -54,15 +55,15 @@ func NewConfigWithSubnets(tc tests.TestContext, defaultNetwork *tmpnet.Network, flag.Parse() // Env vars take priority over flags - envURIs := os.Getenv(envVarName(URIsKey)) + envURIs := os.Getenv(envVarName(EnvPrefix, URIsKey)) if len(envURIs) > 0 { - // CSV.Set doesn't actually return an error - _ = uris.Set(envURIs) + //nolint:errcheck // CSV.Set doesn't actually return an error + uris.Set(envURIs) } - envChainIDs := os.Getenv(envVarName(ChainIDsKey)) + envChainIDs := os.Getenv(envVarName(EnvPrefix, ChainIDsKey)) if len(envChainIDs) > 0 { - // CSV.Set doesn't actually return an error - _ = uris.Set(envChainIDs) + //nolint:errcheck // CSV.Set doesn't actually return an error + chainIDs.Set(envChainIDs) } // Use the network configuration provided @@ -126,6 +127,7 @@ func (c *CSV) Set(value string) error { return nil } -func envVarName(key string) string { - return strings.ToUpper(EnvPrefix + "_" + key) +func envVarName(prefix string, key string) string { + // e.g. MY_PREFIX, network-id -> MY_PREFIX_NETWORK_ID + return strings.ToUpper(prefix + "_" + config.DashesToUnderscores.Replace(key)) } From 9a9244f1a5320c40c1514e293239249d1ff19f95 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 15 Aug 2024 14:00:09 -0400 Subject: [PATCH 21/69] Add P-chain fee APIs (#3286) --- vms/platformvm/client.go | 17 +++++++++ vms/platformvm/service.go | 43 ++++++++++++++++++++++ vms/platformvm/service_test.go | 65 ++++++++++++++++++++++++++++++++++ vms/platformvm/vm_test.go | 43 +++++++++++++++------- 4 files changed, 155 insertions(+), 13 deletions(-) diff --git a/vms/platformvm/client.go b/vms/platformvm/client.go index a631176f5e46..d8880d5b204e 100644 --- a/vms/platformvm/client.go +++ b/vms/platformvm/client.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/rpc" + "github.com/ava-labs/avalanchego/vms/components/fee" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -123,6 +124,10 @@ type Client interface { GetBlock(ctx context.Context, blockID ids.ID, options ...rpc.Option) ([]byte, error) // GetBlockByHeight returns the block at the given [height]. GetBlockByHeight(ctx context.Context, height uint64, options ...rpc.Option) ([]byte, error) + // GetFeeConfig returns the dynamic fee config of the chain. + GetFeeConfig(ctx context.Context, options ...rpc.Option) (*fee.Config, error) + // GetFeeState returns the current fee state of the chain. + GetFeeState(ctx context.Context, options ...rpc.Option) (fee.State, fee.GasPrice, time.Time, error) } // Client implementation for interacting with the P Chain endpoint @@ -517,6 +522,18 @@ func (c *client) GetBlockByHeight(ctx context.Context, height uint64, options .. return formatting.Decode(res.Encoding, res.Block) } +func (c *client) GetFeeConfig(ctx context.Context, options ...rpc.Option) (*fee.Config, error) { + res := &fee.Config{} + err := c.requester.SendRequest(ctx, "platform.getFeeConfig", struct{}{}, res, options...) + return res, err +} + +func (c *client) GetFeeState(ctx context.Context, options ...rpc.Option) (fee.State, fee.GasPrice, time.Time, error) { + res := &GetFeeStateReply{} + err := c.requester.SendRequest(ctx, "platform.getFeeState", struct{}{}, res, options...) + return res.State, res.Price, res.Time, err +} + func AwaitTxAccepted( c Client, ctx context.Context, diff --git a/vms/platformvm/service.go b/vms/platformvm/service.go index 0299192b6677..285fd530cc16 100644 --- a/vms/platformvm/service.go +++ b/vms/platformvm/service.go @@ -28,6 +28,7 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/components/fee" "github.com/ava-labs/avalanchego/vms/components/keystore" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/reward" @@ -1828,6 +1829,48 @@ func (s *Service) GetBlockByHeight(_ *http.Request, args *api.GetBlockByHeightAr return err } +// GetFeeConfig returns the dynamic fee config of the chain. +func (s *Service) GetFeeConfig(_ *http.Request, _ *struct{}, reply *fee.Config) error { + s.vm.ctx.Log.Debug("API called", + zap.String("service", "platform"), + zap.String("method", "getFeeConfig"), + ) + + // TODO: Remove after Etna is activated. + now := time.Now() + if !s.vm.Config.UpgradeConfig.IsEtnaActivated(now) { + return nil + } + + *reply = s.vm.DynamicFeeConfig + return nil +} + +type GetFeeStateReply struct { + fee.State + Price fee.GasPrice `json:"price"` + Time time.Time `json:"timestamp"` +} + +// GetFeeState returns the current fee state of the chain. +func (s *Service) GetFeeState(_ *http.Request, _ *struct{}, reply *GetFeeStateReply) error { + s.vm.ctx.Log.Debug("API called", + zap.String("service", "platform"), + zap.String("method", "getFeeState"), + ) + + s.vm.ctx.Lock.Lock() + defer s.vm.ctx.Lock.Unlock() + + reply.State = s.vm.state.GetFeeState() + reply.Price = s.vm.DynamicFeeConfig.MinGasPrice.MulExp( + reply.State.Excess, + s.vm.DynamicFeeConfig.ExcessConversionConstant, + ) + reply.Time = s.vm.state.GetTimestamp() + return nil +} + func (s *Service) getAPIUptime(staker *state.Staker) (*avajson.Float32, error) { // Only report uptimes that we have been actively tracking. if constants.PrimaryNetworkID != staker.SubnetID && !s.vm.TrackedSubnets.Contains(staker.SubnetID) { diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index a3b2e743c9bc..a1f429510538 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -33,6 +33,7 @@ import ( "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/components/fee" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -1107,3 +1108,67 @@ func TestServiceGetSubnets(t *testing.T) { }, }, response.Subnets) } + +func TestGetFeeConfig(t *testing.T) { + tests := []struct { + name string + etnaTime time.Time + expected fee.Config + }{ + { + name: "pre-etna", + etnaTime: time.Now().Add(time.Hour), + expected: fee.Config{}, + }, + { + name: "post-etna", + etnaTime: time.Now().Add(-time.Hour), + expected: defaultDynamicFeeConfig, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + service, _, _ := defaultService(t) + service.vm.Config.UpgradeConfig.EtnaTime = test.etnaTime + + var reply fee.Config + require.NoError(service.GetFeeConfig(nil, nil, &reply)) + require.Equal(test.expected, reply) + }) + } +} + +func FuzzGetFeeState(f *testing.F) { + f.Fuzz(func(t *testing.T, capacity, excess uint64) { + require := require.New(t) + + service, _, _ := defaultService(t) + + var ( + expectedState = fee.State{ + Capacity: fee.Gas(capacity), + Excess: fee.Gas(excess), + } + expectedTime = time.Now() + expectedReply = GetFeeStateReply{ + State: expectedState, + Price: defaultDynamicFeeConfig.MinGasPrice.MulExp( + expectedState.Excess, + defaultDynamicFeeConfig.ExcessConversionConstant, + ), + Time: expectedTime, + } + ) + + service.vm.ctx.Lock.Lock() + service.vm.state.SetFeeState(expectedState) + service.vm.state.SetTimestamp(expectedTime) + service.vm.ctx.Lock.Unlock() + + var reply GetFeeStateReply + require.NoError(service.GetFeeState(nil, nil, &reply)) + require.Equal(expectedReply, reply) + }) +} diff --git a/vms/platformvm/vm_test.go b/vms/platformvm/vm_test.go index 08d51ce4f135..939112c03242 100644 --- a/vms/platformvm/vm_test.go +++ b/vms/platformvm/vm_test.go @@ -59,7 +59,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -68,9 +67,11 @@ import ( smeng "github.com/ava-labs/avalanchego/snow/engine/snowman" snowgetter "github.com/ava-labs/avalanchego/snow/engine/snowman/getter" timetracker "github.com/ava-labs/avalanchego/snow/networking/tracker" + feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" blockbuilder "github.com/ava-labs/avalanchego/vms/platformvm/block/builder" blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" + txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" walletbuilder "github.com/ava-labs/avalanchego/wallet/chain/p/builder" walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" @@ -123,6 +124,26 @@ var ( defaultMaxValidatorStake = 100 * defaultMinValidatorStake defaultBalance = 2 * defaultMaxValidatorStake // amount all genesis validators have in defaultVM + defaultStaticFeeConfig = txfee.StaticConfig{ + TxFee: defaultTxFee, + CreateSubnetTxFee: 100 * defaultTxFee, + TransformSubnetTxFee: 100 * defaultTxFee, + CreateBlockchainTxFee: 100 * defaultTxFee, + } + defaultDynamicFeeConfig = feecomponent.Config{ + Weights: feecomponent.Dimensions{ + feecomponent.Bandwidth: 1, + feecomponent.DBRead: 1, + feecomponent.DBWrite: 1, + feecomponent.Compute: 1, + }, + MaxGasCapacity: 10_000, + MaxGasPerSecond: 1_000, + TargetGasPerSecond: 500, + MinGasPrice: 1, + ExcessConversionConstant: 5_000, + } + // subnet that exists at genesis in defaultVM // Its controlKeys are keys[0], keys[1], keys[2] // Its threshold is 2 @@ -248,18 +269,14 @@ func defaultVM(t *testing.T, f fork) (*VM, *txstest.WalletFactory, database.Data UptimeLockedCalculator: uptime.NewLockedCalculator(), SybilProtectionEnabled: true, Validators: validators.NewManager(), - StaticFeeConfig: fee.StaticConfig{ - TxFee: defaultTxFee, - CreateSubnetTxFee: 100 * defaultTxFee, - TransformSubnetTxFee: 100 * defaultTxFee, - CreateBlockchainTxFee: 100 * defaultTxFee, - }, - MinValidatorStake: defaultMinValidatorStake, - MaxValidatorStake: defaultMaxValidatorStake, - MinDelegatorStake: defaultMinDelegatorStake, - MinStakeDuration: defaultMinStakingDuration, - MaxStakeDuration: defaultMaxStakingDuration, - RewardConfig: defaultRewardConfig, + StaticFeeConfig: defaultStaticFeeConfig, + DynamicFeeConfig: defaultDynamicFeeConfig, + MinValidatorStake: defaultMinValidatorStake, + MaxValidatorStake: defaultMaxValidatorStake, + MinDelegatorStake: defaultMinDelegatorStake, + MinStakeDuration: defaultMinStakingDuration, + MaxStakeDuration: defaultMaxStakingDuration, + RewardConfig: defaultRewardConfig, UpgradeConfig: upgrade.Config{ ApricotPhase3Time: apricotPhase3Time, ApricotPhase5Time: apricotPhase5Time, From d7d534509e32f0052bcad9944d03ee5f7c2f620c Mon Sep 17 00:00:00 2001 From: marun Date: Thu, 15 Aug 2024 11:08:38 -0700 Subject: [PATCH 22/69] [tmpnet] Add support for checking rpcchainvm version compatibility (#3276) --- tests/fixture/subnet/xsvm.go | 1 + tests/fixture/tmpnet/README.md | 11 +++-- tests/fixture/tmpnet/network.go | 66 +++++++++++++++++++++++-- tests/fixture/tmpnet/subnet.go | 6 +++ vms/example/xsvm/README.md | 1 + vms/example/xsvm/cmd/versionjson/cmd.go | 46 +++++++++++++++++ vms/example/xsvm/cmd/xsvm/main.go | 2 + 7 files changed, 126 insertions(+), 7 deletions(-) create mode 100644 vms/example/xsvm/cmd/versionjson/cmd.go diff --git a/tests/fixture/subnet/xsvm.go b/tests/fixture/subnet/xsvm.go index c5bb03bc2026..5bc6903511eb 100644 --- a/tests/fixture/subnet/xsvm.go +++ b/tests/fixture/subnet/xsvm.go @@ -38,6 +38,7 @@ func NewXSVMOrPanic(name string, key *secp256k1.PrivateKey, nodes ...*tmpnet.Nod VMID: constants.XSVMID, Genesis: genesisBytes, PreFundedKey: key, + VersionArgs: []string{"version-json"}, }, }, ValidatorIDs: tmpnet.NodesToIDs(nodes...), diff --git a/tests/fixture/tmpnet/README.md b/tests/fixture/tmpnet/README.md index b059da9a554d..3f84e5c3acd7 100644 --- a/tests/fixture/tmpnet/README.md +++ b/tests/fixture/tmpnet/README.md @@ -93,9 +93,14 @@ network := &tmpnet.Network{ // Configure non-default values fo Name: "xsvm-a", // User-defined name used to reference subnet in code and on disk Chains: []*tmpnet.Chain{ { - VMName: "xsvm", // Name of the VM the chain will run, will be used to derive the name of the VM binary - Genesis: , // Genesis bytes used to initialize the custom chain - PreFundedKey: , // (Optional) A private key that is funded in the genesis bytes + VMName: "xsvm", // Name of the VM the chain will run, will be used to derive the name of the VM binary + Genesis: , // Genesis bytes used to initialize the custom chain + PreFundedKey: , // (Optional) A private key that is funded in the genesis bytes + VersionArgs: "version-json", // (Optional) Arguments that prompt the VM binary to output version details in json format. + // If one or more arguments are provided, the resulting json output should include a field + // named `rpcchainvm` of type uint64 containing the rpc version supported by the VM binary. + // The version will be checked against the version reported by the configured avalanchego + // binary before network and node start. }, }, ValidatorIDs: , // The IDs of nodes that validate the subnet diff --git a/tests/fixture/tmpnet/network.go b/tests/fixture/tmpnet/network.go index 5e85c020386e..68b4a7173e00 100644 --- a/tests/fixture/tmpnet/network.go +++ b/tests/fixture/tmpnet/network.go @@ -6,10 +6,12 @@ package tmpnet import ( "context" "encoding/hex" + "encoding/json" "errors" "fmt" "io" "os" + "os/exec" "path/filepath" "slices" "strconv" @@ -141,7 +143,7 @@ func BootstrapNewNetwork( if len(network.Nodes) == 0 { return errInsufficientNodes } - if err := checkVMBinariesExist(network.Subnets, pluginDir); err != nil { + if err := checkVMBinaries(w, network.Subnets, avalancheGoExecPath, pluginDir); err != nil { return err } if err := network.EnsureDefaultConfig(w, avalancheGoExecPath, pluginDir); err != nil { @@ -465,11 +467,13 @@ func (n *Network) StartNode(ctx context.Context, w io.Writer, node *Node) error if err != nil { return err } - if err := checkVMBinariesExist(n.Subnets, pluginDir); err != nil { + + if err := n.EnsureNodeConfig(node); err != nil { return err } - if err := n.EnsureNodeConfig(node); err != nil { + // Check the VM binaries after EnsureNodeConfig to ensure node.RuntimeConfig is non-nil + if err := checkVMBinaries(w, n.Subnets, node.RuntimeConfig.AvalancheGoPath, pluginDir); err != nil { return err } @@ -939,15 +943,69 @@ func GetReusableNetworkPathForOwner(owner string) (string, error) { return filepath.Join(networkPath, "latest_"+owner), nil } -func checkVMBinariesExist(subnets []*Subnet, pluginDir string) error { +const invalidRPCVersion = 0 + +// checkVMBinaries checks that VM binaries for the given subnets exist and optionally checks that VM +// binaries have the same rpcchainvm version as the indicated avalanchego binary. +func checkVMBinaries(w io.Writer, subnets []*Subnet, avalanchegoPath string, pluginDir string) error { + if len(subnets) == 0 { + return nil + } + + expectedRPCVersion, err := getRPCVersion(avalanchegoPath, "--version-json") + if err != nil { + // Only warn if the rpc version is not available to ensure backwards compatibility. + if _, err := fmt.Fprintf(w, "Warning: Unable to check rpcchainvm version for avalanchego: %v\n", err); err != nil { + return err + } + } + errs := []error{} for _, subnet := range subnets { for _, chain := range subnet.Chains { pluginPath := filepath.Join(pluginDir, chain.VMID.String()) + + // Check that the path exists if _, err := os.Stat(pluginPath); err != nil { errs = append(errs, fmt.Errorf("failed to check VM binary for subnet %q: %w", subnet.Name, err)) } + + if len(chain.VersionArgs) == 0 || expectedRPCVersion == invalidRPCVersion { + // Not possible to check the rpcchainvm version + continue + } + + // Check that the VM's rpcchainvm version matches avalanchego's version + rpcVersion, err := getRPCVersion(pluginPath, chain.VersionArgs...) + if err != nil { + if _, err := fmt.Fprintf(w, "Warning: Unable to check rpcchainvm version for VM Binary for subnet %q: %v\n", subnet.Name, err); err != nil { + return err + } + } else if expectedRPCVersion != rpcVersion { + errs = append(errs, fmt.Errorf("unexpected rpcchainvm version for VM binary of subnet %q: %q reports %d, but %q reports %d", subnet.Name, avalanchegoPath, expectedRPCVersion, pluginPath, rpcVersion)) + } } } + return errors.Join(errs...) } + +type RPCChainVMVersion struct { + RPCChainVM uint64 `json:"rpcchainvm"` +} + +// getRPCVersion attempts to invoke the given command with the specified version arguments and +// retrieve an rpcchainvm version from its output. +func getRPCVersion(command string, versionArgs ...string) (uint64, error) { + cmd := exec.Command(command, versionArgs...) + output, err := cmd.CombinedOutput() + if err != nil { + return 0, fmt.Errorf("command %q failed with output: %s", command, output) + } + version := &RPCChainVMVersion{} + if err := json.Unmarshal(output, version); err != nil { + return 0, fmt.Errorf("failed to unmarshal output from command %q: %w, output: %s", command, err, output) + } + + return version.RPCChainVM, nil +} diff --git a/tests/fixture/tmpnet/subnet.go b/tests/fixture/tmpnet/subnet.go index fd021facd172..a9062f2fb5cc 100644 --- a/tests/fixture/tmpnet/subnet.go +++ b/tests/fixture/tmpnet/subnet.go @@ -36,6 +36,12 @@ type Chain struct { VMID ids.ID Config string Genesis []byte + // VersionArgs are the argument(s) to pass to the VM binary to receive + // version details in json format (e.g. `--version-json`). This + // supports checking that the rpcchainvm version of the VM binary + // matches the version used by the configured avalanchego binary. If + // empty, the version check will be skipped. + VersionArgs []string // Set at runtime ChainID ids.ID diff --git a/vms/example/xsvm/README.md b/vms/example/xsvm/README.md index 53548228a989..263894ae23d1 100644 --- a/vms/example/xsvm/README.md +++ b/vms/example/xsvm/README.md @@ -66,6 +66,7 @@ Available Commands: help Help about any command issue Issues transactions version Prints out the version + versionjson Prints out the version in json format Flags: -h, --help help for xsvm diff --git a/vms/example/xsvm/cmd/versionjson/cmd.go b/vms/example/xsvm/cmd/versionjson/cmd.go new file mode 100644 index 000000000000..077215f3016c --- /dev/null +++ b/vms/example/xsvm/cmd/versionjson/cmd.go @@ -0,0 +1,46 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package versionjson + +import ( + "encoding/json" + "fmt" + + "github.com/spf13/cobra" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/version" + "github.com/ava-labs/avalanchego/vms/example/xsvm" +) + +type vmVersions struct { + Name string `json:"name"` + VMID ids.ID `json:"vmid"` + Version *version.Semantic `json:"version"` + RPCChainVM uint64 `json:"rpcchainvm"` +} + +func Command() *cobra.Command { + return &cobra.Command{ + Use: "version-json", + Short: "Prints out the version in json format", + RunE: versionFunc, + } +} + +func versionFunc(*cobra.Command, []string) error { + versions := vmVersions{ + Name: constants.XSVMName, + VMID: constants.XSVMID, + Version: xsvm.Version, + RPCChainVM: uint64(version.RPCChainVMProtocol), + } + jsonBytes, err := json.MarshalIndent(versions, "", " ") + if err != nil { + return fmt.Errorf("failed to marshal versions: %w", err) + } + fmt.Println(string(jsonBytes)) + return nil +} diff --git a/vms/example/xsvm/cmd/xsvm/main.go b/vms/example/xsvm/cmd/xsvm/main.go index c6961a8c1741..b6d8796fd313 100644 --- a/vms/example/xsvm/cmd/xsvm/main.go +++ b/vms/example/xsvm/cmd/xsvm/main.go @@ -15,6 +15,7 @@ import ( "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/issue" "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/run" "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/version" + "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/versionjson" ) func init() { @@ -28,6 +29,7 @@ func main() { chain.Command(), issue.Command(), version.Command(), + versionjson.Command(), ) ctx := context.Background() if err := cmd.ExecuteContext(ctx); err != nil { From ce78e7f1799f16c3f05a88d2b36809175179dd70 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 15 Aug 2024 17:11:42 -0400 Subject: [PATCH 23/69] Rename gas price calculation function (#3302) --- vms/components/fee/gas.go | 12 +++++++++--- vms/components/fee/gas_test.go | 14 +++++++------- vms/platformvm/service.go | 3 ++- vms/platformvm/service_test.go | 3 ++- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/vms/components/fee/gas.go b/vms/components/fee/gas.go index a4e5312d3979..0c4a905ce783 100644 --- a/vms/components/fee/gas.go +++ b/vms/components/fee/gas.go @@ -55,7 +55,12 @@ func (g Gas) SubPerSecond(gasPerSecond Gas, seconds uint64) Gas { return Gas(totalGas) } -// MulExp returns an approximation of g * e^(excess / excessConversionConstant) +// CalculateGasPrice returns the gas price given the minimum gas price, the +// excess gas, and the excess conversion constant. +// +// It is defined as an approximation of: +// +// minPrice * e^(excess / excessConversionConstant) // // This implements the EIP-4844 fake exponential formula: // @@ -77,7 +82,8 @@ func (g Gas) SubPerSecond(gasPerSecond Gas, seconds uint64) Gas { // This function does not perform any memory allocations. // //nolint:dupword // The python is copied from the EIP-4844 specification -func (g GasPrice) MulExp( +func CalculateGasPrice( + minPrice GasPrice, excess Gas, excessConversionConstant Gas, ) GasPrice { @@ -95,7 +101,7 @@ func (g GasPrice) MulExp( denominator.SetUint64(uint64(excessConversionConstant)) // range is [0, MaxUint64] i.SetOne() - numeratorAccum.SetUint64(uint64(g)) // range is [0, MaxUint64] + numeratorAccum.SetUint64(uint64(minPrice)) // range is [0, MaxUint64] numeratorAccum.Mul(&numeratorAccum, &denominator) // range is [0, MaxUint128] maxOutput.Mul(&denominator, maxUint64) // range is [0, MaxUint128] diff --git a/vms/components/fee/gas_test.go b/vms/components/fee/gas_test.go index 5414194330b8..b9e2dc99edfe 100644 --- a/vms/components/fee/gas_test.go +++ b/vms/components/fee/gas_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -var gasPriceMulExpTests = []struct { +var calculateGasPriceTests = []struct { minPrice GasPrice excess Gas excessConversionConstant Gas @@ -172,20 +172,20 @@ func Test_Gas_SubPerSecond(t *testing.T) { } } -func Test_GasPrice_MulExp(t *testing.T) { - for _, test := range gasPriceMulExpTests { +func Test_CalculateGasPrice(t *testing.T) { + for _, test := range calculateGasPriceTests { t.Run(fmt.Sprintf("%d*e^(%d/%d)=%d", test.minPrice, test.excess, test.excessConversionConstant, test.expected), func(t *testing.T) { - actual := test.minPrice.MulExp(test.excess, test.excessConversionConstant) + actual := CalculateGasPrice(test.minPrice, test.excess, test.excessConversionConstant) require.Equal(t, test.expected, actual) }) } } -func Benchmark_GasPrice_MulExp(b *testing.B) { - for _, test := range gasPriceMulExpTests { +func Benchmark_CalculateGasPrice(b *testing.B) { + for _, test := range calculateGasPriceTests { b.Run(fmt.Sprintf("%d*e^(%d/%d)=%d", test.minPrice, test.excess, test.excessConversionConstant, test.expected), func(b *testing.B) { for i := 0; i < b.N; i++ { - test.minPrice.MulExp(test.excess, test.excessConversionConstant) + CalculateGasPrice(test.minPrice, test.excess, test.excessConversionConstant) } }) } diff --git a/vms/platformvm/service.go b/vms/platformvm/service.go index 285fd530cc16..600b03231f8f 100644 --- a/vms/platformvm/service.go +++ b/vms/platformvm/service.go @@ -1863,7 +1863,8 @@ func (s *Service) GetFeeState(_ *http.Request, _ *struct{}, reply *GetFeeStateRe defer s.vm.ctx.Lock.Unlock() reply.State = s.vm.state.GetFeeState() - reply.Price = s.vm.DynamicFeeConfig.MinGasPrice.MulExp( + reply.Price = fee.CalculateGasPrice( + s.vm.DynamicFeeConfig.MinGasPrice, reply.State.Excess, s.vm.DynamicFeeConfig.ExcessConversionConstant, ) diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index a1f429510538..f8335a621e07 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -1154,7 +1154,8 @@ func FuzzGetFeeState(f *testing.F) { expectedTime = time.Now() expectedReply = GetFeeStateReply{ State: expectedState, - Price: defaultDynamicFeeConfig.MinGasPrice.MulExp( + Price: fee.CalculateGasPrice( + defaultDynamicFeeConfig.MinGasPrice, expectedState.Excess, defaultDynamicFeeConfig.ExcessConversionConstant, ), From 4b4ec8a54a3024b8ec94d87706803d8c45602805 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Fri, 16 Aug 2024 11:34:06 -0400 Subject: [PATCH 24/69] Remove duplicate fork definitions (#3304) --- upgrade/upgradetest/config.go | 70 +++++++++ upgrade/upgradetest/fork.go | 25 +++ vms/avm/block/executor/block_test.go | 6 +- vms/avm/environment_test.go | 39 +---- vms/avm/index_test.go | 9 +- vms/avm/service_test.go | 55 ++++--- vms/avm/state_test.go | 7 +- .../txs/executor/syntactic_verifier_test.go | 7 +- vms/avm/vm_benchmark_test.go | 5 +- vms/avm/vm_regression_test.go | 3 +- vms/avm/vm_test.go | 23 +-- vms/avm/wallet_service_test.go | 3 +- vms/platformvm/block/builder/builder_test.go | 17 +- vms/platformvm/block/builder/helpers_test.go | 62 ++------ .../block/builder/standard_block_test.go | 3 +- vms/platformvm/block/executor/helpers_test.go | 60 ++----- .../block/executor/proposal_block_test.go | 17 +- .../block/executor/standard_block_test.go | 15 +- .../block/executor/verifier_test.go | 65 ++------ vms/platformvm/service_test.go | 3 +- .../txs/executor/advance_time_test.go | 23 +-- .../txs/executor/create_chain_test.go | 11 +- .../txs/executor/create_subnet_test.go | 3 +- vms/platformvm/txs/executor/export_test.go | 3 +- vms/platformvm/txs/executor/helpers_test.go | 66 +++----- vms/platformvm/txs/executor/import_test.go | 3 +- .../txs/executor/proposal_tx_executor_test.go | 9 +- .../txs/executor/reward_validator_test.go | 13 +- .../executor/staker_tx_verification_test.go | 93 +++++++---- .../txs/executor/standard_tx_executor_test.go | 114 ++++++-------- vms/platformvm/validator_set_property_test.go | 13 +- vms/platformvm/vm_regression_test.go | 36 ++--- vms/platformvm/vm_test.go | 146 ++++-------------- vms/proposervm/block_test.go | 14 +- vms/proposervm/post_fork_option_test.go | 8 +- vms/proposervm/state_syncable_vm_test.go | 9 +- vms/proposervm/vm_test.go | 61 ++------ 37 files changed, 470 insertions(+), 649 deletions(-) create mode 100644 upgrade/upgradetest/config.go create mode 100644 upgrade/upgradetest/fork.go diff --git a/upgrade/upgradetest/config.go b/upgrade/upgradetest/config.go new file mode 100644 index 000000000000..864059e4dc28 --- /dev/null +++ b/upgrade/upgradetest/config.go @@ -0,0 +1,70 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package upgradetest + +import ( + "time" + + "github.com/ava-labs/avalanchego/upgrade" +) + +// GetConfig returns an upgrade config with the provided fork scheduled to have +// been initially activated and all other forks to be unscheduled. +func GetConfig(fork Fork) upgrade.Config { + return GetConfigWithUpgradeTime(fork, upgrade.InitiallyActiveTime) +} + +// GetConfigWithUpgradeTime returns an upgrade config with the provided fork +// scheduled to be activated at the provided upgradeTime and all other forks to +// be unscheduled. +func GetConfigWithUpgradeTime(fork Fork, upgradeTime time.Time) upgrade.Config { + c := upgrade.Config{} + // Initialize all forks to be unscheduled + SetTimesTo(&c, Latest, upgrade.UnscheduledActivationTime) + // Schedule the requested forks at the provided upgrade time + SetTimesTo(&c, fork, upgradeTime) + return c +} + +// SetTimesTo sets the upgrade time of the provided fork, and all prior forks, +// to the provided upgradeTime. +func SetTimesTo(c *upgrade.Config, fork Fork, upgradeTime time.Time) { + switch fork { + case Etna: + c.EtnaTime = upgradeTime + fallthrough + case Durango: + c.DurangoTime = upgradeTime + fallthrough + case Cortina: + c.CortinaTime = upgradeTime + fallthrough + case Banff: + c.BanffTime = upgradeTime + fallthrough + case ApricotPhasePost6: + c.ApricotPhasePost6Time = upgradeTime + fallthrough + case ApricotPhase6: + c.ApricotPhase6Time = upgradeTime + fallthrough + case ApricotPhasePre6: + c.ApricotPhasePre6Time = upgradeTime + fallthrough + case ApricotPhase5: + c.ApricotPhase5Time = upgradeTime + fallthrough + case ApricotPhase4: + c.ApricotPhase4Time = upgradeTime + fallthrough + case ApricotPhase3: + c.ApricotPhase3Time = upgradeTime + fallthrough + case ApricotPhase2: + c.ApricotPhase2Time = upgradeTime + fallthrough + case ApricotPhase1: + c.ApricotPhase1Time = upgradeTime + } +} diff --git a/upgrade/upgradetest/fork.go b/upgrade/upgradetest/fork.go new file mode 100644 index 000000000000..01c9b2ea03ee --- /dev/null +++ b/upgrade/upgradetest/fork.go @@ -0,0 +1,25 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package upgradetest + +const ( + NoUpgrades Fork = iota + ApricotPhase1 + ApricotPhase2 + ApricotPhase3 + ApricotPhase4 + ApricotPhase5 + ApricotPhasePre6 + ApricotPhase6 + ApricotPhasePost6 + Banff + Cortina + Durango + Etna + + Latest = Etna +) + +// Fork is an enum of all the major network upgrades. +type Fork int diff --git a/vms/avm/block/executor/block_test.go b/vms/avm/block/executor/block_test.go index c95796da638f..0a3e8e42059a 100644 --- a/vms/avm/block/executor/block_test.go +++ b/vms/avm/block/executor/block_test.go @@ -15,7 +15,7 @@ import ( "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" @@ -940,9 +940,7 @@ func defaultTestBackend(bootstrapped bool, sharedMemory atomic.SharedMemory) *ex Log: logging.NoLog{}, }, Config: &config.Config{ - Upgrades: upgrade.Config{ - EtnaTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfig(upgradetest.Durango), TxFee: 0, CreateAssetTxFee: 0, }, diff --git a/vms/avm/environment_test.go b/vms/avm/environment_test.go index 75cae23f347a..2dcfd077f234 100644 --- a/vms/avm/environment_test.go +++ b/vms/avm/environment_test.go @@ -8,7 +8,6 @@ import ( "encoding/json" "math/rand" "testing" - "time" "github.com/stretchr/testify/require" @@ -21,14 +20,13 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/snowtest" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/sampler" - "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/vms/avm/block/executor" "github.com/ava-labs/avalanchego/vms/avm/config" "github.com/ava-labs/avalanchego/vms/avm/fxs" @@ -42,14 +40,7 @@ import ( keystoreutils "github.com/ava-labs/avalanchego/vms/components/keystore" ) -type fork uint8 - const ( - durango fork = iota - etna - - latest = durango - testTxFee uint64 = 1000 startBalance uint64 = 50000 @@ -95,7 +86,7 @@ type user struct { } type envConfig struct { - fork fork + fork upgradetest.Fork isCustomFeeAsset bool keystoreUsers []*user vmStaticConfig *config.Config @@ -155,7 +146,11 @@ func setup(tb testing.TB, c *envConfig) *environment { require.NoError(keystoreUser.Close()) } - vmStaticConfig := staticConfig(tb, c.fork) + vmStaticConfig := config.Config{ + Upgrades: upgradetest.GetConfig(c.fork), + TxFee: testTxFee, + CreateAssetTxFee: testTxFee, + } if c.vmStaticConfig != nil { vmStaticConfig = *c.vmStaticConfig } @@ -230,26 +225,6 @@ func setup(tb testing.TB, c *envConfig) *environment { return env } -func staticConfig(tb testing.TB, f fork) config.Config { - c := config.Config{ - Upgrades: upgrade.Config{ - EtnaTime: mockable.MaxTime, - }, - TxFee: testTxFee, - CreateAssetTxFee: testTxFee, - } - - switch f { - case etna: - c.Upgrades.EtnaTime = time.Time{} - case durango: - default: - require.FailNow(tb, "unhandled fork", f) - } - - return c -} - // Returns: // // 1. tx in genesis that creates asset diff --git a/vms/avm/index_test.go b/vms/avm/index_test.go index 3d8614d5ee6d..dfd62198c312 100644 --- a/vms/avm/index_test.go +++ b/vms/avm/index_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" @@ -27,7 +28,7 @@ import ( func TestIndexTransaction_Ordered(t *testing.T) { require := require.New(t) - env := setup(t, &envConfig{fork: durango}) + env := setup(t, &envConfig{fork: upgradetest.Durango}) defer env.vm.ctx.Lock.Unlock() key := keys[0] @@ -66,7 +67,7 @@ func TestIndexTransaction_Ordered(t *testing.T) { func TestIndexTransaction_MultipleTransactions(t *testing.T) { require := require.New(t) - env := setup(t, &envConfig{fork: durango}) + env := setup(t, &envConfig{fork: upgradetest.Durango}) defer env.vm.ctx.Lock.Unlock() addressTxMap := map[ids.ShortID]*txs.Tx{} @@ -109,7 +110,7 @@ func TestIndexTransaction_MultipleTransactions(t *testing.T) { func TestIndexTransaction_MultipleAddresses(t *testing.T) { require := require.New(t) - env := setup(t, &envConfig{fork: durango}) + env := setup(t, &envConfig{fork: upgradetest.Durango}) defer env.vm.ctx.Lock.Unlock() addrs := make([]ids.ShortID, len(keys)) @@ -147,7 +148,7 @@ func TestIndexTransaction_MultipleAddresses(t *testing.T) { func TestIndexer_Read(t *testing.T) { require := require.New(t) - env := setup(t, &envConfig{fork: durango}) + env := setup(t, &envConfig{fork: upgradetest.Durango}) defer env.vm.ctx.Lock.Unlock() // generate test address and asset IDs diff --git a/vms/avm/service_test.go b/vms/avm/service_test.go index 534424c63b0e..b052552e4a13 100644 --- a/vms/avm/service_test.go +++ b/vms/avm/service_test.go @@ -22,13 +22,12 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/choices" "github.com/ava-labs/avalanchego/snow/engine/common" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/avm/block" "github.com/ava-labs/avalanchego/vms/avm/block/executor" @@ -49,7 +48,7 @@ func TestServiceIssueTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -72,7 +71,7 @@ func TestServiceGetTxStatus(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -104,7 +103,7 @@ func TestServiceGetBalanceStrict(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} @@ -258,7 +257,7 @@ func TestServiceGetBalanceStrict(t *testing.T) { func TestServiceGetTxs(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} @@ -299,7 +298,7 @@ func TestServiceGetAllBalances(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} @@ -495,7 +494,7 @@ func TestServiceGetTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -520,7 +519,7 @@ func TestServiceGetTxJSON_BaseTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -608,7 +607,7 @@ func TestServiceGetTxJSON_ExportTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -698,7 +697,7 @@ func TestServiceGetTxJSON_CreateAssetTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: propertyfx.ID, Fx: &propertyfx.Fx{}, @@ -891,7 +890,7 @@ func TestServiceGetTxJSON_OperationTxWithNftxMintOp(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: propertyfx.ID, Fx: &propertyfx.Fx{}, @@ -1033,7 +1032,7 @@ func TestServiceGetTxJSON_OperationTxWithMultipleNftxMintOp(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: propertyfx.ID, Fx: &propertyfx.Fx{}, @@ -1214,7 +1213,7 @@ func TestServiceGetTxJSON_OperationTxWithSecpMintOp(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: propertyfx.ID, Fx: &propertyfx.Fx{}, @@ -1357,7 +1356,7 @@ func TestServiceGetTxJSON_OperationTxWithMultipleSecpMintOp(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: durango, + fork: upgradetest.Durango, additionalFxs: []*common.Fx{{ ID: propertyfx.ID, Fx: &propertyfx.Fx{}, @@ -1544,7 +1543,7 @@ func TestServiceGetTxJSON_OperationTxWithPropertyFxMintOp(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: propertyfx.ID, Fx: &propertyfx.Fx{}, @@ -1679,7 +1678,7 @@ func TestServiceGetTxJSON_OperationTxWithPropertyFxMintOpMultiple(t *testing.T) require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: propertyfx.ID, Fx: &propertyfx.Fx{}, @@ -2010,7 +2009,7 @@ func TestServiceGetNilTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -2024,7 +2023,7 @@ func TestServiceGetUnknownTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -2036,7 +2035,7 @@ func TestServiceGetUnknownTx(t *testing.T) { func TestServiceGetUTXOs(t *testing.T) { env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -2288,7 +2287,7 @@ func TestGetAssetDescription(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -2308,7 +2307,7 @@ func TestGetBalance(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) service := &Service{vm: env.vm} env.vm.ctx.Lock.Unlock() @@ -2332,6 +2331,7 @@ func TestCreateFixedCapAsset(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ + fork: upgradetest.Durango, isCustomFeeAsset: !tc.avaxAsset, keystoreUsers: []*user{{ username: username, @@ -2378,6 +2378,7 @@ func TestCreateVariableCapAsset(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ + fork: upgradetest.Durango, isCustomFeeAsset: !tc.avaxAsset, keystoreUsers: []*user{{ username: username, @@ -2466,6 +2467,7 @@ func TestNFTWorkflow(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ + fork: upgradetest.Durango, isCustomFeeAsset: !tc.avaxAsset, keystoreUsers: []*user{{ username: username, @@ -2584,6 +2586,7 @@ func TestImportExportKey(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ + fork: upgradetest.Durango, keystoreUsers: []*user{{ username: username, password: password, @@ -2623,6 +2626,7 @@ func TestImportAVMKeyNoDuplicates(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ + fork: upgradetest.Durango, keystoreUsers: []*user{{ username: username, password: password, @@ -2668,6 +2672,7 @@ func TestSend(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ + fork: upgradetest.Durango, keystoreUsers: []*user{{ username: username, password: password, @@ -2721,9 +2726,7 @@ func TestSendMultiple(t *testing.T) { initialKeys: keys, }}, vmStaticConfig: &config.Config{ - Upgrades: upgrade.Config{ - EtnaTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfig(upgradetest.Durango), }, }) service := &Service{vm: env.vm} @@ -2773,6 +2776,7 @@ func TestCreateAndListAddresses(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ + fork: upgradetest.Durango, keystoreUsers: []*user{{ username: username, password: password, @@ -2807,6 +2811,7 @@ func TestImport(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ + fork: upgradetest.Durango, isCustomFeeAsset: !tc.avaxAsset, keystoreUsers: []*user{{ username: username, diff --git a/vms/avm/state_test.go b/vms/avm/state_test.go index 35744fdc63e8..948ca37a8e18 100644 --- a/vms/avm/state_test.go +++ b/vms/avm/state_test.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/units" @@ -23,7 +24,7 @@ func TestSetsAndGets(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: ids.GenerateTestID(), Fx: &FxTest{ @@ -83,7 +84,7 @@ func TestSetsAndGets(t *testing.T) { func TestFundingNoAddresses(t *testing.T) { env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: ids.GenerateTestID(), Fx: &FxTest{ @@ -113,7 +114,7 @@ func TestFundingAddresses(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: ids.GenerateTestID(), Fx: &FxTest{ diff --git a/vms/avm/txs/executor/syntactic_verifier_test.go b/vms/avm/txs/executor/syntactic_verifier_test.go index a5811163bad1..438e936af7a8 100644 --- a/vms/avm/txs/executor/syntactic_verifier_test.go +++ b/vms/avm/txs/executor/syntactic_verifier_test.go @@ -12,10 +12,9 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/snowtest" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/vms/avm/config" "github.com/ava-labs/avalanchego/vms/avm/fxs" "github.com/ava-labs/avalanchego/vms/avm/txs" @@ -29,9 +28,7 @@ import ( var ( keys = secp256k1.TestKeys() feeConfig = config.Config{ - Upgrades: upgrade.Config{ - EtnaTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfig(upgradetest.Durango), TxFee: 2, CreateAssetTxFee: 3, } diff --git a/vms/avm/vm_benchmark_test.go b/vms/avm/vm_benchmark_test.go index 8a342cfa2477..48725d72da2a 100644 --- a/vms/avm/vm_benchmark_test.go +++ b/vms/avm/vm_benchmark_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/keystore" @@ -22,7 +23,7 @@ func BenchmarkLoadUser(b *testing.B) { require := require.New(b) env := setup(b, &envConfig{ - fork: latest, + fork: upgradetest.Latest, keystoreUsers: []*user{{ username: username, password: password, @@ -64,7 +65,7 @@ func BenchmarkLoadUser(b *testing.B) { func getAllUTXOsBenchmark(b *testing.B, utxoCount int, randSrc rand.Source) { require := require.New(b) - env := setup(b, &envConfig{fork: latest}) + env := setup(b, &envConfig{fork: upgradetest.Latest}) defer env.vm.ctx.Lock.Unlock() addr := ids.GenerateTestShortID() diff --git a/vms/avm/vm_regression_test.go b/vms/avm/vm_regression_test.go index 9e684e756d5c..5edfdb083851 100644 --- a/vms/avm/vm_regression_test.go +++ b/vms/avm/vm_regression_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/nftfx" @@ -18,7 +19,7 @@ import ( func TestVerifyFxUsage(t *testing.T) { require := require.New(t) - env := setup(t, &envConfig{fork: latest}) + env := setup(t, &envConfig{fork: upgradetest.Latest}) env.vm.ctx.Lock.Unlock() var ( diff --git a/vms/avm/vm_test.go b/vms/avm/vm_test.go index 33af48c483f8..011d9e00eb1d 100644 --- a/vms/avm/vm_test.go +++ b/vms/avm/vm_test.go @@ -17,6 +17,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/snowtest" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/avm/txs" @@ -114,7 +115,7 @@ func TestIssueTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) env.vm.ctx.Lock.Unlock() @@ -127,7 +128,7 @@ func TestIssueNFT(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) env.vm.ctx.Lock.Unlock() @@ -200,7 +201,7 @@ func TestIssueProperty(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, additionalFxs: []*common.Fx{{ ID: propertyfx.ID, Fx: &propertyfx.Fx{}, @@ -288,7 +289,7 @@ func TestIssueTxWithFeeAsset(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, isCustomFeeAsset: true, }) env.vm.ctx.Lock.Unlock() @@ -302,7 +303,7 @@ func TestIssueTxWithAnotherAsset(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, isCustomFeeAsset: true, }) env.vm.ctx.Lock.Unlock() @@ -349,7 +350,7 @@ func TestIssueTxWithAnotherAsset(t *testing.T) { func TestVMFormat(t *testing.T) { env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) defer env.vm.ctx.Lock.Unlock() @@ -376,7 +377,7 @@ func TestTxAcceptAfterParseTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, notLinearized: true, }) defer env.vm.ctx.Lock.Unlock() @@ -451,7 +452,7 @@ func TestIssueImportTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: durango, + fork: upgradetest.Durango, }) defer env.vm.ctx.Lock.Unlock() @@ -529,7 +530,7 @@ func TestForceAcceptImportTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: durango, + fork: upgradetest.Durango, notLinearized: true, }) defer env.vm.ctx.Lock.Unlock() @@ -603,7 +604,7 @@ func TestImportTxNotState(t *testing.T) { func TestIssueExportTx(t *testing.T) { require := require.New(t) - env := setup(t, &envConfig{fork: durango}) + env := setup(t, &envConfig{fork: upgradetest.Durango}) defer env.vm.ctx.Lock.Unlock() genesisTx := getCreateTxFromGenesisTest(t, env.genesisBytes, "AVAX") @@ -662,7 +663,7 @@ func TestClearForceAcceptedExportTx(t *testing.T) { require := require.New(t) env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, }) defer env.vm.ctx.Lock.Unlock() diff --git a/vms/avm/wallet_service_test.go b/vms/avm/wallet_service_test.go index d4423bd31c7d..5bada667fb8c 100644 --- a/vms/avm/wallet_service_test.go +++ b/vms/avm/wallet_service_test.go @@ -10,6 +10,7 @@ import ( "github.com/ava-labs/avalanchego/api" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/linked" "github.com/ava-labs/avalanchego/vms/avm/txs" ) @@ -20,7 +21,7 @@ func TestWalletService_SendMultiple(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { env := setup(t, &envConfig{ - fork: latest, + fork: upgradetest.Latest, isCustomFeeAsset: !tc.avaxAsset, keystoreUsers: []*user{{ username: username, diff --git a/vms/platformvm/block/builder/builder_test.go b/vms/platformvm/block/builder/builder_test.go index eeddc5bc7f9b..33574b384582 100644 --- a/vms/platformvm/block/builder/builder_test.go +++ b/vms/platformvm/block/builder/builder_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/snowman" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -34,7 +35,7 @@ import ( func TestBuildBlockBasic(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -77,7 +78,7 @@ func TestBuildBlockBasic(t *testing.T) { func TestBuildBlockDoesNotBuildWithEmptyMempool(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -94,7 +95,7 @@ func TestBuildBlockDoesNotBuildWithEmptyMempool(t *testing.T) { func TestBuildBlockShouldReward(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -213,7 +214,7 @@ func TestBuildBlockShouldReward(t *testing.T) { func TestBuildBlockAdvanceTime(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -246,7 +247,7 @@ func TestBuildBlockAdvanceTime(t *testing.T) { func TestBuildBlockForceAdvanceTime(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -301,7 +302,7 @@ func TestBuildBlockForceAdvanceTime(t *testing.T) { func TestBuildBlockInvalidStakingDurations(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -421,7 +422,7 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { func TestPreviouslyDroppedTxsCannotBeReAddedToMempool(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -465,7 +466,7 @@ func TestPreviouslyDroppedTxsCannotBeReAddedToMempool(t *testing.T) { func TestNoErrorOnUnexpectedSetPreferenceDuringBootstrapping(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() diff --git a/vms/platformvm/block/builder/helpers_test.go b/vms/platformvm/block/builder/helpers_test.go index 28220e60a1e7..0ed61f930d01 100644 --- a/vms/platformvm/block/builder/helpers_test.go +++ b/vms/platformvm/block/builder/helpers_test.go @@ -26,7 +26,7 @@ import ( "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" @@ -61,15 +61,6 @@ import ( const ( defaultWeight = 10000 trackChecksum = false - - apricotPhase3 fork = iota - apricotPhase5 - banff - cortina - durango - etna - - latestFork = durango ) var ( @@ -97,8 +88,6 @@ func init() { } } -type fork uint8 - type mutableSharedMemory struct { atomic.SharedMemory } @@ -124,12 +113,12 @@ type environment struct { backend txexecutor.Backend } -func newEnvironment(t *testing.T, f fork) *environment { //nolint:unparam +func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { //nolint:unparam require := require.New(t) res := &environment{ isBootstrapped: &utils.Atomic[bool]{}, - config: defaultConfig(t, f), + config: defaultConfig(f), clk: defaultClock(), } res.isBootstrapped.Set(true) @@ -303,8 +292,16 @@ func defaultState( return state } -func defaultConfig(t *testing.T, f fork) *config.Config { - c := &config.Config{ +func defaultConfig(f upgradetest.Fork) *config.Config { + upgrades := upgradetest.GetConfigWithUpgradeTime(f, time.Time{}) + // This package neglects fork ordering + upgradetest.SetTimesTo( + &upgrades, + min(f, upgradetest.ApricotPhase5), + defaultValidateEndTime, + ) + + return &config.Config{ Chains: chains.TestManager, UptimeLockedCalculator: uptime.NewLockedCalculator(), Validators: validators.NewManager(), @@ -324,39 +321,8 @@ func defaultConfig(t *testing.T, f fork) *config.Config { MintingPeriod: 365 * 24 * time.Hour, SupplyCap: 720 * units.MegaAvax, }, - UpgradeConfig: upgrade.Config{ - ApricotPhase3Time: mockable.MaxTime, - ApricotPhase5Time: mockable.MaxTime, - BanffTime: mockable.MaxTime, - CortinaTime: mockable.MaxTime, - DurangoTime: mockable.MaxTime, - EtnaTime: mockable.MaxTime, - }, - } - - switch f { - case etna: - c.UpgradeConfig.EtnaTime = time.Time{} // neglecting fork ordering this for package tests - fallthrough - case durango: - c.UpgradeConfig.DurangoTime = time.Time{} // neglecting fork ordering for this package's tests - fallthrough - case cortina: - c.UpgradeConfig.CortinaTime = time.Time{} // neglecting fork ordering for this package's tests - fallthrough - case banff: - c.UpgradeConfig.BanffTime = time.Time{} // neglecting fork ordering for this package's tests - fallthrough - case apricotPhase5: - c.UpgradeConfig.ApricotPhase5Time = defaultValidateEndTime - fallthrough - case apricotPhase3: - c.UpgradeConfig.ApricotPhase3Time = defaultValidateEndTime - default: - require.FailNow(t, "unhandled fork", f) + UpgradeConfig: upgrades, } - - return c } func defaultClock() *mockable.Clock { diff --git a/vms/platformvm/block/builder/standard_block_test.go b/vms/platformvm/block/builder/standard_block_test.go index 18ca5bdb3582..6909c0efd794 100644 --- a/vms/platformvm/block/builder/standard_block_test.go +++ b/vms/platformvm/block/builder/standard_block_test.go @@ -12,6 +12,7 @@ import ( "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" @@ -23,7 +24,7 @@ import ( func TestAtomicTxImports(t *testing.T) { require := require.New(t) - env := newEnvironment(t, latestFork) + env := newEnvironment(t, upgradetest.Latest) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() diff --git a/vms/platformvm/block/executor/helpers_test.go b/vms/platformvm/block/executor/helpers_test.go index 79f2e78eb19e..22305de07ac7 100644 --- a/vms/platformvm/block/executor/helpers_test.go +++ b/vms/platformvm/block/executor/helpers_test.go @@ -27,7 +27,7 @@ import ( "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" @@ -63,13 +63,6 @@ const ( defaultWeight = 10000 trackChecksum = false - - apricotPhase3 fork = iota - apricotPhase5 - banff - cortina - durango - etna ) var ( @@ -100,8 +93,6 @@ func init() { type stakerStatus uint -type fork uint8 - type staker struct { nodeID ids.NodeID rewardAddress ids.ShortID @@ -136,10 +127,10 @@ type environment struct { backend *executor.Backend } -func newEnvironment(t *testing.T, ctrl *gomock.Controller, f fork) *environment { +func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) *environment { res := &environment{ isBootstrapped: &utils.Atomic[bool]{}, - config: defaultConfig(t, f), + config: defaultConfig(f), clk: defaultClock(), } res.isBootstrapped.Set(true) @@ -332,8 +323,16 @@ func defaultState( return state } -func defaultConfig(t *testing.T, f fork) *config.Config { - c := &config.Config{ +func defaultConfig(f upgradetest.Fork) *config.Config { + upgrades := upgradetest.GetConfigWithUpgradeTime(f, time.Time{}) + // This package neglects fork ordering + upgradetest.SetTimesTo( + &upgrades, + min(f, upgradetest.ApricotPhase5), + defaultValidateEndTime, + ) + + return &config.Config{ Chains: chains.TestManager, UptimeLockedCalculator: uptime.NewLockedCalculator(), Validators: validators.NewManager(), @@ -353,39 +352,8 @@ func defaultConfig(t *testing.T, f fork) *config.Config { MintingPeriod: 365 * 24 * time.Hour, SupplyCap: 720 * units.MegaAvax, }, - UpgradeConfig: upgrade.Config{ - ApricotPhase3Time: mockable.MaxTime, - ApricotPhase5Time: mockable.MaxTime, - BanffTime: mockable.MaxTime, - CortinaTime: mockable.MaxTime, - DurangoTime: mockable.MaxTime, - EtnaTime: mockable.MaxTime, - }, - } - - switch f { - case etna: - c.UpgradeConfig.EtnaTime = time.Time{} // neglecting fork ordering this for package tests - fallthrough - case durango: - c.UpgradeConfig.DurangoTime = time.Time{} // neglecting fork ordering for this package's tests - fallthrough - case cortina: - c.UpgradeConfig.CortinaTime = time.Time{} // neglecting fork ordering for this package's tests - fallthrough - case banff: - c.UpgradeConfig.BanffTime = time.Time{} // neglecting fork ordering for this package's tests - fallthrough - case apricotPhase5: - c.UpgradeConfig.ApricotPhase5Time = defaultValidateEndTime - fallthrough - case apricotPhase3: - c.UpgradeConfig.ApricotPhase3Time = defaultValidateEndTime - default: - require.FailNow(t, "unhandled fork", f) + UpgradeConfig: upgrades, } - - return c } func defaultClock() *mockable.Clock { diff --git a/vms/platformvm/block/executor/proposal_block_test.go b/vms/platformvm/block/executor/proposal_block_test.go index 1f6e1123ab8e..0dbcb74c11d5 100644 --- a/vms/platformvm/block/executor/proposal_block_test.go +++ b/vms/platformvm/block/executor/proposal_block_test.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/snowtest" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" @@ -38,7 +39,7 @@ func TestApricotProposalBlockTimeVerification(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - env := newEnvironment(t, ctrl, apricotPhase5) + env := newEnvironment(t, ctrl, upgradetest.ApricotPhase5) // create apricotParentBlk. It's a standard one for simplicity parentHeight := uint64(2022) @@ -140,7 +141,7 @@ func TestBanffProposalBlockTimeVerification(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - env := newEnvironment(t, ctrl, banff) + env := newEnvironment(t, ctrl, upgradetest.Banff) // create parentBlock. It's a standard one for simplicity parentTime := defaultGenesisTime @@ -531,7 +532,7 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { for _, test := range tests { t.Run(test.description, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) subnetID := testSubnet1.ID() env.config.TrackedSubnets.Add(subnetID) @@ -709,7 +710,7 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) subnetID := testSubnet1.ID() env.config.TrackedSubnets.Add(subnetID) @@ -866,7 +867,7 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { for _, tracked := range []bool{true, false} { t.Run(fmt.Sprintf("tracked %t", tracked), func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) subnetID := testSubnet1.ID() if tracked { @@ -980,7 +981,7 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) // Case: Timestamp is after next validator start time // Add a pending validator @@ -1175,7 +1176,7 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { func TestBanffProposalBlockDelegatorStakers(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) // Case: Timestamp is after next validator start time // Add a pending validator @@ -1370,7 +1371,7 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { func TestAddValidatorProposalBlock(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, durango) + env := newEnvironment(t, nil, upgradetest.Durango) now := env.clk.Time() diff --git a/vms/platformvm/block/executor/standard_block_test.go b/vms/platformvm/block/executor/standard_block_test.go index 3d30030518f9..3dc1f999e789 100644 --- a/vms/platformvm/block/executor/standard_block_test.go +++ b/vms/platformvm/block/executor/standard_block_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/avax" @@ -32,7 +33,7 @@ func TestApricotStandardBlockTimeVerification(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - env := newEnvironment(t, ctrl, apricotPhase5) + env := newEnvironment(t, ctrl, upgradetest.ApricotPhase5) // setup and store parent block // it's a standard block for simplicity @@ -84,7 +85,7 @@ func TestBanffStandardBlockTimeVerification(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - env := newEnvironment(t, ctrl, banff) + env := newEnvironment(t, ctrl, upgradetest.Banff) now := env.clk.Time() env.clk.Set(now) @@ -290,7 +291,7 @@ func TestBanffStandardBlockTimeVerification(t *testing.T) { func TestBanffStandardBlockUpdatePrimaryNetworkStakers(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) // Case: Timestamp is after next validator start time // Add a pending validator @@ -491,7 +492,7 @@ func TestBanffStandardBlockUpdateStakers(t *testing.T) { for _, test := range tests { t.Run(test.description, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) subnetID := testSubnet1.ID() env.config.TrackedSubnets.Add(subnetID) @@ -594,7 +595,7 @@ func TestBanffStandardBlockUpdateStakers(t *testing.T) { // is after the new timestamp func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) subnetID := testSubnet1.ID() env.config.TrackedSubnets.Add(subnetID) @@ -698,7 +699,7 @@ func TestBanffStandardBlockTrackedSubnet(t *testing.T) { for _, tracked := range []bool{true, false} { t.Run(fmt.Sprintf("tracked %t", tracked), func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) subnetID := testSubnet1.ID() if tracked { @@ -762,7 +763,7 @@ func TestBanffStandardBlockTrackedSubnet(t *testing.T) { func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { require := require.New(t) - env := newEnvironment(t, nil, banff) + env := newEnvironment(t, nil, upgradetest.Banff) // Case: Timestamp is after next validator start time // Add a pending validator diff --git a/vms/platformvm/block/executor/verifier_test.go b/vms/platformvm/block/executor/verifier_test.go index 5c058e7c69ee..535e7d70f37e 100644 --- a/vms/platformvm/block/executor/verifier_test.go +++ b/vms/platformvm/block/executor/verifier_test.go @@ -15,7 +15,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -61,9 +61,7 @@ func TestVerifierVisitProposalBlock(t *testing.T) { manager := &manager{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -143,10 +141,7 @@ func TestVerifierVisitAtomicBlock(t *testing.T) { manager := &manager{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - ApricotPhase5Time: time.Now().Add(time.Hour), - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -228,10 +223,7 @@ func TestVerifierVisitStandardBlock(t *testing.T) { manager := &manager{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - ApricotPhase5Time: time.Now().Add(time.Hour), - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -332,9 +324,7 @@ func TestVerifierVisitCommitBlock(t *testing.T) { manager := &manager{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -401,9 +391,7 @@ func TestVerifierVisitAbortBlock(t *testing.T) { manager := &manager{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -458,9 +446,7 @@ func TestVerifyUnverifiedParent(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -532,9 +518,7 @@ func TestBanffAbortBlockTimestampChecks(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: time.Time{}, // banff is activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.Banff), }, Clk: &mockable.Clock{}, }, @@ -631,9 +615,7 @@ func TestBanffCommitBlockTimestampChecks(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: time.Time{}, // banff is activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.Banff), }, Clk: &mockable.Clock{}, }, @@ -713,10 +695,7 @@ func TestVerifierVisitStandardBlockWithDuplicateInputs(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - ApricotPhase5Time: time.Now().Add(time.Hour), - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -805,9 +784,7 @@ func TestVerifierVisitApricotStandardBlockWithProposalBlockParent(t *testing.T) verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -864,9 +841,7 @@ func TestVerifierVisitBanffStandardBlockWithProposalBlockParent(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: time.Time{}, // banff is activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.Banff), }, Clk: &mockable.Clock{}, }, @@ -903,9 +878,7 @@ func TestVerifierVisitApricotCommitBlockUnexpectedParentState(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -948,9 +921,7 @@ func TestVerifierVisitBanffCommitBlockUnexpectedParentState(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: time.Time{}, // banff is activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.Banff), }, Clk: &mockable.Clock{}, }, @@ -994,9 +965,7 @@ func TestVerifierVisitApricotAbortBlockUnexpectedParentState(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: mockable.MaxTime, // banff is not activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.ApricotPhasePost6), }, Clk: &mockable.Clock{}, }, @@ -1039,9 +1008,7 @@ func TestVerifierVisitBanffAbortBlockUnexpectedParentState(t *testing.T) { verifier := &verifier{ txExecutorBackend: &executor.Backend{ Config: &config.Config{ - UpgradeConfig: upgrade.Config{ - BanffTime: time.Time{}, // banff is activated - }, + UpgradeConfig: upgradetest.GetConfig(upgradetest.Banff), }, Clk: &mockable.Clock{}, }, diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index f8335a621e07..3c89f712adf7 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -27,6 +27,7 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" @@ -77,7 +78,7 @@ var ( ) func defaultService(t *testing.T) (*Service, *mutableSharedMemory, *txstest.WalletFactory) { - vm, factory, _, mutableSharedMemory := defaultVM(t, latestFork) + vm, factory, _, mutableSharedMemory := defaultVM(t, upgradetest.Latest) return &Service{ vm: vm, diff --git a/vms/platformvm/txs/executor/advance_time_test.go b/vms/platformvm/txs/executor/advance_time_test.go index ed7e80ad195f..e9e54ad8a3e6 100644 --- a/vms/platformvm/txs/executor/advance_time_test.go +++ b/vms/platformvm/txs/executor/advance_time_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/snowtest" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/platformvm/reward" @@ -38,7 +39,7 @@ func newAdvanceTimeTx(t testing.TB, timestamp time.Time) (*txs.Tx, error) { // for the primary network func TestAdvanceTimeTxUpdatePrimaryNetworkStakers(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() dummyHeight := uint64(1) @@ -103,7 +104,7 @@ func TestAdvanceTimeTxUpdatePrimaryNetworkStakers(t *testing.T) { // Ensure semantic verification fails when proposed timestamp is at or before current timestamp func TestAdvanceTimeTxTimestampTooEarly(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) tx, err := newAdvanceTimeTx(t, env.state.GetTimestamp()) require.NoError(err) @@ -129,7 +130,7 @@ func TestAdvanceTimeTxTimestampTooEarly(t *testing.T) { // Ensure semantic verification fails when proposed timestamp is after next validator set change time func TestAdvanceTimeTxTimestampTooLate(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -164,7 +165,7 @@ func TestAdvanceTimeTxTimestampTooLate(t *testing.T) { } // Case: Timestamp is after next validator end time - env = newEnvironment(t, apricotPhase5) + env = newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -366,7 +367,7 @@ func TestAdvanceTimeTxUpdateStakers(t *testing.T) { for _, test := range tests { t.Run(test.description, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -476,7 +477,7 @@ func TestAdvanceTimeTxUpdateStakers(t *testing.T) { // is after the new timestamp func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -590,7 +591,7 @@ func TestTrackedSubnet(t *testing.T) { for _, tracked := range []bool{true, false} { t.Run(fmt.Sprintf("tracked %t", tracked), func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() dummyHeight := uint64(1) @@ -665,7 +666,7 @@ func TestTrackedSubnet(t *testing.T) { func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() dummyHeight := uint64(1) @@ -775,7 +776,7 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() dummyHeight := uint64(1) @@ -878,7 +879,7 @@ func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { func TestAdvanceTimeTxAfterBanff(t *testing.T) { require := require.New(t) - env := newEnvironment(t, durango) + env := newEnvironment(t, upgradetest.Durango) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() env.clk.Set(defaultGenesisTime) // VM's clock reads the genesis time @@ -912,7 +913,7 @@ func TestAdvanceTimeTxAfterBanff(t *testing.T) { // Ensure marshaling/unmarshaling works func TestAdvanceTimeTxUnmarshal(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() diff --git a/vms/platformvm/txs/executor/create_chain_test.go b/vms/platformvm/txs/executor/create_chain_test.go index 1f5e4be4f97a..f8b29b9c275d 100644 --- a/vms/platformvm/txs/executor/create_chain_test.go +++ b/vms/platformvm/txs/executor/create_chain_test.go @@ -12,6 +12,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/hashing" @@ -29,7 +30,7 @@ import ( // Ensure Execute fails when there are not enough control sigs func TestCreateChainTxInsufficientControlSigs(t *testing.T) { require := require.New(t) - env := newEnvironment(t, banff) + env := newEnvironment(t, upgradetest.Banff) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -65,7 +66,7 @@ func TestCreateChainTxInsufficientControlSigs(t *testing.T) { // Ensure Execute fails when an incorrect control signature is given func TestCreateChainTxWrongControlSig(t *testing.T) { require := require.New(t) - env := newEnvironment(t, banff) + env := newEnvironment(t, upgradetest.Banff) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -108,7 +109,7 @@ func TestCreateChainTxWrongControlSig(t *testing.T) { // its validator set doesn't exist func TestCreateChainTxNoSuchSubnet(t *testing.T) { require := require.New(t) - env := newEnvironment(t, banff) + env := newEnvironment(t, upgradetest.Banff) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -146,7 +147,7 @@ func TestCreateChainTxNoSuchSubnet(t *testing.T) { // Ensure valid tx passes semanticVerify func TestCreateChainTxValid(t *testing.T) { require := require.New(t) - env := newEnvironment(t, banff) + env := newEnvironment(t, upgradetest.Banff) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -209,7 +210,7 @@ func TestCreateChainTxAP3FeeChange(t *testing.T) { t.Run(test.name, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, banff) + env := newEnvironment(t, upgradetest.Banff) env.config.UpgradeConfig.ApricotPhase3Time = ap3Time addrs := set.NewSet[ids.ShortID](len(preFundedKeys)) diff --git a/vms/platformvm/txs/executor/create_subnet_test.go b/vms/platformvm/txs/executor/create_subnet_test.go index e88bc05c6745..a991bda7de0e 100644 --- a/vms/platformvm/txs/executor/create_subnet_test.go +++ b/vms/platformvm/txs/executor/create_subnet_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -52,7 +53,7 @@ func TestCreateSubnetTxAP3FeeChange(t *testing.T) { t.Run(test.name, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase3) + env := newEnvironment(t, upgradetest.ApricotPhase3) env.config.UpgradeConfig.ApricotPhase3Time = ap3Time env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() diff --git a/vms/platformvm/txs/executor/export_test.go b/vms/platformvm/txs/executor/export_test.go index 18e337a82465..d392f0bc9618 100644 --- a/vms/platformvm/txs/executor/export_test.go +++ b/vms/platformvm/txs/executor/export_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -20,7 +21,7 @@ import ( ) func TestNewExportTx(t *testing.T) { - env := newEnvironment(t, banff) + env := newEnvironment(t, upgradetest.Banff) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() diff --git a/vms/platformvm/txs/executor/helpers_test.go b/vms/platformvm/txs/executor/helpers_test.go index 8aea45ee3317..2342f2270d43 100644 --- a/vms/platformvm/txs/executor/helpers_test.go +++ b/vms/platformvm/txs/executor/helpers_test.go @@ -25,7 +25,7 @@ import ( "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" @@ -55,13 +55,6 @@ import ( const ( defaultWeight = 5 * units.MilliAvax trackChecksum = false - - apricotPhase3 fork = iota - apricotPhase5 - banff - cortina - durango - etna ) var ( @@ -90,8 +83,6 @@ func init() { } } -type fork uint8 - type mutableSharedMemory struct { atomic.SharedMemory } @@ -124,11 +115,11 @@ func (e *environment) SetState(blkID ids.ID, chainState state.Chain) { e.states[blkID] = chainState } -func newEnvironment(t *testing.T, f fork) *environment { +func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { var isBootstrapped utils.Atomic[bool] isBootstrapped.Set(true) - config := defaultConfig(t, f) + config := defaultConfig(f) clk := defaultClock(f) baseDB := versiondb.New(memdb.New()) @@ -275,8 +266,18 @@ func defaultState( return state } -func defaultConfig(t *testing.T, f fork) *config.Config { - c := &config.Config{ +func defaultConfig(f upgradetest.Fork) *config.Config { + upgrades := upgradetest.GetConfigWithUpgradeTime( + f, + defaultValidateStartTime.Add(-2*time.Second), + ) + upgradetest.SetTimesTo( + &upgrades, + min(f, upgradetest.ApricotPhase5), + defaultValidateEndTime, + ) + + return &config.Config{ Chains: chains.TestManager, UptimeLockedCalculator: uptime.NewLockedCalculator(), Validators: validators.NewManager(), @@ -296,44 +297,13 @@ func defaultConfig(t *testing.T, f fork) *config.Config { MintingPeriod: 365 * 24 * time.Hour, SupplyCap: 720 * units.MegaAvax, }, - UpgradeConfig: upgrade.Config{ - ApricotPhase3Time: mockable.MaxTime, - ApricotPhase5Time: mockable.MaxTime, - BanffTime: mockable.MaxTime, - CortinaTime: mockable.MaxTime, - DurangoTime: mockable.MaxTime, - EtnaTime: mockable.MaxTime, - }, - } - - switch f { - case etna: - c.UpgradeConfig.EtnaTime = defaultValidateStartTime.Add(-2 * time.Second) - fallthrough - case durango: - c.UpgradeConfig.DurangoTime = defaultValidateStartTime.Add(-2 * time.Second) - fallthrough - case cortina: - c.UpgradeConfig.CortinaTime = defaultValidateStartTime.Add(-2 * time.Second) - fallthrough - case banff: - c.UpgradeConfig.BanffTime = defaultValidateStartTime.Add(-2 * time.Second) - fallthrough - case apricotPhase5: - c.UpgradeConfig.ApricotPhase5Time = defaultValidateEndTime - fallthrough - case apricotPhase3: - c.UpgradeConfig.ApricotPhase3Time = defaultValidateEndTime - default: - require.FailNow(t, "unhandled fork", f) + UpgradeConfig: upgrades, } - - return c } -func defaultClock(f fork) *mockable.Clock { +func defaultClock(f upgradetest.Fork) *mockable.Clock { now := defaultGenesisTime - if f >= banff { + if f >= upgradetest.Banff { // 1 second after active fork now = defaultValidateEndTime.Add(-2 * time.Second) } diff --git a/vms/platformvm/txs/executor/import_test.go b/vms/platformvm/txs/executor/import_test.go index 2aa97c7fee91..ed9ff97375af 100644 --- a/vms/platformvm/txs/executor/import_test.go +++ b/vms/platformvm/txs/executor/import_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -27,7 +28,7 @@ import ( var fundedSharedMemoryCalls byte func TestNewImportTx(t *testing.T) { - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) type test struct { description string diff --git a/vms/platformvm/txs/executor/proposal_tx_executor_test.go b/vms/platformvm/txs/executor/proposal_tx_executor_test.go index ef80a06365f6..0efbae5e65ba 100644 --- a/vms/platformvm/txs/executor/proposal_tx_executor_test.go +++ b/vms/platformvm/txs/executor/proposal_tx_executor_test.go @@ -13,6 +13,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/hashing" "github.com/ava-labs/avalanchego/vms/platformvm/reward" @@ -109,7 +110,7 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { require.NoError(env.state.Commit()) } - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) currentTimestamp := env.state.GetTimestamp() type test struct { @@ -241,7 +242,7 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { for _, tt := range tests { t.Run(tt.description, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.config.UpgradeConfig.ApricotPhase3Time = tt.AP3Time builder, signer := env.factory.NewWallet(tt.feeKeys...) @@ -287,7 +288,7 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -808,7 +809,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { func TestProposalTxExecuteAddValidator(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() diff --git a/vms/platformvm/txs/executor/reward_validator_test.go b/vms/platformvm/txs/executor/reward_validator_test.go index 501d31fe4959..04dc3c27af9a 100644 --- a/vms/platformvm/txs/executor/reward_validator_test.go +++ b/vms/platformvm/txs/executor/reward_validator_test.go @@ -13,6 +13,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/snowtest" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/set" @@ -37,7 +38,7 @@ func newRewardValidatorTx(t testing.TB, txID ids.ID) (*txs.Tx, error) { func TestRewardValidatorTxExecuteOnCommit(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) dummyHeight := uint64(1) currentStakerIterator, err := env.state.GetCurrentStakerIterator() @@ -141,7 +142,7 @@ func TestRewardValidatorTxExecuteOnCommit(t *testing.T) { func TestRewardValidatorTxExecuteOnAbort(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) dummyHeight := uint64(1) currentStakerIterator, err := env.state.GetCurrentStakerIterator() @@ -239,7 +240,7 @@ func TestRewardValidatorTxExecuteOnAbort(t *testing.T) { func TestRewardDelegatorTxExecuteOnCommitPreDelegateeDeferral(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) dummyHeight := uint64(1) vdrRewardAddress := ids.GenerateTestShortID() @@ -373,7 +374,7 @@ func TestRewardDelegatorTxExecuteOnCommitPreDelegateeDeferral(t *testing.T) { func TestRewardDelegatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { require := require.New(t) - env := newEnvironment(t, cortina) + env := newEnvironment(t, upgradetest.Cortina) dummyHeight := uint64(1) vdrRewardAddress := ids.GenerateTestShortID() @@ -603,7 +604,7 @@ func TestRewardDelegatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { func TestRewardDelegatorTxAndValidatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { require := require.New(t) - env := newEnvironment(t, cortina) + env := newEnvironment(t, upgradetest.Cortina) dummyHeight := uint64(1) vdrRewardAddress := ids.GenerateTestShortID() @@ -776,7 +777,7 @@ func TestRewardDelegatorTxAndValidatorTxExecuteOnCommitPostDelegateeDeferral(t * func TestRewardDelegatorTxExecuteOnAbort(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) dummyHeight := uint64(1) initialSupply, err := env.state.GetCurrentSupply(constants.PrimaryNetworkID) diff --git a/vms/platformvm/txs/executor/staker_tx_verification_test.go b/vms/platformvm/txs/executor/staker_tx_verification_test.go index ee8ead112f93..aa8ea9319c81 100644 --- a/vms/platformvm/txs/executor/staker_tx_verification_test.go +++ b/vms/platformvm/txs/executor/staker_tx_verification_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/snowtest" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -22,6 +23,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/platformvm/utxo" "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) @@ -109,10 +111,13 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { name: "fail syntactic verification", backendF: func(*gomock.Controller) *Backend { return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, } }, + stateF: func(ctrl *gomock.Controller) state.Chain { mockState := state.NewMockChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now) @@ -130,8 +135,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { name: "not bootstrapped", backendF: func(*gomock.Controller) *Backend { return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: &utils.Atomic[bool]{}, } }, @@ -154,8 +161,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, cortina, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Cortina, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -178,8 +187,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -205,8 +216,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -232,8 +245,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -260,8 +275,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -291,8 +308,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -322,8 +341,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -355,8 +376,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -382,8 +405,10 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) return &Backend{ - Ctx: ctx, - Config: defaultTestConfig(t, durango, activeForkTime), + Ctx: ctx, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + }, Bootstrapped: bootstrapped, } }, @@ -424,12 +449,14 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { gomock.Any(), ).Return(ErrFlowCheckFailed) - cfg := defaultTestConfig(t, durango, activeForkTime) - cfg.StaticFeeConfig.AddSubnetValidatorFee = 1 - return &Backend{ - FlowChecker: flowChecker, - Config: cfg, + FlowChecker: flowChecker, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + StaticFeeConfig: fee.StaticConfig{ + AddSubnetValidatorFee: 1, + }, + }, Ctx: ctx, Bootstrapped: bootstrapped, } @@ -470,12 +497,14 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { gomock.Any(), ).Return(nil) - cfg := defaultTestConfig(t, durango, activeForkTime) - cfg.StaticFeeConfig.AddSubnetValidatorFee = 1 - return &Backend{ - FlowChecker: flowChecker, - Config: cfg, + FlowChecker: flowChecker, + Config: &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, activeForkTime), + StaticFeeConfig: fee.StaticConfig{ + AddSubnetValidatorFee: 1, + }, + }, Ctx: ctx, Bootstrapped: bootstrapped, } diff --git a/vms/platformvm/txs/executor/standard_tx_executor_test.go b/vms/platformvm/txs/executor/standard_tx_executor_test.go index d57955c08b39..7e7c2c3c0269 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor_test.go +++ b/vms/platformvm/txs/executor/standard_tx_executor_test.go @@ -17,13 +17,12 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "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/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/hashing" - "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" @@ -49,7 +48,7 @@ var errTest = errors.New("non-nil error") func TestStandardTxExecutorAddValidatorTxEmptyID(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -195,7 +194,7 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { require.NoError(env.state.Commit()) } - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) currentTimestamp := env.state.GetTimestamp() type test struct { @@ -327,7 +326,7 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { for _, tt := range tests { t.Run(tt.description, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.config.UpgradeConfig.ApricotPhase3Time = tt.AP3Time builder, signer := env.factory.NewWallet(tt.feeKeys...) @@ -371,7 +370,7 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { require := require.New(t) - env := newEnvironment(t, apricotPhase5) + env := newEnvironment(t, upgradetest.ApricotPhase5) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -894,7 +893,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { func TestBanffStandardTxExecutorAddValidator(t *testing.T) { require := require.New(t) - env := newEnvironment(t, banff) + env := newEnvironment(t, upgradetest.Banff) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -1152,7 +1151,7 @@ func TestDurangoDisabledTransactions(t *testing.T) { t.Run(tt.name, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, durango) + env := newEnvironment(t, upgradetest.Durango) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -1569,7 +1568,7 @@ func TestDurangoMemoField(t *testing.T) { t.Run(tt.name, func(t *testing.T) { require := require.New(t) - env := newEnvironment(t, durango) + env := newEnvironment(t, upgradetest.Durango) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -1601,7 +1600,7 @@ func TestDurangoMemoField(t *testing.T) { func TestEtnaDisabledTransactions(t *testing.T) { require := require.New(t) - env := newEnvironment(t, etna) + env := newEnvironment(t, upgradetest.Etna) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() @@ -1743,7 +1742,9 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env.state.EXPECT().DeleteUTXO(gomock.Any()).Times(len(env.unsignedTx.Ins)) env.state.EXPECT().AddUTXO(gomock.Any()).Times(len(env.unsignedTx.Outs)) - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -1771,7 +1772,9 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -1799,7 +1802,9 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(nil, database.ErrNotFound) env.state.EXPECT().GetPendingValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(nil, database.ErrNotFound) - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -1830,7 +1835,9 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(&staker, nil).Times(1) - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -1859,7 +1866,9 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -1887,7 +1896,9 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(nil, database.ErrNotFound) - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -1917,7 +1928,9 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil) env.fx.EXPECT().VerifyPermission(gomock.Any(), env.unsignedTx.SubnetAuth, env.tx.Creds[len(env.tx.Creds)-1], subnetOwner).Return(errTest) - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -1950,7 +1963,9 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), ).Return(errTest) - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -2108,7 +2123,9 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -2135,7 +2152,9 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() - cfg := defaultTestConfig(t, durango, env.latestForkTime) + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ Backend: &Backend{ @@ -2163,8 +2182,10 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() - cfg := defaultTestConfig(t, durango, env.latestForkTime) - cfg.MaxStakeDuration = math.MaxInt64 + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + MaxStakeDuration: math.MaxInt64, + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ @@ -2198,8 +2219,10 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), ).Return(ErrFlowCheckFailed) - cfg := defaultTestConfig(t, durango, env.latestForkTime) - cfg.MaxStakeDuration = math.MaxInt64 + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + MaxStakeDuration: math.MaxInt64, + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ @@ -2238,8 +2261,10 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env.state.EXPECT().DeleteUTXO(gomock.Any()).Times(len(env.unsignedTx.Ins)) env.state.EXPECT().AddUTXO(gomock.Any()).Times(len(env.unsignedTx.Outs)) - cfg := defaultTestConfig(t, durango, env.latestForkTime) - cfg.MaxStakeDuration = math.MaxInt64 + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + MaxStakeDuration: math.MaxInt64, + } feeCalculator := state.PickFeeCalculator(cfg, env.state) e := &StandardTxExecutor{ @@ -2271,40 +2296,3 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { }) } } - -func defaultTestConfig(t *testing.T, f fork, tm time.Time) *config.Config { - c := &config.Config{ - UpgradeConfig: upgrade.Config{ - ApricotPhase3Time: mockable.MaxTime, - ApricotPhase5Time: mockable.MaxTime, - BanffTime: mockable.MaxTime, - CortinaTime: mockable.MaxTime, - DurangoTime: mockable.MaxTime, - EtnaTime: mockable.MaxTime, - }, - } - - switch f { - case etna: - c.UpgradeConfig.EtnaTime = tm - fallthrough - case durango: - c.UpgradeConfig.DurangoTime = tm - fallthrough - case cortina: - c.UpgradeConfig.CortinaTime = tm - fallthrough - case banff: - c.UpgradeConfig.BanffTime = tm - fallthrough - case apricotPhase5: - c.UpgradeConfig.ApricotPhase5Time = tm - fallthrough - case apricotPhase3: - c.UpgradeConfig.ApricotPhase3Time = tm - default: - require.FailNow(t, "unhandled fork", f) - } - - return c -} diff --git a/vms/platformvm/validator_set_property_test.go b/vms/platformvm/validator_set_property_test.go index 3411fb7e1d72..3935b75416a9 100644 --- a/vms/platformvm/validator_set_property_test.go +++ b/vms/platformvm/validator_set_property_test.go @@ -29,7 +29,7 @@ import ( "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/formatting" @@ -645,7 +645,6 @@ func TestTimestampListGenerator(t *testing.T) { // add a single validator at the end of times, // to make sure it won't pollute our tests func buildVM(t *testing.T) (*VM, ids.ID, error) { - forkTime := defaultGenesisTime vm := &VM{Config: config.Config{ Chains: chains.TestManager, UptimeLockedCalculator: uptime.NewLockedCalculator(), @@ -663,15 +662,9 @@ func buildVM(t *testing.T) (*VM, ids.ID, error) { MinStakeDuration: defaultMinStakingDuration, MaxStakeDuration: defaultMaxStakingDuration, RewardConfig: defaultRewardConfig, - UpgradeConfig: upgrade.Config{ - ApricotPhase3Time: forkTime, - ApricotPhase5Time: forkTime, - BanffTime: forkTime, - CortinaTime: forkTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, defaultGenesisTime), }} - vm.clock.Set(forkTime.Add(time.Second)) + vm.clock.Set(defaultGenesisTime.Add(time.Second)) baseDB := memdb.New() chainDB := prefixdb.New([]byte{0}, baseDB) diff --git a/vms/platformvm/vm_regression_test.go b/vms/platformvm/vm_regression_test.go index b967dfd6632f..3146a8372518 100644 --- a/vms/platformvm/vm_regression_test.go +++ b/vms/platformvm/vm_regression_test.go @@ -27,12 +27,11 @@ import ( "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/bloom" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/block" @@ -53,7 +52,7 @@ import ( func TestAddDelegatorTxOverDelegatedRegression(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -258,7 +257,7 @@ func TestAddDelegatorTxHeapCorruption(t *testing.T) { t.Run(test.name, func(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, apricotPhase3) + vm, factory, _, _ := defaultVM(t, upgradetest.ApricotPhase3) vm.UpgradeConfig.ApricotPhase3Time = test.ap3Time vm.ctx.Lock.Lock() @@ -456,12 +455,7 @@ func TestUnverifiedParentPanicRegression(t *testing.T) { MinStakeDuration: defaultMinStakingDuration, MaxStakeDuration: defaultMaxStakingDuration, RewardConfig: defaultRewardConfig, - UpgradeConfig: upgrade.Config{ - BanffTime: latestForkTime, - CortinaTime: mockable.MaxTime, - DurangoTime: mockable.MaxTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Banff, latestForkTime), }} ctx := snowtest.Context(t, snowtest.PChainID) @@ -600,7 +594,7 @@ func TestUnverifiedParentPanicRegression(t *testing.T) { func TestRejectedStateRegressionInvalidValidatorTimestamp(t *testing.T) { require := require.New(t) - vm, factory, baseDB, mutableSharedMemory := defaultVM(t, cortina) + vm, factory, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -799,7 +793,7 @@ func TestRejectedStateRegressionInvalidValidatorTimestamp(t *testing.T) { func TestRejectedStateRegressionInvalidValidatorReward(t *testing.T) { require := require.New(t) - vm, factory, baseDB, mutableSharedMemory := defaultVM(t, cortina) + vm, factory, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1111,7 +1105,7 @@ func TestRejectedStateRegressionInvalidValidatorReward(t *testing.T) { func TestValidatorSetAtCacheOverwriteRegression(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1253,7 +1247,7 @@ func TestAddDelegatorTxAddBeforeRemove(t *testing.T) { delegator2EndTime := delegator2StartTime.Add(3 * defaultMinStakingDuration) delegator2Stake := defaultMaxValidatorStake - validatorStake - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1367,7 +1361,7 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionNotTracked(t validatorStartTime := latestForkTime.Add(executor.SyncBound).Add(1 * time.Second) validatorEndTime := validatorStartTime.Add(360 * 24 * time.Hour) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1516,7 +1510,7 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t validatorStartTime := latestForkTime.Add(executor.SyncBound).Add(1 * time.Second) validatorEndTime := validatorStartTime.Add(360 * 24 * time.Hour) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1648,7 +1642,7 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { // setup require := require.New(t) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1913,7 +1907,7 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { // setup require := require.New(t) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -2069,7 +2063,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { // setup require := require.New(t) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -2288,7 +2282,7 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { // setup require := require.New(t) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -2426,7 +2420,7 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { func TestValidatorSetRaceCondition(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, cortina) + vm, _, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() diff --git a/vms/platformvm/vm_test.go b/vms/platformvm/vm_test.go index 939112c03242..4175c0346c70 100644 --- a/vms/platformvm/vm_test.go +++ b/vms/platformvm/vm_test.go @@ -36,7 +36,7 @@ import ( "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/subnets" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" @@ -48,7 +48,6 @@ import ( "github.com/ava-labs/avalanchego/utils/resource" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/timer" - "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/vms/components/avax" @@ -77,18 +76,7 @@ import ( walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) -const ( - apricotPhase3 fork = iota - apricotPhase5 - banff - cortina - durango - etna - - latestFork = durango - - defaultWeight uint64 = 10000 -) +const defaultWeight uint64 = 10000 var ( defaultMinStakingDuration = 24 * time.Hour @@ -162,8 +150,6 @@ func init() { } } -type fork uint8 - type mutableSharedMemory struct { atomic.SharedMemory } @@ -228,42 +214,12 @@ func defaultGenesis(t *testing.T, avaxAssetID ids.ID) (*api.BuildGenesisArgs, [] return &buildGenesisArgs, genesisBytes } -func defaultVM(t *testing.T, f fork) (*VM, *txstest.WalletFactory, database.Database, *mutableSharedMemory) { +func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, database.Database, *mutableSharedMemory) { require := require.New(t) - var ( - apricotPhase3Time = mockable.MaxTime - apricotPhase5Time = mockable.MaxTime - banffTime = mockable.MaxTime - cortinaTime = mockable.MaxTime - durangoTime = mockable.MaxTime - etnaTime = mockable.MaxTime - ) // always reset latestForkTime (a package level variable) // to ensure test independence latestForkTime = defaultGenesisTime.Add(time.Second) - switch f { - case etna: - etnaTime = latestForkTime - fallthrough - case durango: - durangoTime = latestForkTime - fallthrough - case cortina: - cortinaTime = latestForkTime - fallthrough - case banff: - banffTime = latestForkTime - fallthrough - case apricotPhase5: - apricotPhase5Time = latestForkTime - fallthrough - case apricotPhase3: - apricotPhase3Time = latestForkTime - default: - require.FailNow("unhandled fork", f) - } - vm := &VM{Config: config.Config{ Chains: chains.TestManager, UptimeLockedCalculator: uptime.NewLockedCalculator(), @@ -277,14 +233,7 @@ func defaultVM(t *testing.T, f fork) (*VM, *txstest.WalletFactory, database.Data MinStakeDuration: defaultMinStakingDuration, MaxStakeDuration: defaultMaxStakingDuration, RewardConfig: defaultRewardConfig, - UpgradeConfig: upgrade.Config{ - ApricotPhase3Time: apricotPhase3Time, - ApricotPhase5Time: apricotPhase5Time, - BanffTime: banffTime, - CortinaTime: cortinaTime, - DurangoTime: durangoTime, - EtnaTime: etnaTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(f, latestForkTime), }} db := memdb.New() @@ -381,7 +330,7 @@ func defaultVM(t *testing.T, f fork) (*VM, *txstest.WalletFactory, database.Data // Ensure genesis state is parsed from bytes and stored correctly func TestGenesis(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, latestFork) + vm, _, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -435,7 +384,7 @@ func TestGenesis(t *testing.T) { // accept proposal to add validator to primary network func TestAddValidatorCommit(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -500,7 +449,7 @@ func TestAddValidatorCommit(t *testing.T) { // verify invalid attempt to add validator to primary network func TestInvalidAddValidatorCommit(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -556,7 +505,7 @@ func TestInvalidAddValidatorCommit(t *testing.T) { // Reject attempt to add validator to primary network func TestAddValidatorReject(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, cortina) + vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -607,7 +556,7 @@ func TestAddValidatorReject(t *testing.T) { // Reject proposal to add validator to primary network func TestAddValidatorInvalidNotReissued(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -658,7 +607,7 @@ func TestAddValidatorInvalidNotReissued(t *testing.T) { // Accept proposal to add validator to subnet func TestAddSubnetValidatorAccept(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -710,7 +659,7 @@ func TestAddSubnetValidatorAccept(t *testing.T) { // Reject proposal to add validator to subnet func TestAddSubnetValidatorReject(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -761,7 +710,7 @@ func TestAddSubnetValidatorReject(t *testing.T) { // Test case where primary network validator rewarded func TestRewardValidatorAccept(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, latestFork) + vm, _, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -829,7 +778,7 @@ func TestRewardValidatorAccept(t *testing.T) { // Test case where primary network validator not rewarded func TestRewardValidatorReject(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, latestFork) + vm, _, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -899,7 +848,7 @@ func TestRewardValidatorReject(t *testing.T) { // Ensure BuildBlock errors when there is no block to build func TestUnneededBuildBlock(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, latestFork) + vm, _, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -910,7 +859,7 @@ func TestUnneededBuildBlock(t *testing.T) { // test acceptance of proposal to create a new chain func TestCreateChain(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -960,7 +909,7 @@ func TestCreateChain(t *testing.T) { // 3) Advance timestamp to validator's end time (removing validator from current) func TestCreateSubnet(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1062,7 +1011,7 @@ func TestCreateSubnet(t *testing.T) { // test asset import func TestAtomicImport(t *testing.T) { require := require.New(t) - vm, factory, baseDB, mutableSharedMemory := defaultVM(t, latestFork) + vm, factory, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1154,7 +1103,7 @@ func TestAtomicImport(t *testing.T) { // test optimistic asset import func TestOptimisticAtomicImport(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, apricotPhase3) + vm, _, _, _ := defaultVM(t, upgradetest.ApricotPhase3) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1221,12 +1170,7 @@ func TestRestartFullyAccepted(t *testing.T) { MinStakeDuration: defaultMinStakingDuration, MaxStakeDuration: defaultMaxStakingDuration, RewardConfig: defaultRewardConfig, - UpgradeConfig: upgrade.Config{ - BanffTime: latestForkTime, - CortinaTime: latestForkTime, - DurangoTime: latestForkTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, latestForkTime), }} firstCtx := snowtest.Context(t, snowtest.PChainID) @@ -1311,12 +1255,7 @@ func TestRestartFullyAccepted(t *testing.T) { MinStakeDuration: defaultMinStakingDuration, MaxStakeDuration: defaultMaxStakingDuration, RewardConfig: defaultRewardConfig, - UpgradeConfig: upgrade.Config{ - BanffTime: latestForkTime, - CortinaTime: latestForkTime, - DurangoTime: latestForkTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, latestForkTime), }} secondCtx := snowtest.Context(t, snowtest.PChainID) @@ -1362,12 +1301,7 @@ func TestBootstrapPartiallyAccepted(t *testing.T) { MinStakeDuration: defaultMinStakingDuration, MaxStakeDuration: defaultMaxStakingDuration, RewardConfig: defaultRewardConfig, - UpgradeConfig: upgrade.Config{ - BanffTime: latestForkTime, - CortinaTime: latestForkTime, - DurangoTime: latestForkTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, latestForkTime), }} initialClkTime := latestForkTime.Add(time.Second) @@ -1713,12 +1647,7 @@ func TestUnverifiedParent(t *testing.T) { MinStakeDuration: defaultMinStakingDuration, MaxStakeDuration: defaultMaxStakingDuration, RewardConfig: defaultRewardConfig, - UpgradeConfig: upgrade.Config{ - BanffTime: latestForkTime, - CortinaTime: latestForkTime, - DurangoTime: latestForkTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, latestForkTime), }} initialClkTime := latestForkTime.Add(time.Second) @@ -1817,7 +1746,7 @@ func TestUnverifiedParent(t *testing.T) { } func TestMaxStakeAmount(t *testing.T) { - vm, _, _, _ := defaultVM(t, latestFork) + vm, _, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1876,12 +1805,7 @@ func TestUptimeDisallowedWithRestart(t *testing.T) { RewardConfig: defaultRewardConfig, Validators: validators.NewManager(), UptimeLockedCalculator: uptime.NewLockedCalculator(), - UpgradeConfig: upgrade.Config{ - BanffTime: latestForkTime, - CortinaTime: latestForkTime, - DurangoTime: latestForkTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, latestForkTime), }} firstCtx := snowtest.Context(t, snowtest.PChainID) @@ -1927,12 +1851,7 @@ func TestUptimeDisallowedWithRestart(t *testing.T) { UptimePercentage: secondUptimePercentage / 100., Validators: validators.NewManager(), UptimeLockedCalculator: uptime.NewLockedCalculator(), - UpgradeConfig: upgrade.Config{ - BanffTime: latestForkTime, - CortinaTime: latestForkTime, - DurangoTime: latestForkTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, latestForkTime), }} secondCtx := snowtest.Context(t, snowtest.PChainID) @@ -2029,12 +1948,7 @@ func TestUptimeDisallowedAfterNeverConnecting(t *testing.T) { RewardConfig: defaultRewardConfig, Validators: validators.NewManager(), UptimeLockedCalculator: uptime.NewLockedCalculator(), - UpgradeConfig: upgrade.Config{ - BanffTime: latestForkTime, - CortinaTime: latestForkTime, - DurangoTime: latestForkTime, - EtnaTime: mockable.MaxTime, - }, + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, latestForkTime), }} ctx := snowtest.Context(t, snowtest.PChainID) @@ -2130,7 +2044,7 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { validatorStartTime := latestForkTime.Add(txexecutor.SyncBound).Add(1 * time.Second) validatorEndTime := validatorStartTime.Add(360 * 24 * time.Hour) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -2266,7 +2180,7 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { func TestTransferSubnetOwnershipTx(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -2355,7 +2269,7 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { func TestBaseTx(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -2441,7 +2355,7 @@ func TestBaseTx(t *testing.T) { func TestPruneMempool(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, latestFork) + vm, factory, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() diff --git a/vms/proposervm/block_test.go b/vms/proposervm/block_test.go index 6c04c5d13948..4603a30f40d4 100644 --- a/vms/proposervm/block_test.go +++ b/vms/proposervm/block_test.go @@ -23,7 +23,7 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/staking" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/vms/proposervm/proposer" @@ -72,11 +72,7 @@ func TestPostForkCommonComponents_buildChild(t *testing.T) { require.NoError(err) vm := &VM{ Config: Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: time.Unix(0, 0), - }, + Upgrades: upgradetest.GetConfig(upgradetest.Latest), StakingCertLeaf: &staking.Certificate{}, StakingLeafSigner: pk, Registerer: prometheus.NewRegistry(), @@ -388,11 +384,7 @@ func TestPostDurangoBuildChildResetScheduler(t *testing.T) { require.NoError(err) vm := &VM{ Config: Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: time.Unix(0, 0), - }, + Upgrades: upgradetest.GetConfig(upgradetest.Latest), StakingCertLeaf: &staking.Certificate{}, StakingLeafSigner: pk, Registerer: prometheus.NewRegistry(), diff --git a/vms/proposervm/post_fork_option_test.go b/vms/proposervm/post_fork_option_test.go index 3a76bc9faa06..0cce5076449f 100644 --- a/vms/proposervm/post_fork_option_test.go +++ b/vms/proposervm/post_fork_option_test.go @@ -19,7 +19,7 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/snowtest" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/vms/proposervm/block" ) @@ -528,11 +528,7 @@ func TestOptionTimestampValidity(t *testing.T) { proVM = New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: time.Unix(0, 0), - }, + Upgrades: upgradetest.GetConfig(upgradetest.Latest), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, diff --git a/vms/proposervm/state_syncable_vm_test.go b/vms/proposervm/state_syncable_vm_test.go index 1017c35d8a40..41f699790934 100644 --- a/vms/proposervm/state_syncable_vm_test.go +++ b/vms/proposervm/state_syncable_vm_test.go @@ -6,7 +6,6 @@ package proposervm import ( "context" "testing" - "time" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" @@ -23,7 +22,7 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/snowman/block" "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/snowtest" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/vms/proposervm/summary" statelessblock "github.com/ava-labs/avalanchego/vms/proposervm/block" @@ -61,11 +60,7 @@ func helperBuildStateSyncTestObjects(t *testing.T) (*fullVM, *VM) { vm := New( innerVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: time.Unix(0, 0), - }, + Upgrades: upgradetest.GetConfig(upgradetest.Latest), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, diff --git a/vms/proposervm/vm_test.go b/vms/proposervm/vm_test.go index e5d5f142281c..a689e7d32013 100644 --- a/vms/proposervm/vm_test.go +++ b/vms/proposervm/vm_test.go @@ -32,6 +32,7 @@ import ( "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/staking" "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -808,11 +809,7 @@ func TestExpiredBuildBlock(t *testing.T) { proVM := New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Time{}, - ApricotPhase4MinPChainHeight: 0, - DurangoTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfigWithUpgradeTime(upgradetest.ApricotPhase4, time.Time{}), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -1128,11 +1125,7 @@ func TestInnerVMRollback(t *testing.T) { proVM := New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Time{}, - ApricotPhase4MinPChainHeight: 0, - DurangoTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfigWithUpgradeTime(upgradetest.ApricotPhase4, time.Time{}), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -1210,11 +1203,7 @@ func TestInnerVMRollback(t *testing.T) { proVM = New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Time{}, - ApricotPhase4MinPChainHeight: 0, - DurangoTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfigWithUpgradeTime(upgradetest.ApricotPhase4, time.Time{}), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -1600,11 +1589,7 @@ func TestRejectedHeightNotIndexed(t *testing.T) { proVM := New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: time.Unix(0, 0), - }, + Upgrades: upgradetest.GetConfigWithUpgradeTime(upgradetest.Latest, time.Time{}), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -1773,11 +1758,7 @@ func TestRejectedOptionHeightNotIndexed(t *testing.T) { proVM := New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: time.Unix(0, 0), - }, + Upgrades: upgradetest.GetConfigWithUpgradeTime(upgradetest.Latest, time.Time{}), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -1910,11 +1891,7 @@ func TestVMInnerBlkCache(t *testing.T) { vm := New( innerVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: time.Unix(0, 0), - }, + Upgrades: upgradetest.GetConfig(upgradetest.Latest), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -2022,11 +1999,7 @@ func TestVM_VerifyBlockWithContext(t *testing.T) { vm := New( innerVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: time.Unix(0, 0), - }, + Upgrades: upgradetest.GetConfig(upgradetest.Latest), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -2226,11 +2199,7 @@ func TestHistoricalBlockDeletion(t *testing.T) { proVM := New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Unix(0, 0), - ApricotPhase4MinPChainHeight: 0, - DurangoTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfigWithUpgradeTime(upgradetest.ApricotPhase4, time.Time{}), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: DefaultNumHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -2320,11 +2289,7 @@ func TestHistoricalBlockDeletion(t *testing.T) { proVM = New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Time{}, - ApricotPhase4MinPChainHeight: 0, - DurangoTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfigWithUpgradeTime(upgradetest.ApricotPhase4, time.Time{}), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: numHistoricalBlocks, StakingLeafSigner: pTestSigner, @@ -2367,11 +2332,7 @@ func TestHistoricalBlockDeletion(t *testing.T) { proVM = New( coreVM, Config{ - Upgrades: upgrade.Config{ - ApricotPhase4Time: time.Time{}, - ApricotPhase4MinPChainHeight: 0, - DurangoTime: mockable.MaxTime, - }, + Upgrades: upgradetest.GetConfigWithUpgradeTime(upgradetest.ApricotPhase4, time.Time{}), MinBlkDelay: DefaultMinBlockDelay, NumHistoricalBlocks: newNumHistoricalBlocks, StakingLeafSigner: pTestSigner, From ac87871316b340c6b2c4d5b4b72d2b734afdfc0a Mon Sep 17 00:00:00 2001 From: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> Date: Mon, 19 Aug 2024 12:32:43 -0400 Subject: [PATCH 25/69] Restrict `Owner` usage after a Subnet manager is set (#3147) Signed-off-by: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> --- .../txs/executor/create_chain_test.go | 37 +++++++ .../txs/executor/staker_tx_verification.go | 11 ++ .../txs/executor/standard_tx_executor_test.go | 101 ++++++++++++++++++ .../txs/executor/subnet_tx_verification.go | 8 ++ 4 files changed, 157 insertions(+) diff --git a/vms/platformvm/txs/executor/create_chain_test.go b/vms/platformvm/txs/executor/create_chain_test.go index f8b29b9c275d..a1ad4c81e186 100644 --- a/vms/platformvm/txs/executor/create_chain_test.go +++ b/vms/platformvm/txs/executor/create_chain_test.go @@ -253,3 +253,40 @@ func TestCreateChainTxAP3FeeChange(t *testing.T) { }) } } + +func TestEtnaCreateChainTxInvalidWithManagedSubnet(t *testing.T) { + require := require.New(t) + env := newEnvironment(t, upgradetest.Etna) + env.ctx.Lock.Lock() + defer env.ctx.Lock.Unlock() + + builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) + utx, err := builder.NewCreateChainTx( + testSubnet1.ID(), + nil, + constants.AVMID, + nil, + "chain name", + ) + require.NoError(err) + tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) + require.NoError(err) + + stateDiff, err := state.NewDiff(lastAcceptedID, env) + require.NoError(err) + + builderDiff, err := state.NewDiffOn(stateDiff) + require.NoError(err) + + stateDiff.SetSubnetManager(testSubnet1.ID(), ids.GenerateTestID(), []byte{'a', 'd', 'd', 'r', 'e', 's', 's'}) + + feeCalculator := state.PickFeeCalculator(env.config, builderDiff) + executor := StandardTxExecutor{ + Backend: &env.backend, + FeeCalculator: feeCalculator, + State: stateDiff, + Tx: tx, + } + err = tx.Unsigned.Visit(&executor) + require.ErrorIs(err, errIsImmutable) +} diff --git a/vms/platformvm/txs/executor/staker_tx_verification.go b/vms/platformvm/txs/executor/staker_tx_verification.go index b84ad9d6e2b1..d458c01ab259 100644 --- a/vms/platformvm/txs/executor/staker_tx_verification.go +++ b/vms/platformvm/txs/executor/staker_tx_verification.go @@ -41,6 +41,7 @@ var ( ErrDurangoUpgradeNotActive = errors.New("attempting to use a Durango-upgrade feature prior to activation") ErrAddValidatorTxPostDurango = errors.New("AddValidatorTx is not permitted post-Durango") ErrAddDelegatorTxPostDurango = errors.New("AddDelegatorTx is not permitted post-Durango") + ErrRemoveValidatorManagedSubnet = errors.New("RemoveSubnetValidatorTx cannot be used to remove a validator from a Subnet with a manager") ) // verifySubnetValidatorPrimaryNetworkRequirements verifies the primary @@ -306,6 +307,16 @@ func verifyRemoveSubnetValidatorTx( return nil, false, err } + if backend.Config.UpgradeConfig.IsEtnaActivated(currentTimestamp) { + _, _, err := chainState.GetSubnetManager(tx.Subnet) + if err == nil { + return nil, false, fmt.Errorf("%w: %q", ErrRemoveValidatorManagedSubnet, tx.Subnet) + } + if err != database.ErrNotFound { + return nil, false, err + } + } + isCurrentValidator := true vdr, err := chainState.GetCurrentValidator(tx.Subnet, tx.NodeID) if err == database.ErrNotFound { diff --git a/vms/platformvm/txs/executor/standard_tx_executor_test.go b/vms/platformvm/txs/executor/standard_tx_executor_test.go index 7e7c2c3c0269..d2a0010f87c5 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor_test.go +++ b/vms/platformvm/txs/executor/standard_tx_executor_test.go @@ -891,6 +891,44 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { } } +func TestEtnaStandardTxExecutorAddSubnetValidator(t *testing.T) { + require := require.New(t) + env := newEnvironment(t, upgradetest.Etna) + env.ctx.Lock.Lock() + defer env.ctx.Lock.Unlock() + + nodeID := genesisNodeIDs[0] + + builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) + utx, err := builder.NewAddSubnetValidatorTx( + &txs.SubnetValidator{ + Validator: txs.Validator{ + NodeID: nodeID, + Start: uint64(defaultValidateStartTime.Unix() + 1), + End: uint64(defaultValidateEndTime.Unix()), + Wght: defaultWeight, + }, + Subnet: testSubnet1.ID(), + }, + ) + require.NoError(err) + tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) + require.NoError(err) + + onAcceptState, err := state.NewDiff(lastAcceptedID, env) + require.NoError(err) + + onAcceptState.SetSubnetManager(testSubnet1.ID(), ids.GenerateTestID(), []byte{'a', 'd', 'd', 'r', 'e', 's', 's'}) + + executor := StandardTxExecutor{ + Backend: &env.backend, + State: onAcceptState, + Tx: tx, + } + err = tx.Unsigned.Visit(&executor) + require.ErrorIs(err, errIsImmutable) +} + func TestBanffStandardTxExecutorAddValidator(t *testing.T) { require := require.New(t) env := newEnvironment(t, upgradetest.Banff) @@ -1984,6 +2022,32 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { }, expectedErr: ErrFlowCheckFailed, }, + { + name: "attempted to remove subnet validator after subnet manager is set", + newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { + env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) + env.state.EXPECT().GetSubnetManager(env.unsignedTx.Subnet).Return(ids.GenerateTestID(), []byte{'a', 'd', 'd', 'r', 'e', 's', 's'}, nil).AnyTimes() + env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() + + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Etna, env.latestForkTime), + } + e := &StandardTxExecutor{ + Backend: &Backend{ + Config: cfg, + Bootstrapped: &utils.Atomic[bool]{}, + Fx: env.fx, + FlowChecker: env.flowChecker, + Ctx: &snow.Context{}, + }, + Tx: env.tx, + State: env.state, + } + e.Bootstrapped.Set(true) + return env.unsignedTx, e + }, + expectedErr: ErrRemoveValidatorManagedSubnet, + }, } for _, tt := range tests { @@ -2213,6 +2277,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { subnetOwner := fx.NewMockOwner(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil) + env.state.EXPECT().GetSubnetManager(env.unsignedTx.Subnet).Return(ids.Empty, nil, database.ErrNotFound).Times(1) env.state.EXPECT().GetSubnetTransformation(env.unsignedTx.Subnet).Return(nil, database.ErrNotFound).Times(1) env.fx.EXPECT().VerifyPermission(gomock.Any(), env.unsignedTx.SubnetAuth, env.tx.Creds[len(env.tx.Creds)-1], subnetOwner).Return(nil) env.flowChecker.EXPECT().VerifySpend( @@ -2242,6 +2307,41 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { }, err: ErrFlowCheckFailed, }, + { + name: "invalid if subnet manager is set", + newExecutor: func(ctrl *gomock.Controller) (*txs.TransformSubnetTx, *StandardTxExecutor) { + env := newValidTransformSubnetTxVerifyEnv(t, ctrl) + + // Set dependency expectations. + subnetOwner := fx.NewMockOwner(ctrl) + env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() + env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil).Times(1) + env.state.EXPECT().GetSubnetManager(env.unsignedTx.Subnet).Return(ids.GenerateTestID(), make([]byte, 20), nil) + env.state.EXPECT().GetSubnetTransformation(env.unsignedTx.Subnet).Return(nil, database.ErrNotFound).Times(1) + env.fx.EXPECT().VerifyPermission(env.unsignedTx, env.unsignedTx.SubnetAuth, env.tx.Creds[len(env.tx.Creds)-1], subnetOwner).Return(nil).Times(1) + + cfg := &config.Config{ + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, env.latestForkTime), + MaxStakeDuration: math.MaxInt64, + } + feeCalculator := state.PickFeeCalculator(cfg, env.state) + e := &StandardTxExecutor{ + Backend: &Backend{ + Config: cfg, + Bootstrapped: &utils.Atomic[bool]{}, + Fx: env.fx, + FlowChecker: env.flowChecker, + Ctx: &snow.Context{}, + }, + FeeCalculator: feeCalculator, + Tx: env.tx, + State: env.state, + } + e.Bootstrapped.Set(true) + return env.unsignedTx, e + }, + err: errIsImmutable, + }, { name: "valid tx", newExecutor: func(ctrl *gomock.Controller) (*txs.TransformSubnetTx, *StandardTxExecutor) { @@ -2251,6 +2351,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { subnetOwner := fx.NewMockOwner(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil).Times(1) + env.state.EXPECT().GetSubnetManager(env.unsignedTx.Subnet).Return(ids.Empty, nil, database.ErrNotFound).Times(1) env.state.EXPECT().GetSubnetTransformation(env.unsignedTx.Subnet).Return(nil, database.ErrNotFound).Times(1) env.fx.EXPECT().VerifyPermission(env.unsignedTx, env.unsignedTx.SubnetAuth, env.tx.Creds[len(env.tx.Creds)-1], subnetOwner).Return(nil).Times(1) env.flowChecker.EXPECT().VerifySpend( diff --git a/vms/platformvm/txs/executor/subnet_tx_verification.go b/vms/platformvm/txs/executor/subnet_tx_verification.go index f1a75f6f2f3f..6e5ecb9a34f5 100644 --- a/vms/platformvm/txs/executor/subnet_tx_verification.go +++ b/vms/platformvm/txs/executor/subnet_tx_verification.go @@ -43,6 +43,14 @@ func verifyPoASubnetAuthorization( return nil, err } + _, _, err = chainState.GetSubnetManager(subnetID) + if err == nil { + return nil, fmt.Errorf("%q %w", subnetID, errIsImmutable) + } + if err != database.ErrNotFound { + return nil, err + } + return creds, nil } From eea2b00bd34f9e58a5c1a66d57a2069a7c2e214f Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Mon, 19 Aug 2024 12:48:31 -0400 Subject: [PATCH 26/69] SoV networking support (#2951) --- message/mock_outbound_message_builder.go | 16 +- message/outbound_msg_builder.go | 8 +- network/README.md | 144 +- network/ip_tracker.go | 547 +++++--- network/ip_tracker_test.go | 1517 ++++++++++++++-------- network/network.go | 91 +- network/peer/config.go | 1 + network/peer/network.go | 3 + network/peer/peer.go | 13 +- network/peer/peer_test.go | 12 +- network/peer/test_network.go | 9 +- proto/p2p/p2p.proto | 4 + proto/pb/p2p/p2p.pb.go | 378 +++--- 13 files changed, 1757 insertions(+), 986 deletions(-) diff --git a/message/mock_outbound_message_builder.go b/message/mock_outbound_message_builder.go index 917d764028fe..1422230961e4 100644 --- a/message/mock_outbound_message_builder.go +++ b/message/mock_outbound_message_builder.go @@ -254,18 +254,18 @@ func (mr *MockOutboundMsgBuilderMockRecorder) GetAncestors(arg0, arg1, arg2, arg } // GetPeerList mocks base method. -func (m *MockOutboundMsgBuilder) GetPeerList(arg0, arg1 []byte) (OutboundMessage, error) { +func (m *MockOutboundMsgBuilder) GetPeerList(arg0, arg1 []byte, arg2 bool) (OutboundMessage, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPeerList", arg0, arg1) + ret := m.ctrl.Call(m, "GetPeerList", arg0, arg1, arg2) ret0, _ := ret[0].(OutboundMessage) ret1, _ := ret[1].(error) return ret0, ret1 } // GetPeerList indicates an expected call of GetPeerList. -func (mr *MockOutboundMsgBuilderMockRecorder) GetPeerList(arg0, arg1 any) *gomock.Call { +func (mr *MockOutboundMsgBuilderMockRecorder) GetPeerList(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPeerList", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).GetPeerList), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPeerList", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).GetPeerList), arg0, arg1, arg2) } // GetStateSummaryFrontier mocks base method. @@ -284,18 +284,18 @@ func (mr *MockOutboundMsgBuilderMockRecorder) GetStateSummaryFrontier(arg0, arg1 } // Handshake mocks base method. -func (m *MockOutboundMsgBuilder) Handshake(arg0 uint32, arg1 uint64, arg2 netip.AddrPort, arg3 string, arg4, arg5, arg6 uint32, arg7 uint64, arg8, arg9 []byte, arg10 []ids.ID, arg11, arg12 []uint32, arg13, arg14 []byte) (OutboundMessage, error) { +func (m *MockOutboundMsgBuilder) Handshake(arg0 uint32, arg1 uint64, arg2 netip.AddrPort, arg3 string, arg4, arg5, arg6 uint32, arg7 uint64, arg8, arg9 []byte, arg10 []ids.ID, arg11, arg12 []uint32, arg13, arg14 []byte, arg15 bool) (OutboundMessage, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Handshake", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14) + ret := m.ctrl.Call(m, "Handshake", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) ret0, _ := ret[0].(OutboundMessage) ret1, _ := ret[1].(error) return ret0, ret1 } // Handshake indicates an expected call of Handshake. -func (mr *MockOutboundMsgBuilderMockRecorder) Handshake(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14 any) *gomock.Call { +func (mr *MockOutboundMsgBuilderMockRecorder) Handshake(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Handshake", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Handshake), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Handshake", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Handshake), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) } // PeerList mocks base method. diff --git a/message/outbound_msg_builder.go b/message/outbound_msg_builder.go index 78aacdce3e08..296e77446153 100644 --- a/message/outbound_msg_builder.go +++ b/message/outbound_msg_builder.go @@ -35,11 +35,13 @@ type OutboundMsgBuilder interface { objectedACPs []uint32, knownPeersFilter []byte, knownPeersSalt []byte, + requestAllSubnetIPs bool, ) (OutboundMessage, error) GetPeerList( knownPeersFilter []byte, knownPeersSalt []byte, + requestAllSubnetIPs bool, ) (OutboundMessage, error) PeerList( @@ -242,6 +244,7 @@ func (b *outMsgBuilder) Handshake( objectedACPs []uint32, knownPeersFilter []byte, knownPeersSalt []byte, + requestAllSubnetIPs bool, ) (OutboundMessage, error) { subnetIDBytes := make([][]byte, len(trackedSubnets)) encodeIDs(trackedSubnets, subnetIDBytes) @@ -270,7 +273,8 @@ func (b *outMsgBuilder) Handshake( Filter: knownPeersFilter, Salt: knownPeersSalt, }, - IpBlsSig: ipBLSSig, + IpBlsSig: ipBLSSig, + AllSubnets: requestAllSubnetIPs, }, }, }, @@ -282,6 +286,7 @@ func (b *outMsgBuilder) Handshake( func (b *outMsgBuilder) GetPeerList( knownPeersFilter []byte, knownPeersSalt []byte, + requestAllSubnetIPs bool, ) (OutboundMessage, error) { return b.builder.createOutbound( &p2p.Message{ @@ -291,6 +296,7 @@ func (b *outMsgBuilder) GetPeerList( Filter: knownPeersFilter, Salt: knownPeersSalt, }, + AllSubnets: requestAllSubnetIPs, }, }, }, diff --git a/network/README.md b/network/README.md index b4a6a01d648b..3d3341050e60 100644 --- a/network/README.md +++ b/network/README.md @@ -16,6 +16,7 @@ - [Bloom Filter](#bloom-filter) - [GetPeerList](#getpeerlist) - [PeerList](#peerlist) + - [Avoiding Persistent Network Traffic](#avoiding-persistent-network-traffic) ## Overview @@ -33,15 +34,15 @@ Peers communicate by enqueuing messages between one another. Each peer on either ```mermaid sequenceDiagram - actor Alice - actor Bob + actor Morty + actor Rick loop - Alice->>Bob: Write outbound messages - Bob->>Alice: Read incoming messages + Morty->>Rick: Write outbound messages + Rick->>Morty: Read incoming messages end loop - Bob->>Alice: Write outbound messages - Alice->>Bob: Read incoming messages + Rick->>Morty: Write outbound messages + Morty->>Rick: Read incoming messages end ``` @@ -55,50 +56,50 @@ A peer will then read the full message and attempt to parse it into either a net Upon connection to a new peer, a handshake is performed between the node attempting to establish the outbound connection to the peer and the peer receiving the inbound connection. -When attempting to establish the connection, the first message that the node sends is a `Handshake` message describing the compatibility of the nodes. If the `Handshake` message is successfully received and the peer decides that it wants a connection with this node, it replies with a `PeerList` message that contains metadata about other peers that allows a node to connect to them. See [Peerlist Gossip](#peerlist-gossip). +When attempting to establish the connection, the first message that the node sends is a `Handshake` message describing the configuration of the node. If the `Handshake` message is successfully received and the peer decides that it will allow a connection with this node, it replies with a `PeerList` message that contains metadata about other peers that allows a node to connect to them. See [PeerList Gossip](#peerlist-gossip). As an example, nodes that are attempting to connect with an incompatible version of AvalancheGo or a significantly skewed local clock are rejected. ```mermaid sequenceDiagram - actor Alice - actor Bob - Note over Alice,Bob: Connection Created + actor Morty + actor Rick + Note over Morty,Rick: Connection Created par - Alice->>Bob: AvalancheGo v1.0.0 + Morty->>Rick: AvalancheGo v1.0.0 and - Bob->>Alice: AvalancheGo v1.11.4 + Rick->>Morty: AvalancheGo v1.11.4 end - Note right of Bob: v1.0.0 is incompatible with v1.11.4. - Note left of Alice: v1.11.4 could be compatible with v1.0.0! + Note right of Rick: v1.0.0 is incompatible with v1.11.4. + Note left of Morty: v1.11.4 could be compatible with v1.0.0! par - Bob-->>Alice: Disconnect + Rick-->>Morty: Disconnect and - Alice-XBob: Peerlist + Morty-XRick: Peerlist end - Note over Alice,Bob: Handshake Failed + Note over Morty,Rick: Handshake Failed ``` Nodes that mutually desire the connection will both respond with `PeerList` messages and complete the handshake. ```mermaid sequenceDiagram - actor Alice - actor Bob - Note over Alice,Bob: Connection Created + actor Morty + actor Rick + Note over Morty,Rick: Connection Created par - Alice->>Bob: AvalancheGo v1.11.0 + Morty->>Rick: AvalancheGo v1.11.0 and - Bob->>Alice: AvalancheGo v1.11.4 + Rick->>Morty: AvalancheGo v1.11.4 end - Note right of Bob: v1.11.0 is compatible with v1.11.4! - Note left of Alice: v1.11.4 could be compatible with v1.11.0! + Note right of Rick: v1.11.0 is compatible with v1.11.4! + Note left of Morty: v1.11.4 could be compatible with v1.11.0! par - Bob->>Alice: Peerlist + Rick->>Morty: Peerlist and - Alice->>Bob: Peerlist + Morty->>Rick: Peerlist end - Note over Alice,Bob: Handshake Complete + Note over Morty,Rick: Handshake Complete ``` ### Ping-Pong Messages @@ -107,12 +108,12 @@ Peers periodically send `Ping` messages containing perceived uptime information. ```mermaid sequenceDiagram - actor Alice - actor Bob - Note left of Alice: Send Ping - Alice->>Bob: I think your uptime is 95% - Note right of Bob: Send Pong - Bob->>Alice: ACK + actor Morty + actor Rick + Note left of Morty: Send Ping + Morty->>Rick: I think your uptime is 95% + Note right of Rick: Send Pong + Rick->>Morty: ACK ``` ## Peer Discovery @@ -127,10 +128,12 @@ It is expected for Avalanche nodes to allow inbound connections. If a validator Avalanche nodes that have identified the `IP:Port` pair of a node they want to connect to will initiate outbound connections to this `IP:Port` pair. If the connection is not able to complete the [Peer Handshake](#peer-handshake), the connection will be re-attempted with an [Exponential Backoff](https://en.wikipedia.org/wiki/Exponential_backoff). -A node should initiate outbound connections to an `IP:Port` pair that is believed to belong to a node that is not connected and meets at least one of the following conditions: -- The node is in the initial bootstrapper set. -- The node is in the default bootstrapper set. -- The node in the current Primary Network validator set. +A node should initiate outbound connections to an `IP:Port` pair that is believed to belong to another node that is not connected and meets at least one of the following conditions: +- The peer is in the initial bootstrapper set. +- The peer is in the default bootstrapper set. +- The peer is a Primary Network validator. +- The peer is a validator of a tracked Subnet. +- The peer is a validator of a Subnet and the local node is a Primary Network validator. #### IP Authentication @@ -148,7 +151,16 @@ Once connected to an initial set of peers, a node can use these connections to d Peers are discovered by receiving [`PeerList`](#peerlist) messages during the [Peer Handshake](#peer-handshake). These messages quickly provide a node with knowledge of peers in the network. However, they offer no guarantee that the node will connect to and maintain connections with every peer in the network. -To provide an eventual guarantee that all peers learn of one another, nodes periodically send a [`GetPeerList`](#getpeerlist) message to a randomly selected validator with the node's current [Bloom Filter](#bloom-filter) and `Salt`. +To provide an eventual guarantee that all peers learn of one another, nodes periodically send a [`GetPeerList`](#getpeerlist) message to a randomly selected Primary Network validator with the node's current [Bloom Filter](#bloom-filter) and `Salt`. + +#### Gossipable Peers + +The peers that a node may include into a [`GetPeerList`](#getpeerlist) message are considered `gossipable`. + + +#### Trackable Peers + +The peers that a node would attempt to connect to if included in a [`PeerList`](#peerlist) message are considered `trackable`. #### Bloom Filter @@ -171,32 +183,42 @@ A `GetPeerList` message contains the Bloom Filter of the currently known peers a `PeerList` messages are expected to contain `IP:Port` pairs that satisfy all of the following constraints: - The Bloom Filter sent when requesting the `PeerList` message does not contain the node claiming the `IP:Port` pair. - The node claiming the `IP:Port` pair is currently connected. -- The `IP:Port` pair the node shared during the `Handshake` message is the node's most recently known `IP:Port` pair. -- The node claiming the `IP:Port` pair is either in the default bootstrapper set or is a current Primary Network validator. +- The node claiming the `IP:Port` pair is either in the default bootstrapper set, is a current Primary Network validator, is a validator of a tracked Subnet, or is a validator of a Subnet and the peer is a Primary Network validator. -#### Example PeerList Gossip +#### Avoiding Persistent Network Traffic -The following diagram shows an example of `Alice` repeatedly learning about new peers from `Bob`. +To avoid persistent network traffic, it must eventually hold that the set of [`gossipable peers`](#gossipable-peers) is a subset of the [`trackable peers`](#trackable-peers) for all nodes in the network. + +For example, say there are 3 nodes: `Rick`, `Morty`, and `Summer`. + +First we consider the case that `Rick` and `Morty` consider `Summer` [`gossipable`](#gossipable-peers) and [`trackable`](#trackable-peers), respectively. +```mermaid +sequenceDiagram + actor Morty + actor Rick + Note left of Morty: Not currently tracking Summer + Morty->>Rick: GetPeerList + Note right of Rick: Summer isn't in the bloom filter + Rick->>Morty: PeerList - Contains Summer + Note left of Morty: Track Summer and add to bloom filter + Morty->>Rick: GetPeerList + Note right of Rick: Summer is in the bloom filter + Rick->>Morty: PeerList - Empty +``` +This case is ideal, as `Rick` only notifies `Morty` about `Summer` once, and never uses bandwidth for their connection again. +Now we consider the case that `Rick` considers `Summer` [`gossipable`](#gossipable-peers), but `Morty` does not consider `Summer` [`trackable`](#trackable-peers). ```mermaid sequenceDiagram - actor Alice - actor Bob - Note left of Alice: Initialize Bloom Filter - Note left of Alice: Bloom: [0, 0, 0] - Alice->>Bob: GetPeerList [0, 0, 0] - Note right of Bob: Any peers can be sent. - Bob->>Alice: PeerList - Peer-1 - Note left of Alice: Bloom: [1, 0, 0] - Alice->>Bob: GetPeerList [1, 0, 0] - Note right of Bob: Either Peer-2 or Peer-3 can be sent. - Bob->>Alice: PeerList - Peer-3 - Note left of Alice: Bloom: [1, 0, 1] - Alice->>Bob: GetPeerList [1, 0, 1] - Note right of Bob: Only Peer-2 can be sent. - Bob->>Alice: PeerList - Peer-2 - Note left of Alice: Bloom: [1, 1, 1] - Alice->>Bob: GetPeerList [1, 1, 1] - Note right of Bob: There are no more peers left to send! - Bob->>Alice: PeerList - Empty + actor Morty + actor Rick + Note left of Morty: Not currently tracking Summer + Morty->>Rick: GetPeerList + Note right of Rick: Summer isn't in the bloom filter + Rick->>Morty: PeerList - Contains Summer + Note left of Morty: Ignore Summer + Morty->>Rick: GetPeerList + Note right of Rick: Summer isn't in the bloom filter + Rick->>Morty: PeerList - Contains Summer ``` +This case is suboptimal, because `Rick` told `Morty` about `Summer` multiple times. If this case were to happen consistently, `Rick` may waste a significant amount of bandwidth trying to teach `Morty` about `Summer`. \ No newline at end of file diff --git a/network/ip_tracker.go b/network/ip_tracker.go index 47cb032fc7a4..9fa87e1c01e4 100644 --- a/network/ip_tracker.go +++ b/network/ip_tracker.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/bloom" + "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/ips" "github.com/ava-labs/avalanchego/utils/logging" @@ -37,9 +38,10 @@ const ( newTimestamp = 2 ) -var _ validators.SetCallbackListener = (*ipTracker)(nil) +var _ validators.ManagerCallbackListener = (*ipTracker)(nil) func newIPTracker( + trackedSubnets set.Set[ids.ID], log logging.Logger, registerer prometheus.Registerer, ) (*ipTracker, error) { @@ -48,24 +50,30 @@ func newIPTracker( return nil, err } tracker := &ipTracker{ - log: log, - numTrackedIPs: prometheus.NewGauge(prometheus.GaugeOpts{ - Name: "tracked_ips", - Help: "Number of IPs this node is willing to dial", + trackedSubnets: trackedSubnets, + log: log, + numTrackedPeers: prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "tracked_peers", + Help: "number of peers this node is monitoring", }), numGossipableIPs: prometheus.NewGauge(prometheus.GaugeOpts{ Name: "gossipable_ips", - Help: "Number of IPs this node is willing to gossip", + Help: "number of IPs this node considers able to be gossiped", }), - bloomMetrics: bloomMetrics, - mostRecentTrackedIPs: make(map[ids.NodeID]*ips.ClaimedIPPort), - bloomAdditions: make(map[ids.NodeID]int), - connected: make(map[ids.NodeID]*ips.ClaimedIPPort), - gossipableIndices: make(map[ids.NodeID]int), + numTrackedSubnets: prometheus.NewGauge(prometheus.GaugeOpts{ + Name: "tracked_subnets", + Help: "number of subnets this node is monitoring", + }), + bloomMetrics: bloomMetrics, + tracked: make(map[ids.NodeID]*trackedNode), + bloomAdditions: make(map[ids.NodeID]int), + connected: make(map[ids.NodeID]*connectedNode), + subnet: make(map[ids.ID]*gossipableSubnet), } err = errors.Join( - registerer.Register(tracker.numTrackedIPs), + registerer.Register(tracker.numTrackedPeers), registerer.Register(tracker.numGossipableIPs), + registerer.Register(tracker.numTrackedSubnets), ) if err != nil { return nil, err @@ -73,30 +81,139 @@ func newIPTracker( return tracker, tracker.resetBloom() } -type ipTracker struct { - log logging.Logger - numTrackedIPs prometheus.Gauge +// A node is tracked if any of the following conditions are met: +// - The node was manually tracked +// - The node is a validator on any subnet +type trackedNode struct { + // manuallyTracked tracks if this node's connection was manually requested. + manuallyTracked bool + // validatedSubnets contains all the subnets that this node is a validator + // of, including potentially the primary network. + validatedSubnets set.Set[ids.ID] + // subnets contains the subset of [subnets] that the local node also tracks, + // including potentially the primary network. + trackedSubnets set.Set[ids.ID] + // ip is the most recently known IP of this node. + ip *ips.ClaimedIPPort +} + +func (n *trackedNode) wantsConnection() bool { + return n.manuallyTracked || n.trackedSubnets.Len() > 0 +} + +func (n *trackedNode) canDelete() bool { + return !n.manuallyTracked && n.validatedSubnets.Len() == 0 +} + +type connectedNode struct { + // trackedSubnets contains all the subnets that this node is syncing, + // including the primary network. + trackedSubnets set.Set[ids.ID] + // ip this node claimed when connecting. The IP is not necessarily the same + // IP as in the tracked map. + ip *ips.ClaimedIPPort +} + +type gossipableSubnet struct { numGossipableIPs prometheus.Gauge - bloomMetrics *bloom.Metrics - lock sync.RWMutex - // manuallyTracked contains the nodeIDs of all nodes whose connection was - // manually requested. - manuallyTracked set.Set[ids.NodeID] // manuallyGossipable contains the nodeIDs of all nodes whose IP was - // manually configured to be gossiped. + // manually configured to be gossiped for this subnet. manuallyGossipable set.Set[ids.NodeID] - // mostRecentTrackedIPs tracks the most recent IP of each node whose - // connection is desired. - // - // An IP is tracked if one of the following conditions are met: - // - The node was manually tracked - // - The node was manually requested to be gossiped - // - The node is a validator - mostRecentTrackedIPs map[ids.NodeID]*ips.ClaimedIPPort - // trackedIDs contains the nodeIDs of all nodes whose connection is desired. - trackedIDs set.Set[ids.NodeID] + // gossipableIDs contains the nodeIDs of all nodes whose IP could be + // gossiped. This is a superset of manuallyGossipable. + gossipableIDs set.Set[ids.NodeID] + + // An IP is marked as gossipable if all of the following conditions are met: + // - The node is a validator or was manually requested to be gossiped + // - The node is connected + // - The node reported that they are syncing this subnet + // - The IP the node connected with is its latest IP + gossipableIndices map[ids.NodeID]int + gossipableIPs []*ips.ClaimedIPPort +} + +func (s *gossipableSubnet) setGossipableIP(ip *ips.ClaimedIPPort) { + if index, ok := s.gossipableIndices[ip.NodeID]; ok { + s.gossipableIPs[index] = ip + return + } + + s.numGossipableIPs.Inc() + s.gossipableIndices[ip.NodeID] = len(s.gossipableIPs) + s.gossipableIPs = append(s.gossipableIPs, ip) +} + +func (s *gossipableSubnet) removeGossipableIP(nodeID ids.NodeID) { + indexToRemove, wasGossipable := s.gossipableIndices[nodeID] + if !wasGossipable { + return + } + + // If we aren't removing the last IP, we need to swap the last IP with the + // IP we are removing so that the slice is contiguous. + newNumGossipable := len(s.gossipableIPs) - 1 + if newNumGossipable != indexToRemove { + replacementIP := s.gossipableIPs[newNumGossipable] + s.gossipableIndices[replacementIP.NodeID] = indexToRemove + s.gossipableIPs[indexToRemove] = replacementIP + } + + s.numGossipableIPs.Dec() + delete(s.gossipableIndices, nodeID) + s.gossipableIPs[newNumGossipable] = nil + s.gossipableIPs = s.gossipableIPs[:newNumGossipable] +} + +// [maxNumIPs] applies to the total number of IPs returned, including the IPs +// initially provided in [ips]. +// [ips] and [nodeIDs] are extended and returned with the additional IPs added. +func (s *gossipableSubnet) getGossipableIPs( + exceptNodeID ids.NodeID, + exceptIPs *bloom.ReadFilter, + salt []byte, + maxNumIPs int, + ips []*ips.ClaimedIPPort, + nodeIDs set.Set[ids.NodeID], +) ([]*ips.ClaimedIPPort, set.Set[ids.NodeID]) { + uniform := sampler.NewUniform() + uniform.Initialize(uint64(len(s.gossipableIPs))) + + for len(ips) < maxNumIPs { + index, hasNext := uniform.Next() + if !hasNext { + return ips, nodeIDs + } + + ip := s.gossipableIPs[index] + if ip.NodeID == exceptNodeID || + nodeIDs.Contains(ip.NodeID) || + bloom.Contains(exceptIPs, ip.GossipID[:], salt) { + continue + } + + ips = append(ips, ip) + nodeIDs.Add(ip.NodeID) + } + return ips, nodeIDs +} + +func (s *gossipableSubnet) canDelete() bool { + return s.gossipableIDs.Len() == 0 +} + +type ipTracker struct { + // trackedSubnets does not include the primary network. + trackedSubnets set.Set[ids.ID] + log logging.Logger + numTrackedPeers prometheus.Gauge + numGossipableIPs prometheus.Gauge // IPs are not deduplicated across subnets + numTrackedSubnets prometheus.Gauge + bloomMetrics *bloom.Metrics + + lock sync.RWMutex + tracked map[ids.NodeID]*trackedNode // The bloom filter contains the most recent tracked IPs to avoid // unnecessary IP gossip. @@ -108,19 +225,11 @@ type ipTracker struct { bloomSalt []byte maxBloomCount int - // Connected tracks the IP of currently connected peers, including tracked - // and untracked nodes. The IP is not necessarily the same IP as in - // mostRecentTrackedIPs. - connected map[ids.NodeID]*ips.ClaimedIPPort - - // An IP is marked as gossipable if all of the following conditions are met: - // - The node is a validator or was manually requested to be gossiped - // - The node is connected - // - The IP the node connected with is its latest IP - gossipableIndices map[ids.NodeID]int - // gossipableIPs is guaranteed to be a subset of [mostRecentTrackedIPs]. - gossipableIPs []*ips.ClaimedIPPort - gossipableIDs set.Set[ids.NodeID] + // Connected tracks the information of currently connected peers, including + // tracked and untracked nodes. + connected map[ids.NodeID]*connectedNode + // subnet tracks all the subnets that have at least one gossipable ID. + subnet map[ids.ID]*gossipableSubnet } // ManuallyTrack marks the provided nodeID as being desirable to connect to. @@ -134,8 +243,7 @@ func (i *ipTracker) ManuallyTrack(nodeID ids.NodeID) { i.lock.Lock() defer i.lock.Unlock() - i.addTrackableID(nodeID) - i.manuallyTracked.Add(nodeID) + i.addTrackableID(nodeID, nil) } // ManuallyGossip marks the provided nodeID as being desirable to connect to and @@ -143,107 +251,142 @@ func (i *ipTracker) ManuallyTrack(nodeID ids.NodeID) { // // In order to avoid persistent network gossip, it's important for nodes in the // network to agree upon manually gossiped nodeIDs. -func (i *ipTracker) ManuallyGossip(nodeID ids.NodeID) { +func (i *ipTracker) ManuallyGossip(subnetID ids.ID, nodeID ids.NodeID) { i.lock.Lock() defer i.lock.Unlock() - i.addTrackableID(nodeID) - i.manuallyTracked.Add(nodeID) + if subnetID == constants.PrimaryNetworkID || i.trackedSubnets.Contains(subnetID) { + i.addTrackableID(nodeID, nil) + } - i.addGossipableID(nodeID) - i.manuallyGossipable.Add(nodeID) + i.addTrackableID(nodeID, &subnetID) + i.addGossipableID(nodeID, subnetID, true) } // WantsConnection returns true if any of the following conditions are met: // 1. The node has been manually tracked. -// 2. The node has been manually gossiped. -// 3. The node is currently a validator. +// 2. The node has been manually gossiped on a tracked subnet. +// 3. The node is currently a validator on a tracked subnet. func (i *ipTracker) WantsConnection(nodeID ids.NodeID) bool { i.lock.RLock() defer i.lock.RUnlock() - return i.trackedIDs.Contains(nodeID) + node, ok := i.tracked[nodeID] + return ok && node.wantsConnection() } // ShouldVerifyIP is used as an optimization to avoid unnecessary IP // verification. It returns true if all of the following conditions are met: // 1. The provided IP is from a node whose connection is desired. // 2. This IP is newer than the most recent IP we know of for the node. -func (i *ipTracker) ShouldVerifyIP(ip *ips.ClaimedIPPort) bool { +func (i *ipTracker) ShouldVerifyIP( + ip *ips.ClaimedIPPort, + trackAllSubnets bool, +) bool { i.lock.RLock() defer i.lock.RUnlock() - if !i.trackedIDs.Contains(ip.NodeID) { + node, ok := i.tracked[ip.NodeID] + if !ok { + return false + } + + if !trackAllSubnets && !node.wantsConnection() { return false } - prevIP, ok := i.mostRecentTrackedIPs[ip.NodeID] - return !ok || // This would be the first IP - prevIP.Timestamp < ip.Timestamp // This would be a newer IP + return node.ip == nil || // This would be the first IP + node.ip.Timestamp < ip.Timestamp // This would be a newer IP } // AddIP attempts to update the node's IP to the provided IP. This function // assumes the provided IP has been verified. Returns true if all of the // following conditions are met: -// 1. The provided IP is from a node whose connection is desired. +// 1. The provided IP is from a node whose connection is desired on a tracked +// subnet. // 2. This IP is newer than the most recent IP we know of for the node. // -// If the previous IP was marked as gossipable, calling this function will -// remove the IP from the gossipable set. +// If this IP is replacing a gossipable IP, this IP will also be marked as +// gossipable. func (i *ipTracker) AddIP(ip *ips.ClaimedIPPort) bool { i.lock.Lock() defer i.lock.Unlock() - return i.addIP(ip) > sameTimestamp + timestampComparison, trackedNode := i.addIP(ip) + if timestampComparison <= sameTimestamp { + return false + } + + if connectedNode, ok := i.connected[ip.NodeID]; ok { + i.setGossipableIP(trackedNode.ip, connectedNode.trackedSubnets) + } + return trackedNode.wantsConnection() } -// GetIP returns the most recent IP of the provided nodeID. If a connection to -// this nodeID is not desired, this function will return false. +// GetIP returns the most recent IP of the provided nodeID. Returns true if all +// of the following conditions are met: +// 1. There is currently an IP for the provided nodeID. +// 2. The provided IP is from a node whose connection is desired on a tracked +// subnet. func (i *ipTracker) GetIP(nodeID ids.NodeID) (*ips.ClaimedIPPort, bool) { i.lock.RLock() defer i.lock.RUnlock() - ip, ok := i.mostRecentTrackedIPs[nodeID] - return ip, ok + node, ok := i.tracked[nodeID] + if !ok || node.ip == nil { + return nil, false + } + return node.ip, node.wantsConnection() } // Connected is called when a connection is established. The peer should have // provided [ip] during the handshake. -func (i *ipTracker) Connected(ip *ips.ClaimedIPPort) { +func (i *ipTracker) Connected(ip *ips.ClaimedIPPort, trackedSubnets set.Set[ids.ID]) { i.lock.Lock() defer i.lock.Unlock() - i.connected[ip.NodeID] = ip - if i.addIP(ip) >= sameTimestamp && i.gossipableIDs.Contains(ip.NodeID) { - i.addGossipableIP(ip) + i.connected[ip.NodeID] = &connectedNode{ + trackedSubnets: trackedSubnets, + ip: ip, } -} -func (i *ipTracker) addIP(ip *ips.ClaimedIPPort) int { - if !i.trackedIDs.Contains(ip.NodeID) { - return untrackedTimestamp + timestampComparison, trackedNode := i.addIP(ip) + if timestampComparison != untrackedTimestamp { + i.setGossipableIP(trackedNode.ip, trackedSubnets) } +} - prevIP, ok := i.mostRecentTrackedIPs[ip.NodeID] +func (i *ipTracker) addIP(ip *ips.ClaimedIPPort) (int, *trackedNode) { + node, ok := i.tracked[ip.NodeID] if !ok { + return untrackedTimestamp, nil + } + + if node.ip == nil { // This is the first IP we've heard from the validator, so it is the // most recent. - i.updateMostRecentTrackedIP(ip) - // Because we didn't previously have an IP, we know we aren't currently - // connected to them. - return newTimestamp + i.updateMostRecentTrackedIP(node, ip) + return newTimestamp, node } - if prevIP.Timestamp > ip.Timestamp { - return olderTimestamp // This IP is old than the previously known IP. + if node.ip.Timestamp > ip.Timestamp { + return olderTimestamp, node // This IP is older than the previously known IP. } - if prevIP.Timestamp == ip.Timestamp { - return sameTimestamp // This IP is equal to the previously known IP. + if node.ip.Timestamp == ip.Timestamp { + return sameTimestamp, node // This IP is equal to the previously known IP. } - i.updateMostRecentTrackedIP(ip) - i.removeGossipableIP(ip.NodeID) - return newerTimestamp + // This IP is newer than the previously known IP. + i.updateMostRecentTrackedIP(node, ip) + return newerTimestamp, node +} + +func (i *ipTracker) setGossipableIP(ip *ips.ClaimedIPPort, trackedSubnets set.Set[ids.ID]) { + for subnetID := range trackedSubnets { + if subnet, ok := i.subnet[subnetID]; ok && subnet.gossipableIDs.Contains(ip.NodeID) { + subnet.setGossipableIP(ip) + } + } } // Disconnected is called when a connection to the peer is closed. @@ -251,77 +394,135 @@ func (i *ipTracker) Disconnected(nodeID ids.NodeID) { i.lock.Lock() defer i.lock.Unlock() + connectedNode, ok := i.connected[nodeID] + if !ok { + return + } delete(i.connected, nodeID) - i.removeGossipableIP(nodeID) + + for subnetID := range connectedNode.trackedSubnets { + if subnet, ok := i.subnet[subnetID]; ok { + subnet.removeGossipableIP(nodeID) + } + } } -func (i *ipTracker) OnValidatorAdded(nodeID ids.NodeID, _ *bls.PublicKey, _ ids.ID, _ uint64) { +func (i *ipTracker) OnValidatorAdded(subnetID ids.ID, nodeID ids.NodeID, _ *bls.PublicKey, _ ids.ID, _ uint64) { i.lock.Lock() defer i.lock.Unlock() - i.addTrackableID(nodeID) - i.addGossipableID(nodeID) + i.addTrackableID(nodeID, &subnetID) + i.addGossipableID(nodeID, subnetID, false) } -func (i *ipTracker) addTrackableID(nodeID ids.NodeID) { - if i.trackedIDs.Contains(nodeID) { +// If [subnetID] is nil, the nodeID is being manually tracked. +func (i *ipTracker) addTrackableID(nodeID ids.NodeID, subnetID *ids.ID) { + nodeTracker, previouslyTracked := i.tracked[nodeID] + if !previouslyTracked { + i.numTrackedPeers.Inc() + nodeTracker = &trackedNode{} + i.tracked[nodeID] = nodeTracker + } + + if subnetID == nil { + nodeTracker.manuallyTracked = true + } else { + nodeTracker.validatedSubnets.Add(*subnetID) + if *subnetID == constants.PrimaryNetworkID || i.trackedSubnets.Contains(*subnetID) { + nodeTracker.trackedSubnets.Add(*subnetID) + } + } + + if previouslyTracked { return } - i.trackedIDs.Add(nodeID) - ip, connected := i.connected[nodeID] + node, connected := i.connected[nodeID] if !connected { return } // Because we previously weren't tracking this nodeID, the IP from the // connection is guaranteed to be the most up-to-date IP that we know. - i.updateMostRecentTrackedIP(ip) + i.updateMostRecentTrackedIP(nodeTracker, node.ip) } -func (i *ipTracker) addGossipableID(nodeID ids.NodeID) { - if i.gossipableIDs.Contains(nodeID) { - return +func (i *ipTracker) addGossipableID(nodeID ids.NodeID, subnetID ids.ID, manuallyGossiped bool) { + subnet, ok := i.subnet[subnetID] + if !ok { + i.numTrackedSubnets.Inc() + subnet = &gossipableSubnet{ + numGossipableIPs: i.numGossipableIPs, + gossipableIndices: make(map[ids.NodeID]int), + } + i.subnet[subnetID] = subnet } - i.gossipableIDs.Add(nodeID) - connectedIP, connected := i.connected[nodeID] - if !connected { + if manuallyGossiped { + subnet.manuallyGossipable.Add(nodeID) + } + if subnet.gossipableIDs.Contains(nodeID) { return } - if updatedIP, ok := i.mostRecentTrackedIPs[nodeID]; !ok || connectedIP.Timestamp != updatedIP.Timestamp { + subnet.gossipableIDs.Add(nodeID) + node, connected := i.connected[nodeID] + if !connected || !node.trackedSubnets.Contains(subnetID) { return } - i.addGossipableIP(connectedIP) + if trackedNode, ok := i.tracked[nodeID]; ok { + subnet.setGossipableIP(trackedNode.ip) + } } -func (*ipTracker) OnValidatorWeightChanged(ids.NodeID, uint64, uint64) {} +func (*ipTracker) OnValidatorWeightChanged(ids.ID, ids.NodeID, uint64, uint64) {} -func (i *ipTracker) OnValidatorRemoved(nodeID ids.NodeID, _ uint64) { +func (i *ipTracker) OnValidatorRemoved(subnetID ids.ID, nodeID ids.NodeID, _ uint64) { i.lock.Lock() defer i.lock.Unlock() - if i.manuallyGossipable.Contains(nodeID) { + subnet, ok := i.subnet[subnetID] + if !ok { + i.log.Error("attempted removal of validator from untracked subnet", + zap.Stringer("subnetID", subnetID), + zap.Stringer("nodeID", nodeID), + ) + return + } + + if subnet.manuallyGossipable.Contains(nodeID) { return } - i.gossipableIDs.Remove(nodeID) - i.removeGossipableIP(nodeID) + subnet.gossipableIDs.Remove(nodeID) + subnet.removeGossipableIP(nodeID) - if i.manuallyTracked.Contains(nodeID) { + if subnet.canDelete() { + i.numTrackedSubnets.Dec() + delete(i.subnet, subnetID) + } + + trackedNode, ok := i.tracked[nodeID] + if !ok { + i.log.Error("attempted removal of untracked validator", + zap.Stringer("subnetID", subnetID), + zap.Stringer("nodeID", nodeID), + ) return } - i.trackedIDs.Remove(nodeID) - delete(i.mostRecentTrackedIPs, nodeID) - i.numTrackedIPs.Set(float64(len(i.mostRecentTrackedIPs))) + trackedNode.validatedSubnets.Remove(subnetID) + trackedNode.trackedSubnets.Remove(subnetID) + + if trackedNode.canDelete() { + i.numTrackedPeers.Dec() + delete(i.tracked, nodeID) + } } -func (i *ipTracker) updateMostRecentTrackedIP(ip *ips.ClaimedIPPort) { - i.mostRecentTrackedIPs[ip.NodeID] = ip - i.numTrackedIPs.Set(float64(len(i.mostRecentTrackedIPs))) +func (i *ipTracker) updateMostRecentTrackedIP(node *trackedNode, ip *ips.ClaimedIPPort) { + node.ip = ip oldCount := i.bloomAdditions[ip.NodeID] if oldCount >= maxIPEntriesPerNode { @@ -350,68 +551,6 @@ func (i *ipTracker) updateMostRecentTrackedIP(ip *ips.ClaimedIPPort) { i.bloomMetrics.Count.Inc() } -func (i *ipTracker) addGossipableIP(ip *ips.ClaimedIPPort) { - i.gossipableIndices[ip.NodeID] = len(i.gossipableIPs) - i.gossipableIPs = append(i.gossipableIPs, ip) - i.numGossipableIPs.Inc() -} - -func (i *ipTracker) removeGossipableIP(nodeID ids.NodeID) { - indexToRemove, wasGossipable := i.gossipableIndices[nodeID] - if !wasGossipable { - return - } - - newNumGossipable := len(i.gossipableIPs) - 1 - if newNumGossipable != indexToRemove { - replacementIP := i.gossipableIPs[newNumGossipable] - i.gossipableIndices[replacementIP.NodeID] = indexToRemove - i.gossipableIPs[indexToRemove] = replacementIP - } - - delete(i.gossipableIndices, nodeID) - i.gossipableIPs[newNumGossipable] = nil - i.gossipableIPs = i.gossipableIPs[:newNumGossipable] - i.numGossipableIPs.Dec() -} - -// GetGossipableIPs returns the latest IPs of connected validators. The returned -// IPs will not contain [exceptNodeID] or any IPs contained in [exceptIPs]. If -// the number of eligible IPs to return low, it's possible that every IP will be -// iterated over while handling this call. -func (i *ipTracker) GetGossipableIPs( - exceptNodeID ids.NodeID, - exceptIPs *bloom.ReadFilter, - salt []byte, - maxNumIPs int, -) []*ips.ClaimedIPPort { - var ( - uniform = sampler.NewUniform() - ips = make([]*ips.ClaimedIPPort, 0, maxNumIPs) - ) - - i.lock.RLock() - defer i.lock.RUnlock() - - uniform.Initialize(uint64(len(i.gossipableIPs))) - for len(ips) < maxNumIPs { - index, hasNext := uniform.Next() - if !hasNext { - return ips - } - - ip := i.gossipableIPs[index] - if ip.NodeID == exceptNodeID { - continue - } - - if !bloom.Contains(exceptIPs, ip.GossipID[:], salt) { - ips = append(ips, ip) - } - } - return ips -} - // ResetBloom prunes the current bloom filter. This must be called periodically // to ensure that validators that change their IPs are updated correctly and // that validators that left the validator set are removed. @@ -441,7 +580,7 @@ func (i *ipTracker) resetBloom() error { return err } - count := max(maxIPEntriesPerNode*i.trackedIDs.Len(), minCountEstimate) + count := max(maxIPEntriesPerNode*len(i.tracked), minCountEstimate) numHashes, numEntries := bloom.OptimalParameters( count, targetFalsePositiveProbability, @@ -456,10 +595,56 @@ func (i *ipTracker) resetBloom() error { i.bloomSalt = newSalt i.maxBloomCount = bloom.EstimateCount(numHashes, numEntries, maxFalsePositiveProbability) - for nodeID, ip := range i.mostRecentTrackedIPs { - bloom.Add(newFilter, ip.GossipID[:], newSalt) + for nodeID, trackedNode := range i.tracked { + if trackedNode.ip == nil { + continue + } + + bloom.Add(newFilter, trackedNode.ip.GossipID[:], newSalt) i.bloomAdditions[nodeID] = 1 } i.bloomMetrics.Reset(newFilter, i.maxBloomCount) return nil } + +func getGossipableIPs[T any]( + i *ipTracker, + iter map[ids.ID]T, // The values in this map aren't actually used. + allowed func(ids.ID) bool, + exceptNodeID ids.NodeID, + exceptIPs *bloom.ReadFilter, + salt []byte, + maxNumIPs int, +) []*ips.ClaimedIPPort { + var ( + ips = make([]*ips.ClaimedIPPort, 0, maxNumIPs) + nodeIDs = set.NewSet[ids.NodeID](maxNumIPs) + ) + + i.lock.RLock() + defer i.lock.RUnlock() + + for subnetID := range iter { + if !allowed(subnetID) { + continue + } + + subnet, ok := i.subnet[subnetID] + if !ok { + continue + } + + ips, nodeIDs = subnet.getGossipableIPs( + exceptNodeID, + exceptIPs, + salt, + maxNumIPs, + ips, + nodeIDs, + ) + if len(ips) >= maxNumIPs { + break + } + } + return ips +} diff --git a/network/ip_tracker_test.go b/network/ip_tracker_test.go index bbfbdb958773..99f1a616287e 100644 --- a/network/ip_tracker_test.go +++ b/network/ip_tracker_test.go @@ -12,12 +12,18 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/bloom" + "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/set" ) func newTestIPTracker(t *testing.T) *ipTracker { - tracker, err := newIPTracker(logging.NoLog{}, prometheus.NewRegistry()) + tracker, err := newIPTracker( + nil, + logging.NoLog{}, + prometheus.NewRegistry(), + ) require.NoError(t, err) return tracker } @@ -33,800 +39,1135 @@ func newerTestIP(ip *ips.ClaimedIPPort) *ips.ClaimedIPPort { func requireEqual(t *testing.T, expected, actual *ipTracker) { require := require.New(t) - require.Equal(expected.manuallyTracked, actual.manuallyTracked) - require.Equal(expected.manuallyGossipable, actual.manuallyGossipable) - require.Equal(expected.mostRecentTrackedIPs, actual.mostRecentTrackedIPs) - require.Equal(expected.trackedIDs, actual.trackedIDs) + require.Equal(expected.tracked, actual.tracked) require.Equal(expected.bloomAdditions, actual.bloomAdditions) require.Equal(expected.maxBloomCount, actual.maxBloomCount) require.Equal(expected.connected, actual.connected) - require.Equal(expected.gossipableIndices, actual.gossipableIndices) - require.Equal(expected.gossipableIPs, actual.gossipableIPs) - require.Equal(expected.gossipableIDs, actual.gossipableIDs) + require.Equal(expected.subnet, actual.subnet) } func requireMetricsConsistent(t *testing.T, tracker *ipTracker) { require := require.New(t) - require.Equal(float64(len(tracker.mostRecentTrackedIPs)), testutil.ToFloat64(tracker.numTrackedIPs)) - require.Equal(float64(len(tracker.gossipableIPs)), testutil.ToFloat64(tracker.numGossipableIPs)) + require.Equal(float64(len(tracker.tracked)), testutil.ToFloat64(tracker.numTrackedPeers)) + var numGossipableIPs int + for _, subnet := range tracker.subnet { + numGossipableIPs += len(subnet.gossipableIndices) + } + require.Equal(float64(numGossipableIPs), testutil.ToFloat64(tracker.numGossipableIPs)) + require.Equal(float64(len(tracker.subnet)), testutil.ToFloat64(tracker.numTrackedSubnets)) require.Equal(float64(tracker.bloom.Count()), testutil.ToFloat64(tracker.bloomMetrics.Count)) require.Equal(float64(tracker.maxBloomCount), testutil.ToFloat64(tracker.bloomMetrics.MaxCount)) } func TestIPTracker_ManuallyTrack(t *testing.T) { + subnetID := ids.GenerateTestID() tests := []struct { - name string - initialState *ipTracker - nodeID ids.NodeID - expectedState *ipTracker + name string + initialState func(t *testing.T) *ipTracker + expectedChange func(*ipTracker) }{ { name: "non-connected non-validator", - initialState: newTestIPTracker(t), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.manuallyTracked.Add(ip.NodeID) - tracker.trackedIDs.Add(ip.NodeID) - return tracker - }(), + initialState: newTestIPTracker, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedPeers.Inc() + tracker.tracked[ip.NodeID] = &trackedNode{ + manuallyTracked: true, + } + }, }, { name: "connected non-validator", - initialState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.Connected(ip) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.manuallyTracked.Add(ip.NodeID) - tracker.mostRecentTrackedIPs[ip.NodeID] = ip - tracker.trackedIDs.Add(ip.NodeID) + }, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedPeers.Inc() + tracker.tracked[ip.NodeID] = &trackedNode{ + manuallyTracked: true, + ip: ip, + } tracker.bloomAdditions[ip.NodeID] = 1 - return tracker - }(), + }, }, { - name: "non-connected validator", - initialState: func() *ipTracker { + name: "non-connected tracked validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + }, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].manuallyTracked = true + }, + }, + { + name: "non-connected untracked validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.manuallyTracked.Add(ip.NodeID) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), + }, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].manuallyTracked = true + }, }, { - name: "connected validator", - initialState: func() *ipTracker { + name: "connected tracked validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + }, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].manuallyTracked = true + }, + }, + { + name: "connected untracked validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.manuallyTracked.Add(ip.NodeID) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), + }, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].manuallyTracked = true + }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - test.initialState.ManuallyTrack(test.nodeID) - requireEqual(t, test.expectedState, test.initialState) - requireMetricsConsistent(t, test.initialState) + testState := test.initialState(t) + expectedState := test.initialState(t) + + testState.ManuallyTrack(ip.NodeID) + test.expectedChange(expectedState) + + requireEqual(t, expectedState, testState) + requireMetricsConsistent(t, testState) }) } } func TestIPTracker_ManuallyGossip(t *testing.T) { + subnetID := ids.GenerateTestID() tests := []struct { - name string - initialState *ipTracker - nodeID ids.NodeID - expectedState *ipTracker + name string + initialState func(t *testing.T) *ipTracker + subnetID ids.ID + expectedChange func(*ipTracker) }{ { - name: "non-connected non-validator", - initialState: newTestIPTracker(t), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + name: "non-connected tracked non-validator", + initialState: newTestIPTracker, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedPeers.Inc() + tracker.numTrackedSubnets.Inc() + tracker.tracked[ip.NodeID] = &trackedNode{ + manuallyTracked: true, + validatedSubnets: set.Of(constants.PrimaryNetworkID), + trackedSubnets: set.Of(constants.PrimaryNetworkID), + } + tracker.subnet[constants.PrimaryNetworkID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + manuallyGossipable: set.Of(ip.NodeID), + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: make(map[ids.NodeID]int), + } + }, + }, + { + name: "non-connected untracked non-validator", + initialState: newTestIPTracker, + subnetID: subnetID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedPeers.Inc() + tracker.numTrackedSubnets.Inc() + tracker.tracked[ip.NodeID] = &trackedNode{ + validatedSubnets: set.Of(subnetID), + } + tracker.subnet[subnetID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + manuallyGossipable: set.Of(ip.NodeID), + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: make(map[ids.NodeID]int), + } + }, + }, + { + name: "connected tracked non-validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.manuallyTracked.Add(ip.NodeID) - tracker.manuallyGossipable.Add(ip.NodeID) - tracker.trackedIDs.Add(ip.NodeID) - tracker.gossipableIDs.Add(ip.NodeID) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedPeers.Inc() + tracker.numGossipableIPs.Inc() + tracker.numTrackedSubnets.Inc() + tracker.tracked[ip.NodeID] = &trackedNode{ + manuallyTracked: true, + validatedSubnets: set.Of(constants.PrimaryNetworkID), + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } + tracker.bloomAdditions[ip.NodeID] = 1 + tracker.subnet[constants.PrimaryNetworkID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + manuallyGossipable: set.Of(ip.NodeID), + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: map[ids.NodeID]int{ + ip.NodeID: 0, + }, + gossipableIPs: []*ips.ClaimedIPPort{ + ip, + }, + } + }, }, { - name: "connected non-validator", - initialState: func() *ipTracker { + name: "connected untracked non-validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.Connected(ip) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.manuallyTracked.Add(ip.NodeID) - tracker.manuallyGossipable.Add(ip.NodeID) - tracker.mostRecentTrackedIPs[ip.NodeID] = ip - tracker.trackedIDs.Add(ip.NodeID) + }, + subnetID: subnetID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedPeers.Inc() + tracker.numTrackedSubnets.Inc() + tracker.tracked[ip.NodeID] = &trackedNode{ + validatedSubnets: set.Of(subnetID), + ip: ip, + } tracker.bloomAdditions[ip.NodeID] = 1 - tracker.gossipableIndices[ip.NodeID] = 0 - tracker.gossipableIPs = []*ips.ClaimedIPPort{ - ip, + tracker.subnet[subnetID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + manuallyGossipable: set.Of(ip.NodeID), + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: make(map[ids.NodeID]int), } - tracker.gossipableIDs.Add(ip.NodeID) - return tracker - }(), + }, }, { - name: "non-connected validator", - initialState: func() *ipTracker { + name: "non-connected tracked validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].manuallyTracked = true + tracker.subnet[constants.PrimaryNetworkID].manuallyGossipable = set.Of(ip.NodeID) + }, + }, + { + name: "non-connected untracked validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.manuallyTracked.Add(ip.NodeID) - tracker.manuallyGossipable.Add(ip.NodeID) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), + }, + subnetID: subnetID, + expectedChange: func(tracker *ipTracker) { + tracker.subnet[subnetID].manuallyGossipable = set.Of(ip.NodeID) + }, }, { - name: "connected validator", - initialState: func() *ipTracker { + name: "connected tracked validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].manuallyTracked = true + tracker.subnet[constants.PrimaryNetworkID].manuallyGossipable = set.Of(ip.NodeID) + }, + }, + { + name: "connected untracked validator", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.manuallyTracked.Add(ip.NodeID) - tracker.manuallyGossipable.Add(ip.NodeID) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), + }, + subnetID: subnetID, + expectedChange: func(tracker *ipTracker) { + tracker.subnet[subnetID].manuallyGossipable = set.Of(ip.NodeID) + }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - test.initialState.ManuallyGossip(test.nodeID) - requireEqual(t, test.expectedState, test.initialState) - requireMetricsConsistent(t, test.initialState) + testState := test.initialState(t) + expectedState := test.initialState(t) + + testState.ManuallyGossip(test.subnetID, ip.NodeID) + test.expectedChange(expectedState) + + requireEqual(t, expectedState, testState) + requireMetricsConsistent(t, testState) }) } } -func TestIPTracker_AddIP(t *testing.T) { +func TestIPTracker_ShouldVerifyIP(t *testing.T) { newerIP := newerTestIP(ip) tests := []struct { - name string - initialState *ipTracker - ip *ips.ClaimedIPPort - expectedUpdated bool - expectedState *ipTracker + name string + tracker func(t *testing.T) *ipTracker + ip *ips.ClaimedIPPort + expectedTrackAllSubnets bool + expectedTrackRequestedSubnets bool }{ { - name: "non-validator", - initialState: newTestIPTracker(t), - ip: ip, - expectedUpdated: false, - expectedState: newTestIPTracker(t), + name: "node not tracked", + tracker: newTestIPTracker, + ip: ip, + expectedTrackAllSubnets: false, + expectedTrackRequestedSubnets: false, }, { - name: "first known IP", - initialState: func() *ipTracker { + name: "undesired connection", + tracker: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(ids.GenerateTestID(), ip.NodeID, nil, ids.Empty, 0) return tracker - }(), - ip: ip, - expectedUpdated: true, - expectedState: func() *ipTracker { + }, + ip: ip, + expectedTrackAllSubnets: true, + expectedTrackRequestedSubnets: false, + }, + { + name: "desired connection first IP", + tracker: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.mostRecentTrackedIPs[ip.NodeID] = ip - tracker.bloomAdditions[ip.NodeID] = 1 + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), + }, + ip: ip, + expectedTrackAllSubnets: true, + expectedTrackRequestedSubnets: true, }, { - name: "older IP", - initialState: func() *ipTracker { + name: "desired connection older IP", + tracker: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) require.True(t, tracker.AddIP(newerIP)) return tracker - }(), - ip: ip, - expectedUpdated: false, - expectedState: func() *ipTracker { + }, + ip: ip, + expectedTrackAllSubnets: false, + expectedTrackRequestedSubnets: false, + }, + { + name: "desired connection same IP", + tracker: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - require.True(t, tracker.AddIP(newerIP)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + require.True(t, tracker.AddIP(ip)) return tracker - }(), + }, + ip: ip, + expectedTrackAllSubnets: false, + expectedTrackRequestedSubnets: false, }, { - name: "same IP", - initialState: func() *ipTracker { + name: "desired connection newer IP", + tracker: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) require.True(t, tracker.AddIP(ip)) return tracker - }(), - ip: ip, - expectedUpdated: false, - expectedState: func() *ipTracker { + }, + ip: newerIP, + expectedTrackAllSubnets: true, + expectedTrackRequestedSubnets: true, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + tracker := test.tracker(t) + require.Equal(test.expectedTrackAllSubnets, tracker.ShouldVerifyIP(test.ip, true)) + require.Equal(test.expectedTrackRequestedSubnets, tracker.ShouldVerifyIP(test.ip, false)) + }) + } +} + +func TestIPTracker_AddIP(t *testing.T) { + subnetID := ids.GenerateTestID() + newerIP := newerTestIP(ip) + tests := []struct { + name string + initialState func(t *testing.T) *ipTracker + ip *ips.ClaimedIPPort + expectedChange func(*ipTracker) + expectedUpdatedAndDesired bool + }{ + { + name: "non-validator", + initialState: newTestIPTracker, + ip: ip, + expectedChange: func(*ipTracker) {}, + expectedUpdatedAndDesired: false, + }, + { + name: "first known IP of tracked node", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - require.True(t, tracker.AddIP(ip)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), + }, + ip: ip, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].ip = ip + tracker.bloomAdditions[ip.NodeID] = 1 + }, + expectedUpdatedAndDesired: true, + }, + { + name: "first known IP of untracked node", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + return tracker + }, + ip: ip, + expectedUpdatedAndDesired: false, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].ip = ip + tracker.bloomAdditions[ip.NodeID] = 1 + }, }, { - name: "disconnected newer IP", - initialState: func() *ipTracker { + name: "older IP of tracked node", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + require.True(t, tracker.AddIP(newerIP)) + return tracker + }, + ip: ip, + expectedUpdatedAndDesired: false, + expectedChange: func(*ipTracker) {}, + }, + { + name: "older IP of untracked node", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + require.False(t, tracker.AddIP(newerIP)) + return tracker + }, + ip: ip, + expectedUpdatedAndDesired: false, + expectedChange: func(*ipTracker) {}, + }, + { + name: "same IP of tracked node", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) require.True(t, tracker.AddIP(ip)) return tracker - }(), - ip: newerIP, - expectedUpdated: true, - expectedState: func() *ipTracker { + }, + ip: ip, + expectedUpdatedAndDesired: false, + expectedChange: func(*ipTracker) {}, + }, + { + name: "same IP of untracked node", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + require.False(t, tracker.AddIP(ip)) + return tracker + }, + ip: ip, + expectedUpdatedAndDesired: false, + expectedChange: func(*ipTracker) {}, + }, + { + name: "disconnected newer IP of tracked node", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) require.True(t, tracker.AddIP(ip)) - tracker.mostRecentTrackedIPs[newerIP.NodeID] = newerIP - tracker.bloomAdditions[newerIP.NodeID] = 2 return tracker - }(), + }, + ip: newerIP, + expectedUpdatedAndDesired: true, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[newerIP.NodeID].ip = newerIP + tracker.bloomAdditions[newerIP.NodeID] = 2 + }, }, { - name: "connected newer IP", - initialState: func() *ipTracker { + name: "disconnected newer IP of untracked node", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + require.False(t, tracker.AddIP(ip)) return tracker - }(), - ip: newerIP, - expectedUpdated: true, - expectedState: func() *ipTracker { + }, + ip: newerIP, + expectedUpdatedAndDesired: false, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[newerIP.NodeID].ip = newerIP + tracker.bloomAdditions[newerIP.NodeID] = 2 + }, + }, + { + name: "connected newer IP of tracked node", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - tracker.mostRecentTrackedIPs[newerIP.NodeID] = newerIP + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) + return tracker + }, + ip: newerIP, + expectedUpdatedAndDesired: true, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[newerIP.NodeID].ip = newerIP tracker.bloomAdditions[newerIP.NodeID] = 2 - delete(tracker.gossipableIndices, newerIP.NodeID) - tracker.gossipableIPs = tracker.gossipableIPs[:0] + tracker.subnet[constants.PrimaryNetworkID].gossipableIPs[0] = newerIP + }, + }, + { + name: "connected newer IP of untracked node", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), + }, + ip: newerIP, + expectedUpdatedAndDesired: false, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[newerIP.NodeID].ip = newerIP + tracker.bloomAdditions[newerIP.NodeID] = 2 + }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - updated := test.initialState.AddIP(test.ip) - require.Equal(t, test.expectedUpdated, updated) - requireEqual(t, test.expectedState, test.initialState) - requireMetricsConsistent(t, test.initialState) + testState := test.initialState(t) + expectedState := test.initialState(t) + + updated := testState.AddIP(test.ip) + test.expectedChange(expectedState) + + require.Equal(t, test.expectedUpdatedAndDesired, updated) + requireEqual(t, expectedState, testState) + requireMetricsConsistent(t, testState) }) } } func TestIPTracker_Connected(t *testing.T) { + subnetID := ids.GenerateTestID() newerIP := newerTestIP(ip) tests := []struct { - name string - initialState *ipTracker - ip *ips.ClaimedIPPort - expectedState *ipTracker + name string + initialState func(t *testing.T) *ipTracker + ip *ips.ClaimedIPPort + expectedChange func(*ipTracker) }{ { name: "non-validator", - initialState: newTestIPTracker(t), + initialState: newTestIPTracker, ip: ip, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.connected[ip.NodeID] = ip - return tracker - }(), + expectedChange: func(tracker *ipTracker) { + tracker.connected[ip.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } + }, }, { - name: "first known IP", - initialState: func() *ipTracker { + name: "first known IP of node tracking subnet", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), + }, ip: ip, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.mostRecentTrackedIPs[ip.NodeID] = ip + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Inc() + tracker.tracked[ip.NodeID].ip = ip tracker.bloomAdditions[ip.NodeID] = 1 - tracker.connected[ip.NodeID] = ip - tracker.gossipableIndices[ip.NodeID] = 0 - tracker.gossipableIPs = []*ips.ClaimedIPPort{ + tracker.connected[ip.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } + + subnet := tracker.subnet[constants.PrimaryNetworkID] + subnet.gossipableIndices[ip.NodeID] = 0 + subnet.gossipableIPs = []*ips.ClaimedIPPort{ ip, } + }, + }, + { + name: "first known IP of node not tracking subnet", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), + }, + ip: ip, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].ip = ip + tracker.bloomAdditions[ip.NodeID] = 1 + tracker.connected[ip.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } + }, }, { - name: "connected with older IP", - initialState: func() *ipTracker { + name: "connected with older IP of node tracking subnet", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) require.True(t, tracker.AddIP(newerIP)) return tracker - }(), + }, ip: ip, - expectedState: func() *ipTracker { + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Inc() + tracker.connected[ip.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } + + subnet := tracker.subnet[constants.PrimaryNetworkID] + subnet.gossipableIndices[newerIP.NodeID] = 0 + subnet.gossipableIPs = []*ips.ClaimedIPPort{ + newerIP, + } + }, + }, + { + name: "connected with older IP of node not tracking subnet", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - require.True(t, tracker.AddIP(newerIP)) - tracker.connected[ip.NodeID] = ip + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + require.False(t, tracker.AddIP(newerIP)) return tracker - }(), + }, + ip: ip, + expectedChange: func(tracker *ipTracker) { + tracker.connected[ip.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } + }, }, { - name: "connected with newer IP", - initialState: func() *ipTracker { + name: "connected with newer IP of node tracking subnet", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) require.True(t, tracker.AddIP(ip)) return tracker - }(), + }, ip: newerIP, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - require.True(t, tracker.AddIP(ip)) - tracker.mostRecentTrackedIPs[newerIP.NodeID] = newerIP + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Inc() + tracker.tracked[newerIP.NodeID].ip = newerIP tracker.bloomAdditions[newerIP.NodeID] = 2 - tracker.connected[newerIP.NodeID] = newerIP - tracker.gossipableIndices[newerIP.NodeID] = 0 - tracker.gossipableIPs = []*ips.ClaimedIPPort{ + tracker.connected[newerIP.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: newerIP, + } + + subnet := tracker.subnet[constants.PrimaryNetworkID] + subnet.gossipableIndices[newerIP.NodeID] = 0 + subnet.gossipableIPs = []*ips.ClaimedIPPort{ newerIP, } + }, + }, + { + name: "connected with newer IP of node not tracking subnet", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + require.False(t, tracker.AddIP(ip)) return tracker - }(), + }, + ip: newerIP, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[newerIP.NodeID].ip = newerIP + tracker.bloomAdditions[newerIP.NodeID] = 2 + tracker.connected[newerIP.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: newerIP, + } + }, }, { - name: "connected with same IP", - initialState: func() *ipTracker { + name: "connected with same IP of node tracking subnet", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) require.True(t, tracker.AddIP(ip)) return tracker - }(), + }, ip: ip, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - require.True(t, tracker.AddIP(ip)) - tracker.connected[ip.NodeID] = ip - tracker.gossipableIndices[ip.NodeID] = 0 - tracker.gossipableIPs = []*ips.ClaimedIPPort{ + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Inc() + tracker.connected[ip.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } + + subnet := tracker.subnet[constants.PrimaryNetworkID] + subnet.gossipableIndices[ip.NodeID] = 0 + subnet.gossipableIPs = []*ips.ClaimedIPPort{ ip, } + }, + }, + { + name: "connected with same IP of node not tracking subnet", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + require.False(t, tracker.AddIP(ip)) return tracker - }(), + }, + ip: ip, + expectedChange: func(tracker *ipTracker) { + tracker.connected[ip.NodeID] = &connectedNode{ + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } + }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - test.initialState.Connected(test.ip) - requireEqual(t, test.expectedState, test.initialState) - requireMetricsConsistent(t, test.initialState) + testState := test.initialState(t) + expectedState := test.initialState(t) + + testState.Connected(test.ip, set.Of(constants.PrimaryNetworkID)) + test.expectedChange(expectedState) + + requireEqual(t, expectedState, testState) + requireMetricsConsistent(t, testState) }) } } func TestIPTracker_Disconnected(t *testing.T) { + subnetID := ids.GenerateTestID() tests := []struct { - name string - initialState *ipTracker - nodeID ids.NodeID - expectedState *ipTracker + name string + initialState func(t *testing.T) *ipTracker + expectedChange func(*ipTracker) }{ - { - name: "not tracked", - initialState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.Connected(ip) - return tracker - }(), - nodeID: ip.NodeID, - expectedState: newTestIPTracker(t), - }, { name: "not gossipable", - initialState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.ManuallyTrack(ip.NodeID) - return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.ManuallyTrack(ip.NodeID) - delete(tracker.connected, ip.NodeID) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), + }, + expectedChange: func(*ipTracker) {}, }, { name: "latest gossipable", - initialState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) + }, + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Dec() delete(tracker.connected, ip.NodeID) - delete(tracker.gossipableIndices, ip.NodeID) - tracker.gossipableIPs = tracker.gossipableIPs[:0] - return tracker - }(), + + subnet := tracker.subnet[constants.PrimaryNetworkID] + delete(subnet.gossipableIndices, ip.NodeID) + subnet.gossipableIPs = subnet.gossipableIPs[:0] + }, }, { name: "non-latest gossipable", - initialState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - tracker.OnValidatorAdded(otherIP.NodeID, nil, ids.Empty, 0) - tracker.Connected(otherIP) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, otherIP.NodeID, nil, ids.Empty, 0) + tracker.Connected(otherIP, set.Of(constants.PrimaryNetworkID)) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - tracker.OnValidatorAdded(otherIP.NodeID, nil, ids.Empty, 0) - tracker.Connected(otherIP) + }, + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Dec() delete(tracker.connected, ip.NodeID) - tracker.gossipableIndices = map[ids.NodeID]int{ + + subnet := tracker.subnet[constants.PrimaryNetworkID] + subnet.gossipableIndices = map[ids.NodeID]int{ otherIP.NodeID: 0, } - tracker.gossipableIPs = []*ips.ClaimedIPPort{ + subnet.gossipableIPs = []*ips.ClaimedIPPort{ otherIP, } + }, + }, + { + name: "remove multiple gossipable IPs", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID, subnetID)) return tracker - }(), + }, + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Add(-2) + delete(tracker.connected, ip.NodeID) + + primarySubnet := tracker.subnet[constants.PrimaryNetworkID] + delete(primarySubnet.gossipableIndices, ip.NodeID) + primarySubnet.gossipableIPs = primarySubnet.gossipableIPs[:0] + + subnet := tracker.subnet[subnetID] + delete(subnet.gossipableIndices, ip.NodeID) + subnet.gossipableIPs = subnet.gossipableIPs[:0] + }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - test.initialState.Disconnected(test.nodeID) - requireEqual(t, test.expectedState, test.initialState) - requireMetricsConsistent(t, test.initialState) + testState := test.initialState(t) + expectedState := test.initialState(t) + + testState.Disconnected(ip.NodeID) + expectedState.Disconnected(ip.NodeID) + + requireEqual(t, expectedState, testState) + requireMetricsConsistent(t, testState) }) } } func TestIPTracker_OnValidatorAdded(t *testing.T) { newerIP := newerTestIP(ip) - + subnetID := ids.GenerateTestID() tests := []struct { - name string - initialState *ipTracker - nodeID ids.NodeID - expectedState *ipTracker + name string + initialState func(t *testing.T) *ipTracker + subnetID ids.ID + expectedChange func(*ipTracker) }{ { name: "manually tracked", - initialState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) tracker.ManuallyTrack(ip.NodeID) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID].validatedSubnets.Add(constants.PrimaryNetworkID) + tracker.tracked[ip.NodeID].trackedSubnets.Add(constants.PrimaryNetworkID) + tracker.subnet[constants.PrimaryNetworkID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: make(map[ids.NodeID]int), + } + }, + }, + { + name: "manually tracked and connected", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) tracker.ManuallyTrack(ip.NodeID) - tracker.gossipableIDs.Add(ip.NodeID) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Inc() + tracker.tracked[ip.NodeID].validatedSubnets.Add(constants.PrimaryNetworkID) + tracker.tracked[ip.NodeID].trackedSubnets.Add(constants.PrimaryNetworkID) + tracker.subnet[constants.PrimaryNetworkID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: map[ids.NodeID]int{ + ip.NodeID: 0, + }, + gossipableIPs: []*ips.ClaimedIPPort{ + ip, + }, + } + }, }, { name: "manually tracked and connected with older IP", - initialState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) tracker.ManuallyTrack(ip.NodeID) - tracker.Connected(ip) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) require.True(t, tracker.AddIP(newerIP)) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.ManuallyTrack(ip.NodeID) - tracker.Connected(ip) - require.True(t, tracker.AddIP(newerIP)) - tracker.gossipableIDs.Add(ip.NodeID) - return tracker - }(), + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Inc() + tracker.tracked[ip.NodeID].validatedSubnets.Add(constants.PrimaryNetworkID) + tracker.tracked[ip.NodeID].trackedSubnets.Add(constants.PrimaryNetworkID) + tracker.subnet[constants.PrimaryNetworkID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: map[ids.NodeID]int{ + ip.NodeID: 0, + }, + gossipableIPs: []*ips.ClaimedIPPort{ + newerIP, + }, + } + }, }, { name: "manually gossiped", - initialState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.ManuallyGossip(ip.NodeID) + tracker.ManuallyGossip(constants.PrimaryNetworkID, ip.NodeID) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.ManuallyGossip(ip.NodeID) - return tracker - }(), + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(*ipTracker) {}, }, { name: "disconnected", - initialState: newTestIPTracker(t), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.trackedIDs.Add(ip.NodeID) - tracker.gossipableIDs.Add(ip.NodeID) - return tracker - }(), + initialState: newTestIPTracker, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.tracked[ip.NodeID] = &trackedNode{ + validatedSubnets: set.Of(constants.PrimaryNetworkID), + trackedSubnets: set.Of(constants.PrimaryNetworkID), + } + tracker.subnet[constants.PrimaryNetworkID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: make(map[ids.NodeID]int), + } + }, }, { name: "connected", - initialState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.Connected(ip) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.mostRecentTrackedIPs[ip.NodeID] = ip - tracker.trackedIDs.Add(ip.NodeID) + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Inc() + tracker.tracked[ip.NodeID] = &trackedNode{ + validatedSubnets: set.Of(constants.PrimaryNetworkID), + trackedSubnets: set.Of(constants.PrimaryNetworkID), + ip: ip, + } tracker.bloomAdditions[ip.NodeID] = 1 - tracker.gossipableIndices[ip.NodeID] = 0 - tracker.gossipableIPs = []*ips.ClaimedIPPort{ - ip, + tracker.subnet[constants.PrimaryNetworkID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: map[ids.NodeID]int{ + ip.NodeID: 0, + }, + gossipableIPs: []*ips.ClaimedIPPort{ + ip, + }, } - tracker.gossipableIDs.Add(ip.NodeID) + }, + }, + { + name: "connected to other subnet", + initialState: func(t *testing.T) *ipTracker { + tracker := newTestIPTracker(t) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), + }, + subnetID: subnetID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedSubnets.Inc() + tracker.tracked[ip.NodeID] = &trackedNode{ + validatedSubnets: set.Of(subnetID), + ip: ip, + } + tracker.bloomAdditions[ip.NodeID] = 1 + tracker.subnet[subnetID] = &gossipableSubnet{ + numGossipableIPs: tracker.numGossipableIPs, + gossipableIDs: set.Of(ip.NodeID), + gossipableIndices: make(map[ids.NodeID]int), + } + }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - test.initialState.OnValidatorAdded(test.nodeID, nil, ids.Empty, 0) - requireEqual(t, test.expectedState, test.initialState) - requireMetricsConsistent(t, test.initialState) + testState := test.initialState(t) + expectedState := test.initialState(t) + + testState.OnValidatorAdded(test.subnetID, ip.NodeID, nil, ids.Empty, 0) + test.expectedChange(expectedState) + + requireEqual(t, expectedState, testState) + requireMetricsConsistent(t, testState) }) } } func TestIPTracker_OnValidatorRemoved(t *testing.T) { + subnetID := ids.GenerateTestID() tests := []struct { - name string - initialState *ipTracker - nodeID ids.NodeID - expectedState *ipTracker + name string + initialState func(t *testing.T) *ipTracker + subnetID ids.ID + expectedChange func(*ipTracker) }{ { - name: "manually tracked not gossipable", - initialState: func() *ipTracker { + name: "remove last validator of subnet", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.ManuallyTrack(ip.NodeID) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - require.True(t, tracker.AddIP(ip)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedPeers.Dec() + tracker.numTrackedSubnets.Dec() + delete(tracker.tracked, ip.NodeID) + delete(tracker.subnet, constants.PrimaryNetworkID) + }, + }, + { + name: "manually tracked not gossipable", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) tracker.ManuallyTrack(ip.NodeID) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) require.True(t, tracker.AddIP(ip)) - tracker.gossipableIDs.Remove(ip.NodeID) return tracker - }(), + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedSubnets.Dec() + + node := tracker.tracked[ip.NodeID] + node.validatedSubnets.Remove(constants.PrimaryNetworkID) + node.trackedSubnets.Remove(constants.PrimaryNetworkID) + + delete(tracker.subnet, constants.PrimaryNetworkID) + }, }, { name: "manually tracked latest gossipable", - initialState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.ManuallyTrack(ip.NodeID) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) tracker.ManuallyTrack(ip.NodeID) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - delete(tracker.gossipableIndices, ip.NodeID) - tracker.gossipableIPs = tracker.gossipableIPs[:0] - tracker.gossipableIDs.Remove(ip.NodeID) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numGossipableIPs.Dec() + tracker.numTrackedSubnets.Dec() + + node := tracker.tracked[ip.NodeID] + node.validatedSubnets.Remove(constants.PrimaryNetworkID) + node.trackedSubnets.Remove(constants.PrimaryNetworkID) + + delete(tracker.subnet, constants.PrimaryNetworkID) + }, }, { name: "manually gossiped", - initialState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.ManuallyGossip(ip.NodeID) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.ManuallyGossip(ip.NodeID) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) + tracker.ManuallyGossip(constants.PrimaryNetworkID, ip.NodeID) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(*ipTracker) {}, }, { - name: "not gossipable", - initialState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - require.True(t, tracker.AddIP(ip)) - return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { + name: "manually gossiped on other subnet", + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - require.True(t, tracker.AddIP(ip)) - delete(tracker.mostRecentTrackedIPs, ip.NodeID) - tracker.trackedIDs.Remove(ip.NodeID) - tracker.gossipableIDs.Remove(ip.NodeID) + tracker.ManuallyGossip(constants.PrimaryNetworkID, ip.NodeID) + tracker.OnValidatorAdded(subnetID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) return tracker - }(), - }, - { - name: "latest gossipable", - initialState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - delete(tracker.mostRecentTrackedIPs, ip.NodeID) - tracker.trackedIDs.Remove(ip.NodeID) - delete(tracker.gossipableIndices, ip.NodeID) - tracker.gossipableIPs = tracker.gossipableIPs[:0] - tracker.gossipableIDs.Remove(ip.NodeID) - return tracker - }(), + }, + subnetID: subnetID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedSubnets.Dec() + tracker.tracked[ip.NodeID].validatedSubnets.Remove(subnetID) + delete(tracker.subnet, subnetID) + }, }, { name: "non-latest gossipable", - initialState: func() *ipTracker { + initialState: func(t *testing.T) *ipTracker { tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - tracker.OnValidatorAdded(otherIP.NodeID, nil, ids.Empty, 0) - tracker.Connected(otherIP) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, otherIP.NodeID, nil, ids.Empty, 0) + tracker.Connected(otherIP, set.Of(constants.PrimaryNetworkID)) return tracker - }(), - nodeID: ip.NodeID, - expectedState: func() *ipTracker { - tracker := newTestIPTracker(t) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.Connected(ip) - tracker.OnValidatorAdded(otherIP.NodeID, nil, ids.Empty, 0) - tracker.Connected(otherIP) - delete(tracker.mostRecentTrackedIPs, ip.NodeID) - tracker.trackedIDs.Remove(ip.NodeID) - tracker.gossipableIndices = map[ids.NodeID]int{ + }, + subnetID: constants.PrimaryNetworkID, + expectedChange: func(tracker *ipTracker) { + tracker.numTrackedPeers.Dec() + tracker.numGossipableIPs.Dec() + delete(tracker.tracked, ip.NodeID) + + subnet := tracker.subnet[constants.PrimaryNetworkID] + subnet.gossipableIDs.Remove(ip.NodeID) + subnet.gossipableIndices = map[ids.NodeID]int{ otherIP.NodeID: 0, } - tracker.gossipableIPs = []*ips.ClaimedIPPort{ + subnet.gossipableIPs = []*ips.ClaimedIPPort{ otherIP, } - tracker.gossipableIDs.Remove(ip.NodeID) - return tracker - }(), + }, }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - test.initialState.OnValidatorRemoved(test.nodeID, 0) - requireEqual(t, test.expectedState, test.initialState) - requireMetricsConsistent(t, test.initialState) - }) - } -} - -func TestIPTracker_GetGossipableIPs(t *testing.T) { - require := require.New(t) - - tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.Connected(otherIP) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.OnValidatorAdded(otherIP.NodeID, nil, ids.Empty, 0) + testState := test.initialState(t) + expectedState := test.initialState(t) - gossipableIPs := tracker.GetGossipableIPs(ids.EmptyNodeID, bloom.EmptyFilter, nil, 2) - require.ElementsMatch([]*ips.ClaimedIPPort{ip, otherIP}, gossipableIPs) - - gossipableIPs = tracker.GetGossipableIPs(ip.NodeID, bloom.EmptyFilter, nil, 2) - require.Equal([]*ips.ClaimedIPPort{otherIP}, gossipableIPs) - - gossipableIPs = tracker.GetGossipableIPs(ids.EmptyNodeID, bloom.FullFilter, nil, 2) - require.Empty(gossipableIPs) - - filter, err := bloom.New(8, 1024) - require.NoError(err) - bloom.Add(filter, ip.GossipID[:], nil) - - readFilter, err := bloom.Parse(filter.Marshal()) - require.NoError(err) + testState.OnValidatorRemoved(test.subnetID, ip.NodeID, 0) + test.expectedChange(expectedState) - gossipableIPs = tracker.GetGossipableIPs(ip.NodeID, readFilter, nil, 2) - require.Equal([]*ips.ClaimedIPPort{otherIP}, gossipableIPs) -} - -func TestIPTracker_BloomFiltersEverything(t *testing.T) { - require := require.New(t) - - tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.Connected(otherIP) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.OnValidatorAdded(otherIP.NodeID, nil, ids.Empty, 0) - - bloomBytes, salt := tracker.Bloom() - readFilter, err := bloom.Parse(bloomBytes) - require.NoError(err) - - gossipableIPs := tracker.GetGossipableIPs(ids.EmptyNodeID, readFilter, salt, 2) - require.Empty(gossipableIPs) - - require.NoError(tracker.ResetBloom()) + requireEqual(t, expectedState, testState) + requireMetricsConsistent(t, testState) + }) + } } func TestIPTracker_BloomGrows(t *testing.T) { @@ -837,7 +1178,7 @@ func TestIPTracker_BloomGrows(t *testing.T) { { name: "Add Validator", add: func(tracker *ipTracker) { - tracker.OnValidatorAdded(ids.GenerateTestNodeID(), nil, ids.Empty, 0) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ids.GenerateTestNodeID(), nil, ids.Empty, 0) }, }, { @@ -846,6 +1187,12 @@ func TestIPTracker_BloomGrows(t *testing.T) { tracker.ManuallyTrack(ids.GenerateTestNodeID()) }, }, + { + name: "Manually Gossip", + add: func(tracker *ipTracker) { + tracker.ManuallyGossip(ids.GenerateTestID(), ids.GenerateTestNodeID()) + }, + }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { @@ -869,12 +1216,13 @@ func TestIPTracker_BloomResetsDynamically(t *testing.T) { require := require.New(t) tracker := newTestIPTracker(t) - tracker.Connected(ip) - tracker.OnValidatorAdded(ip.NodeID, nil, ids.Empty, 0) - tracker.OnValidatorRemoved(ip.NodeID, 0) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorRemoved(constants.PrimaryNetworkID, ip.NodeID, 0) + tracker.maxBloomCount = 1 - tracker.Connected(otherIP) - tracker.OnValidatorAdded(otherIP.NodeID, nil, ids.Empty, 0) + tracker.Connected(otherIP, set.Of(constants.PrimaryNetworkID)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, otherIP.NodeID, nil, ids.Empty, 0) requireMetricsConsistent(t, tracker) bloomBytes, salt := tracker.Bloom() @@ -892,7 +1240,7 @@ func TestIPTracker_PreventBloomFilterAddition(t *testing.T) { newestIP := newerTestIP(newerIP) tracker := newTestIPTracker(t) - tracker.ManuallyGossip(ip.NodeID) + tracker.ManuallyGossip(constants.PrimaryNetworkID, ip.NodeID) require.True(tracker.AddIP(ip)) require.True(tracker.AddIP(newerIP)) require.True(tracker.AddIP(newestIP)) @@ -900,18 +1248,133 @@ func TestIPTracker_PreventBloomFilterAddition(t *testing.T) { requireMetricsConsistent(t, tracker) } -func TestIPTracker_ShouldVerifyIP(t *testing.T) { - require := require.New(t) - - newerIP := newerTestIP(ip) +func TestIPTracker_GetGossipableIPs(t *testing.T) { + subnetIDA := ids.GenerateTestID() + subnetIDB := ids.GenerateTestID() + unknownSubnetID := ids.GenerateTestID() tracker := newTestIPTracker(t) - require.False(tracker.ShouldVerifyIP(ip)) - tracker.ManuallyTrack(ip.NodeID) - require.True(tracker.ShouldVerifyIP(ip)) - tracker.ManuallyGossip(ip.NodeID) - require.True(tracker.ShouldVerifyIP(ip)) - require.True(tracker.AddIP(ip)) - require.False(tracker.ShouldVerifyIP(ip)) - require.True(tracker.ShouldVerifyIP(newerIP)) + tracker.Connected(ip, set.Of(constants.PrimaryNetworkID, subnetIDA)) + tracker.Connected(otherIP, set.Of(constants.PrimaryNetworkID, subnetIDA, subnetIDB)) + tracker.OnValidatorAdded(constants.PrimaryNetworkID, ip.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(subnetIDA, otherIP.NodeID, nil, ids.Empty, 0) + tracker.OnValidatorAdded(subnetIDB, otherIP.NodeID, nil, ids.Empty, 0) + + myFilterBytes, mySalt := tracker.Bloom() + myFilter, err := bloom.Parse(myFilterBytes) + require.NoError(t, err) + + tests := []struct { + name string + toIterate set.Set[ids.ID] + allowed set.Set[ids.ID] + nodeID ids.NodeID + filter *bloom.ReadFilter + salt []byte + expected []*ips.ClaimedIPPort + }{ + { + name: "fetch both subnets IPs", + toIterate: set.Of(constants.PrimaryNetworkID, subnetIDA), + allowed: set.Of(constants.PrimaryNetworkID, subnetIDA), + nodeID: ids.EmptyNodeID, + filter: bloom.EmptyFilter, + salt: nil, + expected: []*ips.ClaimedIPPort{ip, otherIP}, + }, + { + name: "filter nodeID", + toIterate: set.Of(constants.PrimaryNetworkID, subnetIDA), + allowed: set.Of(constants.PrimaryNetworkID, subnetIDA), + nodeID: ip.NodeID, + filter: bloom.EmptyFilter, + salt: nil, + expected: []*ips.ClaimedIPPort{otherIP}, + }, + { + name: "filter duplicate nodeIDs", + toIterate: set.Of(subnetIDA, subnetIDB), + allowed: set.Of(subnetIDA, subnetIDB), + nodeID: ids.EmptyNodeID, + filter: bloom.EmptyFilter, + salt: nil, + expected: []*ips.ClaimedIPPort{otherIP}, + }, + { + name: "filter known IPs", + toIterate: set.Of(constants.PrimaryNetworkID, subnetIDA), + allowed: set.Of(constants.PrimaryNetworkID, subnetIDA), + nodeID: ids.EmptyNodeID, + filter: func() *bloom.ReadFilter { + filter, err := bloom.New(8, 1024) + require.NoError(t, err) + bloom.Add(filter, ip.GossipID[:], nil) + + readFilter, err := bloom.Parse(filter.Marshal()) + require.NoError(t, err) + return readFilter + }(), + salt: nil, + expected: []*ips.ClaimedIPPort{otherIP}, + }, + { + name: "filter everything", + toIterate: set.Of(constants.PrimaryNetworkID, subnetIDA, subnetIDB), + allowed: set.Of(constants.PrimaryNetworkID, subnetIDA, subnetIDB), + nodeID: ids.EmptyNodeID, + filter: myFilter, + salt: mySalt, + expected: nil, + }, + { + name: "only fetch primary network IPs", + toIterate: set.Of(constants.PrimaryNetworkID), + allowed: set.Of(constants.PrimaryNetworkID), + nodeID: ids.EmptyNodeID, + filter: bloom.EmptyFilter, + salt: nil, + expected: []*ips.ClaimedIPPort{ip}, + }, + { + name: "only fetch subnet IPs", + toIterate: set.Of(subnetIDA), + allowed: set.Of(subnetIDA), + nodeID: ids.EmptyNodeID, + filter: bloom.EmptyFilter, + salt: nil, + expected: []*ips.ClaimedIPPort{otherIP}, + }, + { + name: "filter subnet", + toIterate: set.Of(constants.PrimaryNetworkID, subnetIDA), + allowed: set.Of(constants.PrimaryNetworkID), + nodeID: ids.EmptyNodeID, + filter: bloom.EmptyFilter, + salt: nil, + expected: []*ips.ClaimedIPPort{ip}, + }, + { + name: "skip unknown subnet", + toIterate: set.Of(unknownSubnetID), + allowed: set.Of(unknownSubnetID), + nodeID: ids.EmptyNodeID, + filter: bloom.EmptyFilter, + salt: nil, + expected: nil, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + gossipableIPs := getGossipableIPs( + tracker, + test.toIterate, + test.allowed.Contains, + test.nodeID, + test.filter, + test.salt, + 2, + ) + require.ElementsMatch(t, test.expected, gossipableIPs) + }) + } } diff --git a/network/network.go b/network/network.go index 94993a129d81..9f785f34bd05 100644 --- a/network/network.go +++ b/network/network.go @@ -235,16 +235,16 @@ func NewNetwork( return nil, fmt.Errorf("initializing network metrics failed with: %w", err) } - ipTracker, err := newIPTracker(log, metricsRegisterer) + ipTracker, err := newIPTracker(config.TrackedSubnets, log, metricsRegisterer) if err != nil { return nil, fmt.Errorf("initializing ip tracker failed with: %w", err) } - config.Validators.RegisterSetCallbackListener(constants.PrimaryNetworkID, ipTracker) + config.Validators.RegisterCallbackListener(ipTracker) // Track all default bootstrappers to ensure their current IPs are gossiped // like validator IPs. for _, bootstrapper := range genesis.GetBootstrappers(config.NetworkID) { - ipTracker.ManuallyGossip(bootstrapper.ID) + ipTracker.ManuallyGossip(constants.PrimaryNetworkID, bootstrapper.ID) } // Track all recent validators to optimistically connect to them before the // P-chain has finished syncing. @@ -263,6 +263,7 @@ func NewNetwork( Network: nil, // This is set below. Router: router, VersionCompatibility: version.GetCompatibility(minCompatibleTime), + MyNodeID: config.MyNodeID, MySubnets: config.TrackedSubnets, Beacons: config.Beacons, Validators: config.Validators, @@ -454,14 +455,13 @@ func (n *network) Connected(nodeID ids.NodeID) { peerIP.Timestamp, peerIP.TLSSignature, ) - n.ipTracker.Connected(newIP) + trackedSubnets := peer.TrackedSubnets() + n.ipTracker.Connected(newIP, trackedSubnets) n.metrics.markConnected(peer) peerVersion := peer.Version() n.router.Connected(nodeID, peerVersion, constants.PrimaryNetworkID) - - trackedSubnets := peer.TrackedSubnets() for subnetID := range n.peerConfig.MySubnets { if trackedSubnets.Contains(subnetID) { n.router.Connected(nodeID, peerVersion, subnetID) @@ -477,13 +477,14 @@ func (n *network) AllowConnection(nodeID ids.NodeID) bool { if !n.config.RequireValidatorToConnect { return true } - _, iAmAValidator := n.config.Validators.GetValidator(constants.PrimaryNetworkID, n.config.MyNodeID) - return iAmAValidator || n.ipTracker.WantsConnection(nodeID) + _, areWeAPrimaryNetworkAValidator := n.config.Validators.GetValidator(constants.PrimaryNetworkID, n.config.MyNodeID) + return areWeAPrimaryNetworkAValidator || n.ipTracker.WantsConnection(nodeID) } func (n *network) Track(claimedIPPorts []*ips.ClaimedIPPort) error { + _, areWeAPrimaryNetworkAValidator := n.config.Validators.GetValidator(constants.PrimaryNetworkID, n.config.MyNodeID) for _, ip := range claimedIPPorts { - if err := n.track(ip); err != nil { + if err := n.track(ip, areWeAPrimaryNetworkAValidator); err != nil { return err } } @@ -513,9 +514,61 @@ func (n *network) KnownPeers() ([]byte, []byte) { return n.ipTracker.Bloom() } -func (n *network) Peers(except ids.NodeID, knownPeers *bloom.ReadFilter, salt []byte) []*ips.ClaimedIPPort { - return n.ipTracker.GetGossipableIPs( - except, +// There are 3 types of responses: +// +// - Respond with subnet IPs tracked by both ourselves and the peer +// - We do not consider ourself to be a primary network validator +// +// - Respond with all subnet IPs +// - The peer requests all peers +// - We believe the peer to be a primary network validator +// - We believe ourself to be a primary network validator +// +// - Respond with subnet IPs tracked by the peer +// - Either the peer does not request all peers or we don't consider them to +// be a primary network validator +// - We believe ourself to be a primary network validator +// +// The reason we allow the peer to request all peers is so that we can avoid +// sending unnecessary data in the case that we consider them a primary network +// validator but they do not consider themselves one. +func (n *network) Peers( + peerID ids.NodeID, + trackedSubnets set.Set[ids.ID], + requestAllPeers bool, + knownPeers *bloom.ReadFilter, + salt []byte, +) []*ips.ClaimedIPPort { + _, areWeAPrimaryNetworkValidator := n.config.Validators.GetValidator(constants.PrimaryNetworkID, n.config.MyNodeID) + + // Only return IPs for subnets that we are tracking. + var allowedSubnets func(ids.ID) bool + if areWeAPrimaryNetworkValidator { + allowedSubnets = func(ids.ID) bool { return true } + } else { + allowedSubnets = func(subnetID ids.ID) bool { + return subnetID == constants.PrimaryNetworkID || n.ipTracker.trackedSubnets.Contains(subnetID) + } + } + + _, areTheyAPrimaryNetworkValidator := n.config.Validators.GetValidator(constants.PrimaryNetworkID, peerID) + if areWeAPrimaryNetworkValidator && requestAllPeers && areTheyAPrimaryNetworkValidator { + // Return IPs for all subnets. + return getGossipableIPs( + n.ipTracker, + n.ipTracker.subnet, + allowedSubnets, + peerID, + knownPeers, + salt, + int(n.config.PeerListNumValidatorIPs), + ) + } + return getGossipableIPs( + n.ipTracker, + trackedSubnets, + allowedSubnets, + peerID, knownPeers, salt, int(n.config.PeerListNumValidatorIPs), @@ -621,7 +674,7 @@ func (n *network) ManuallyTrack(nodeID ids.NodeID, ip netip.AddrPort) { } } -func (n *network) track(ip *ips.ClaimedIPPort) error { +func (n *network) track(ip *ips.ClaimedIPPort, trackAllSubnets bool) error { // To avoid signature verification when the IP isn't needed, we // optimistically filter out IPs. This can result in us not tracking an IP // that we otherwise would have. This case can only happen if the node @@ -630,7 +683,7 @@ func (n *network) track(ip *ips.ClaimedIPPort) error { // // Note: Avoiding signature verification when the IP isn't needed is a // **significant** performance optimization. - if !n.ipTracker.ShouldVerifyIP(ip) { + if !n.ipTracker.ShouldVerifyIP(ip, trackAllSubnets) { n.metrics.numUselessPeerListBytes.Add(float64(ip.Size())) return nil } @@ -698,9 +751,9 @@ func (n *network) getPeers( continue } - _, isValidator := n.config.Validators.GetValidator(subnetID, nodeID) + _, areTheyAValidator := n.config.Validators.GetValidator(subnetID, nodeID) // check if the peer is allowed to connect to the subnet - if !allower.IsAllowed(nodeID, isValidator) { + if !allower.IsAllowed(nodeID, areTheyAValidator) { continue } @@ -741,9 +794,9 @@ func (n *network) samplePeers( return false } - _, isValidator := n.config.Validators.GetValidator(subnetID, peerID) + _, areTheyAValidator := n.config.Validators.GetValidator(subnetID, peerID) // check if the peer is allowed to connect to the subnet - if !allower.IsAllowed(peerID, isValidator) { + if !allower.IsAllowed(peerID, areTheyAValidator) { return false } @@ -752,7 +805,7 @@ func (n *network) samplePeers( return true } - if isValidator { + if areTheyAValidator { numValidatorsToSample-- return numValidatorsToSample >= 0 } diff --git a/network/peer/config.go b/network/peer/config.go index 8aa12820cc41..4ee52ecf48e0 100644 --- a/network/peer/config.go +++ b/network/peer/config.go @@ -33,6 +33,7 @@ type Config struct { Network Network Router router.InboundHandler VersionCompatibility version.Compatibility + MyNodeID ids.NodeID // MySubnets does not include the primary network ID MySubnets set.Set[ids.ID] Beacons validators.Manager diff --git a/network/peer/network.go b/network/peer/network.go index b8fb01814546..19161321f1c3 100644 --- a/network/peer/network.go +++ b/network/peer/network.go @@ -7,6 +7,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/bloom" "github.com/ava-labs/avalanchego/utils/ips" + "github.com/ava-labs/avalanchego/utils/set" ) // Network defines the interface that is used by a peer to help establish a well @@ -35,6 +36,8 @@ type Network interface { // Peers returns peers that are not known. Peers( peerID ids.NodeID, + trackedSubnets set.Set[ids.ID], + requestAllPeers bool, knownPeers *bloom.ReadFilter, peerSalt []byte, ) []*ips.ClaimedIPPort diff --git a/network/peer/peer.go b/network/peer/peer.go index a92791ff72ee..c424c1fbdccd 100644 --- a/network/peer/peer.go +++ b/network/peer/peer.go @@ -534,6 +534,7 @@ func (p *peer) writeMessages() { myVersion := p.VersionCompatibility.Version() knownPeersFilter, knownPeersSalt := p.Network.KnownPeers() + _, areWeAPrimaryNetworkValidator := p.Validators.GetValidator(constants.PrimaryNetworkID, p.MyNodeID) msg, err := p.MessageCreator.Handshake( p.NetworkID, p.Clock.Unix(), @@ -550,6 +551,7 @@ func (p *peer) writeMessages() { p.ObjectedACPs, knownPeersFilter, knownPeersSalt, + areWeAPrimaryNetworkValidator, ) if err != nil { p.Log.Error(failedToCreateMessageLog, @@ -643,7 +645,12 @@ func (p *peer) sendNetworkMessages() { select { case <-p.getPeerListChan: knownPeersFilter, knownPeersSalt := p.Config.Network.KnownPeers() - msg, err := p.Config.MessageCreator.GetPeerList(knownPeersFilter, knownPeersSalt) + _, areWeAPrimaryNetworkValidator := p.Validators.GetValidator(constants.PrimaryNetworkID, p.MyNodeID) + msg, err := p.Config.MessageCreator.GetPeerList( + knownPeersFilter, + knownPeersSalt, + areWeAPrimaryNetworkValidator, + ) if err != nil { p.Log.Error(failedToCreateMessageLog, zap.Stringer("nodeID", p.id), @@ -1113,7 +1120,7 @@ func (p *peer) handleHandshake(msg *p2p.Handshake) { p.gotHandshake.Set(true) - peerIPs := p.Network.Peers(p.id, knownPeers, salt) + peerIPs := p.Network.Peers(p.id, p.trackedSubnets, msg.AllSubnets, knownPeers, salt) // We bypass throttling here to ensure that the handshake message is // acknowledged correctly. @@ -1175,7 +1182,7 @@ func (p *peer) handleGetPeerList(msg *p2p.GetPeerList) { return } - peerIPs := p.Network.Peers(p.id, filter, salt) + peerIPs := p.Network.Peers(p.id, p.trackedSubnets, msg.AllSubnets, filter, salt) if len(peerIPs) == 0 { p.Log.Debug("skipping sending of empty peer list", zap.Stringer("nodeID", p.id), diff --git a/network/peer/peer_test.go b/network/peer/peer_test.go index 316b491180af..0ae75b571f27 100644 --- a/network/peer/peer_test.go +++ b/network/peer/peer_test.go @@ -42,7 +42,6 @@ type testPeer struct { type rawTestPeer struct { config *Config cert *staking.Certificate - nodeID ids.NodeID inboundMsgChan <-chan message.InboundMessage } @@ -106,7 +105,7 @@ func newRawTestPeer(t *testing.T, config Config) *rawTestPeer { require.NoError(err) cert, err := staking.ParseCertificate(tlsCert.Leaf.Raw) require.NoError(err) - nodeID := ids.NodeIDFromCert(cert) + config.MyNodeID = ids.NodeIDFromCert(cert) ip := utils.NewAtomic(netip.AddrPortFrom( netip.IPv6Loopback(), @@ -126,7 +125,6 @@ func newRawTestPeer(t *testing.T, config Config) *rawTestPeer { return &rawTestPeer{ config: &config, cert: cert, - nodeID: nodeID, inboundMsgChan: inboundMsgChan, } } @@ -137,10 +135,10 @@ func startTestPeer(self *rawTestPeer, peer *rawTestPeer, conn net.Conn) *testPee self.config, conn, peer.cert, - peer.nodeID, + peer.config.MyNodeID, NewThrottledMessageQueue( self.config.Metrics, - peer.nodeID, + peer.config.MyNodeID, logging.NoLog{}, throttling.NewNoOutboundThrottler(), ), @@ -411,7 +409,7 @@ func TestInvalidBLSKeyDisconnects(t *testing.T) { require.NoError(rawPeer0.config.Validators.AddStaker( constants.PrimaryNetworkID, - rawPeer1.nodeID, + rawPeer1.config.MyNodeID, bls.PublicFromSecretKey(rawPeer1.config.IPSigner.blsSigner), ids.GenerateTestID(), 1, @@ -421,7 +419,7 @@ func TestInvalidBLSKeyDisconnects(t *testing.T) { require.NoError(err) require.NoError(rawPeer1.config.Validators.AddStaker( constants.PrimaryNetworkID, - rawPeer0.nodeID, + rawPeer0.config.MyNodeID, bls.PublicFromSecretKey(bogusBLSKey), // This is the wrong BLS key for this peer ids.GenerateTestID(), 1, diff --git a/network/peer/test_network.go b/network/peer/test_network.go index 01a341ae9abc..b38c7788081e 100644 --- a/network/peer/test_network.go +++ b/network/peer/test_network.go @@ -7,6 +7,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/bloom" "github.com/ava-labs/avalanchego/utils/ips" + "github.com/ava-labs/avalanchego/utils/set" ) var TestNetwork Network = testNetwork{} @@ -29,6 +30,12 @@ func (testNetwork) KnownPeers() ([]byte, []byte) { return bloom.EmptyFilter.Marshal(), nil } -func (testNetwork) Peers(ids.NodeID, *bloom.ReadFilter, []byte) []*ips.ClaimedIPPort { +func (testNetwork) Peers( + ids.NodeID, + set.Set[ids.ID], + bool, + *bloom.ReadFilter, + []byte, +) []*ips.ClaimedIPPort { return nil } diff --git a/proto/p2p/p2p.proto b/proto/p2p/p2p.proto index 7935ef6e44a5..7df36717c56e 100644 --- a/proto/p2p/p2p.proto +++ b/proto/p2p/p2p.proto @@ -112,6 +112,9 @@ message Handshake { // Signature of the peer IP port pair at a provided timestamp with the BLS // key. bytes ip_bls_sig = 13; + // To avoid sending IPs that the client isn't interested in tracking, the + // server expects the client to confirm that it is tracking all subnets. + bool all_subnets = 14; } // Metadata about a peer's P2P client used to determine compatibility @@ -154,6 +157,7 @@ message ClaimedIpPort { // filter. message GetPeerList { BloomFilter known_peers = 1; + bool all_subnets = 2; } // PeerList contains network-level metadata for a set of validators. diff --git a/proto/pb/p2p/p2p.pb.go b/proto/pb/p2p/p2p.pb.go index df754b0e2d74..9b10923bbf20 100644 --- a/proto/pb/p2p/p2p.pb.go +++ b/proto/pb/p2p/p2p.pb.go @@ -679,6 +679,9 @@ type Handshake struct { // Signature of the peer IP port pair at a provided timestamp with the BLS // key. IpBlsSig []byte `protobuf:"bytes,13,opt,name=ip_bls_sig,json=ipBlsSig,proto3" json:"ip_bls_sig,omitempty"` + // To avoid sending IPs that the client isn't interested in tracking, the + // server expects the client to confirm that it is tracking all subnets. + AllSubnets bool `protobuf:"varint,14,opt,name=all_subnets,json=allSubnets,proto3" json:"all_subnets,omitempty"` } func (x *Handshake) Reset() { @@ -797,6 +800,13 @@ func (x *Handshake) GetIpBlsSig() []byte { return nil } +func (x *Handshake) GetAllSubnets() bool { + if x != nil { + return x.AllSubnets + } + return false +} + // Metadata about a peer's P2P client used to determine compatibility type Client struct { state protoimpl.MessageState @@ -1033,6 +1043,7 @@ type GetPeerList struct { unknownFields protoimpl.UnknownFields KnownPeers *BloomFilter `protobuf:"bytes,1,opt,name=known_peers,json=knownPeers,proto3" json:"known_peers,omitempty"` + AllSubnets bool `protobuf:"varint,2,opt,name=all_subnets,json=allSubnets,proto3" json:"all_subnets,omitempty"` } func (x *GetPeerList) Reset() { @@ -1074,6 +1085,13 @@ func (x *GetPeerList) GetKnownPeers() *BloomFilter { return nil } +func (x *GetPeerList) GetAllSubnets() bool { + if x != nil { + return x.AllSubnets + } + return false +} + // PeerList contains network-level metadata for a set of validators. // // PeerList must be sent in response to an inbound Handshake message from a @@ -2640,7 +2658,7 @@ var file_p2p_p2p_proto_rawDesc = []byte{ 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x49, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x75, 0x70, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x75, 0x70, 0x74, 0x69, 0x6d, 0x65, 0x22, 0x12, 0x0a, 0x04, 0x50, 0x6f, 0x6e, - 0x67, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x4a, 0x04, 0x08, 0x02, 0x10, 0x03, 0x22, 0xb3, 0x03, + 0x67, 0x4a, 0x04, 0x08, 0x01, 0x10, 0x02, 0x4a, 0x04, 0x08, 0x02, 0x10, 0x03, 0x22, 0xd4, 0x03, 0x0a, 0x09, 0x48, 0x61, 0x6e, 0x64, 0x73, 0x68, 0x61, 0x6b, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x6e, 0x65, 0x74, 0x77, 0x6f, 0x72, 0x6b, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x6d, 0x79, @@ -2667,202 +2685,206 @@ var file_p2p_p2p_proto_rawDesc = []byte{ 0x0b, 0x32, 0x10, 0x2e, 0x70, 0x32, 0x70, 0x2e, 0x42, 0x6c, 0x6f, 0x6f, 0x6d, 0x46, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x52, 0x0a, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x50, 0x65, 0x65, 0x72, 0x73, 0x12, 0x1c, 0x0a, 0x0a, 0x69, 0x70, 0x5f, 0x62, 0x6c, 0x73, 0x5f, 0x73, 0x69, 0x67, 0x18, 0x0d, 0x20, - 0x01, 0x28, 0x0c, 0x52, 0x08, 0x69, 0x70, 0x42, 0x6c, 0x73, 0x53, 0x69, 0x67, 0x4a, 0x04, 0x08, - 0x05, 0x10, 0x06, 0x22, 0x5e, 0x0a, 0x06, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, 0x12, 0x0a, - 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, - 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, - 0x52, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x12, 0x14, 0x0a, - 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x70, 0x61, - 0x74, 0x63, 0x68, 0x22, 0x39, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x6f, 0x6d, 0x46, 0x69, 0x6c, 0x74, - 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x73, 0x61, - 0x6c, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x73, 0x61, 0x6c, 0x74, 0x22, 0xbd, - 0x01, 0x0a, 0x0d, 0x43, 0x6c, 0x61, 0x69, 0x6d, 0x65, 0x64, 0x49, 0x70, 0x50, 0x6f, 0x72, 0x74, - 0x12, 0x29, 0x0a, 0x10, 0x78, 0x35, 0x30, 0x39, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, - 0x63, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x78, 0x35, 0x30, 0x39, - 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x69, - 0x70, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x69, 0x70, - 0x41, 0x64, 0x64, 0x72, 0x12, 0x17, 0x0a, 0x07, 0x69, 0x70, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x18, - 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x69, 0x70, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x1c, 0x0a, - 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, 0x04, - 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x1c, 0x0a, 0x09, 0x73, - 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, - 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x13, 0x0a, 0x05, 0x74, 0x78, 0x5f, - 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x74, 0x78, 0x49, 0x64, 0x22, 0x40, - 0x0a, 0x0b, 0x47, 0x65, 0x74, 0x50, 0x65, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x31, 0x0a, - 0x0b, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x70, 0x32, 0x70, 0x2e, 0x42, 0x6c, 0x6f, 0x6f, 0x6d, 0x46, 0x69, - 0x6c, 0x74, 0x65, 0x72, 0x52, 0x0a, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x50, 0x65, 0x65, 0x72, 0x73, - 0x22, 0x48, 0x0a, 0x08, 0x50, 0x65, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x3c, 0x0a, 0x10, - 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x65, 0x64, 0x5f, 0x69, 0x70, 0x5f, 0x70, 0x6f, 0x72, 0x74, 0x73, - 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x70, 0x32, 0x70, 0x2e, 0x43, 0x6c, 0x61, - 0x69, 0x6d, 0x65, 0x64, 0x49, 0x70, 0x50, 0x6f, 0x72, 0x74, 0x52, 0x0e, 0x63, 0x6c, 0x61, 0x69, - 0x6d, 0x65, 0x64, 0x49, 0x70, 0x50, 0x6f, 0x72, 0x74, 0x73, 0x22, 0x6f, 0x0a, 0x17, 0x47, 0x65, - 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x46, 0x72, 0x6f, + 0x01, 0x28, 0x0c, 0x52, 0x08, 0x69, 0x70, 0x42, 0x6c, 0x73, 0x53, 0x69, 0x67, 0x12, 0x1f, 0x0a, + 0x0b, 0x61, 0x6c, 0x6c, 0x5f, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x73, 0x18, 0x0e, 0x20, 0x01, + 0x28, 0x08, 0x52, 0x0a, 0x61, 0x6c, 0x6c, 0x53, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x73, 0x4a, 0x04, + 0x08, 0x05, 0x10, 0x06, 0x22, 0x5e, 0x0a, 0x06, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, 0x12, + 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, + 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0d, 0x52, 0x05, 0x6d, 0x61, 0x6a, 0x6f, 0x72, 0x12, 0x14, 0x0a, 0x05, 0x6d, 0x69, 0x6e, 0x6f, + 0x72, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x6d, 0x69, 0x6e, 0x6f, 0x72, 0x12, 0x14, + 0x0a, 0x05, 0x70, 0x61, 0x74, 0x63, 0x68, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x05, 0x70, + 0x61, 0x74, 0x63, 0x68, 0x22, 0x39, 0x0a, 0x0b, 0x42, 0x6c, 0x6f, 0x6f, 0x6d, 0x46, 0x69, 0x6c, + 0x74, 0x65, 0x72, 0x12, 0x16, 0x0a, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0c, 0x52, 0x06, 0x66, 0x69, 0x6c, 0x74, 0x65, 0x72, 0x12, 0x12, 0x0a, 0x04, 0x73, + 0x61, 0x6c, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x73, 0x61, 0x6c, 0x74, 0x22, + 0xbd, 0x01, 0x0a, 0x0d, 0x43, 0x6c, 0x61, 0x69, 0x6d, 0x65, 0x64, 0x49, 0x70, 0x50, 0x6f, 0x72, + 0x74, 0x12, 0x29, 0x0a, 0x10, 0x78, 0x35, 0x30, 0x39, 0x5f, 0x63, 0x65, 0x72, 0x74, 0x69, 0x66, + 0x69, 0x63, 0x61, 0x74, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0f, 0x78, 0x35, 0x30, + 0x39, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x12, 0x17, 0x0a, 0x07, + 0x69, 0x70, 0x5f, 0x61, 0x64, 0x64, 0x72, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x69, + 0x70, 0x41, 0x64, 0x64, 0x72, 0x12, 0x17, 0x0a, 0x07, 0x69, 0x70, 0x5f, 0x70, 0x6f, 0x72, 0x74, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x06, 0x69, 0x70, 0x50, 0x6f, 0x72, 0x74, 0x12, 0x1c, + 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x04, 0x20, 0x01, 0x28, + 0x04, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x12, 0x1c, 0x0a, 0x09, + 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x09, 0x73, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75, 0x72, 0x65, 0x12, 0x13, 0x0a, 0x05, 0x74, 0x78, + 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x74, 0x78, 0x49, 0x64, 0x22, + 0x61, 0x0a, 0x0b, 0x47, 0x65, 0x74, 0x50, 0x65, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x31, + 0x0a, 0x0b, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x01, 0x20, + 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x70, 0x32, 0x70, 0x2e, 0x42, 0x6c, 0x6f, 0x6f, 0x6d, 0x46, + 0x69, 0x6c, 0x74, 0x65, 0x72, 0x52, 0x0a, 0x6b, 0x6e, 0x6f, 0x77, 0x6e, 0x50, 0x65, 0x65, 0x72, + 0x73, 0x12, 0x1f, 0x0a, 0x0b, 0x61, 0x6c, 0x6c, 0x5f, 0x73, 0x75, 0x62, 0x6e, 0x65, 0x74, 0x73, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0a, 0x61, 0x6c, 0x6c, 0x53, 0x75, 0x62, 0x6e, 0x65, + 0x74, 0x73, 0x22, 0x48, 0x0a, 0x08, 0x50, 0x65, 0x65, 0x72, 0x4c, 0x69, 0x73, 0x74, 0x12, 0x3c, + 0x0a, 0x10, 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x65, 0x64, 0x5f, 0x69, 0x70, 0x5f, 0x70, 0x6f, 0x72, + 0x74, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x70, 0x32, 0x70, 0x2e, 0x43, + 0x6c, 0x61, 0x69, 0x6d, 0x65, 0x64, 0x49, 0x70, 0x50, 0x6f, 0x72, 0x74, 0x52, 0x0e, 0x63, 0x6c, + 0x61, 0x69, 0x6d, 0x65, 0x64, 0x49, 0x70, 0x50, 0x6f, 0x72, 0x74, 0x73, 0x22, 0x6f, 0x0a, 0x17, + 0x47, 0x65, 0x74, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x46, + 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, + 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, + 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, + 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x22, 0x6a, 0x0a, + 0x14, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x46, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, + 0x18, 0x0a, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, + 0x52, 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x89, 0x01, 0x0a, 0x17, 0x47, 0x65, + 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, + 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, + 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, + 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, + 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x22, 0x6a, 0x0a, 0x14, 0x53, - 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x46, 0x72, 0x6f, 0x6e, 0x74, - 0x69, 0x65, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, - 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x18, 0x0a, - 0x07, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, - 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x22, 0x89, 0x01, 0x0a, 0x17, 0x47, 0x65, 0x74, 0x41, - 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, - 0x61, 0x72, 0x79, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, - 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, - 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, - 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x68, 0x65, 0x69, - 0x67, 0x68, 0x74, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x04, 0x52, 0x07, 0x68, 0x65, 0x69, 0x67, - 0x68, 0x74, 0x73, 0x22, 0x71, 0x0a, 0x14, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x53, - 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, 0x19, 0x0a, 0x08, 0x63, - 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, - 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, - 0x5f, 0x69, 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0a, 0x73, 0x75, 0x6d, 0x6d, - 0x61, 0x72, 0x79, 0x49, 0x64, 0x73, 0x22, 0x71, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x41, 0x63, 0x63, - 0x65, 0x70, 0x74, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x12, 0x19, 0x0a, - 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, - 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, - 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, - 0x69, 0x6e, 0x65, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x22, 0x6f, 0x0a, 0x10, 0x41, 0x63, 0x63, - 0x65, 0x70, 0x74, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x12, 0x19, 0x0a, + 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x68, + 0x65, 0x69, 0x67, 0x68, 0x74, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x04, 0x52, 0x07, 0x68, 0x65, + 0x69, 0x67, 0x68, 0x74, 0x73, 0x22, 0x71, 0x0a, 0x14, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, + 0x64, 0x53, 0x74, 0x61, 0x74, 0x65, 0x53, 0x75, 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x61, - 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x63, - 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x22, 0x8e, 0x01, 0x0a, 0x0b, 0x47, - 0x65, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, - 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, - 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, - 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, - 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, - 0x12, 0x23, 0x0a, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, - 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, - 0x65, 0x72, 0x49, 0x64, 0x73, 0x4a, 0x04, 0x08, 0x05, 0x10, 0x06, 0x22, 0x69, 0x0a, 0x08, 0x41, - 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, - 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, - 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, - 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, - 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, - 0x6e, 0x65, 0x72, 0x49, 0x64, 0x73, 0x22, 0xb9, 0x01, 0x0a, 0x0c, 0x47, 0x65, 0x74, 0x41, 0x6e, - 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, - 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, - 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, - 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x21, 0x0a, - 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, - 0x12, 0x30, 0x0a, 0x0b, 0x65, 0x6e, 0x67, 0x69, 0x6e, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x18, - 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0f, 0x2e, 0x70, 0x32, 0x70, 0x2e, 0x45, 0x6e, 0x67, 0x69, - 0x6e, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a, 0x65, 0x6e, 0x67, 0x69, 0x6e, 0x65, 0x54, 0x79, - 0x70, 0x65, 0x22, 0x65, 0x0a, 0x09, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x12, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x73, 0x75, 0x6d, 0x6d, 0x61, + 0x72, 0x79, 0x5f, 0x69, 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0a, 0x73, 0x75, + 0x6d, 0x6d, 0x61, 0x72, 0x79, 0x49, 0x64, 0x73, 0x22, 0x71, 0x0a, 0x13, 0x47, 0x65, 0x74, 0x41, + 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, - 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, - 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0a, 0x63, - 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x73, 0x22, 0x84, 0x01, 0x0a, 0x03, 0x47, 0x65, - 0x74, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, + 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, + 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, + 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x4a, 0x04, 0x08, 0x04, 0x10, 0x05, 0x22, 0x6f, 0x0a, 0x10, 0x41, + 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x46, 0x72, 0x6f, 0x6e, 0x74, 0x69, 0x65, 0x72, 0x12, + 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, + 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, + 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x22, 0x8e, 0x01, 0x0a, + 0x0b, 0x47, 0x65, 0x74, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x12, 0x19, 0x0a, 0x08, + 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, + 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, + 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, + 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, + 0x6e, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x5f, + 0x69, 0x64, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x61, + 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x73, 0x4a, 0x04, 0x08, 0x05, 0x10, 0x06, 0x22, 0x69, 0x0a, + 0x08, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, + 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x49, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, + 0x5f, 0x69, 0x64, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, 0x0c, 0x63, 0x6f, 0x6e, 0x74, + 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x73, 0x22, 0xb9, 0x01, 0x0a, 0x0c, 0x47, 0x65, 0x74, + 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, + 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, + 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, + 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, + 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, + 0x49, 0x64, 0x12, 0x30, 0x0a, 0x0b, 0x65, 0x6e, 0x67, 0x69, 0x6e, 0x65, 0x5f, 0x74, 0x79, 0x70, + 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x0f, 0x2e, 0x70, 0x32, 0x70, 0x2e, 0x45, 0x6e, + 0x67, 0x69, 0x6e, 0x65, 0x54, 0x79, 0x70, 0x65, 0x52, 0x0a, 0x65, 0x6e, 0x67, 0x69, 0x6e, 0x65, + 0x54, 0x79, 0x70, 0x65, 0x22, 0x65, 0x0a, 0x09, 0x41, 0x6e, 0x63, 0x65, 0x73, 0x74, 0x6f, 0x72, + 0x73, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, - 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, - 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, - 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x61, - 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x63, - 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x4a, 0x04, 0x08, 0x05, 0x10, 0x06, - 0x22, 0x5d, 0x0a, 0x03, 0x50, 0x75, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, + 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1e, 0x0a, 0x0a, 0x63, + 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0c, 0x52, + 0x0a, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x73, 0x22, 0x84, 0x01, 0x0a, 0x03, + 0x47, 0x65, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, + 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, + 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, + 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, + 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, + 0x0b, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x4a, 0x04, 0x08, 0x05, + 0x10, 0x06, 0x22, 0x5d, 0x0a, 0x03, 0x50, 0x75, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, + 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x49, 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, + 0x72, 0x22, 0xb0, 0x01, 0x0a, 0x09, 0x50, 0x75, 0x73, 0x68, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, + 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, + 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, + 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, + 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, + 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, + 0x65, 0x72, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, + 0x6e, 0x65, 0x72, 0x12, 0x29, 0x0a, 0x10, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, + 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x72, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x4a, 0x04, + 0x08, 0x05, 0x10, 0x06, 0x22, 0xb5, 0x01, 0x0a, 0x09, 0x50, 0x75, 0x6c, 0x6c, 0x51, 0x75, 0x65, + 0x72, 0x79, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, + 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, + 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, + 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, + 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x74, + 0x61, 0x69, 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, + 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x12, 0x29, 0x0a, 0x10, 0x72, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, + 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, + 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x4a, 0x04, 0x08, 0x05, 0x10, 0x06, 0x22, 0xba, 0x01, 0x0a, + 0x05, 0x43, 0x68, 0x69, 0x74, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, + 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, + 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, + 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, + 0x12, 0x21, 0x0a, 0x0c, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, 0x64, 0x5f, 0x69, 0x64, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, + 0x64, 0x49, 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x5f, + 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, + 0x65, 0x64, 0x49, 0x64, 0x12, 0x33, 0x0a, 0x16, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, + 0x64, 0x5f, 0x69, 0x64, 0x5f, 0x61, 0x74, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x05, + 0x20, 0x01, 0x28, 0x0c, 0x52, 0x13, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, 0x64, 0x49, + 0x64, 0x41, 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x7f, 0x0a, 0x0a, 0x41, 0x70, 0x70, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, - 0x64, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x22, - 0xb0, 0x01, 0x0a, 0x09, 0x50, 0x75, 0x73, 0x68, 0x51, 0x75, 0x65, 0x72, 0x79, 0x12, 0x19, 0x0a, + 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, + 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x1b, 0x0a, + 0x09, 0x61, 0x70, 0x70, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, + 0x52, 0x08, 0x61, 0x70, 0x70, 0x42, 0x79, 0x74, 0x65, 0x73, 0x22, 0x64, 0x0a, 0x0b, 0x41, 0x70, + 0x70, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, + 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, + 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x61, 0x70, 0x70, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, + 0x18, 0x03, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x61, 0x70, 0x70, 0x42, 0x79, 0x74, 0x65, 0x73, + 0x22, 0x88, 0x01, 0x0a, 0x08, 0x41, 0x70, 0x70, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, - 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, - 0x69, 0x6e, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, - 0x72, 0x12, 0x29, 0x0a, 0x10, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x5f, 0x68, - 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0f, 0x72, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x4a, 0x04, 0x08, 0x05, - 0x10, 0x06, 0x22, 0xb5, 0x01, 0x0a, 0x09, 0x50, 0x75, 0x6c, 0x6c, 0x51, 0x75, 0x65, 0x72, 0x79, - 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, - 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, - 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1a, 0x0a, 0x08, 0x64, 0x65, - 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x04, 0x52, 0x08, 0x64, 0x65, - 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, - 0x6e, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x63, 0x6f, - 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x49, 0x64, 0x12, 0x29, 0x0a, 0x10, 0x72, 0x65, 0x71, - 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x06, 0x20, - 0x01, 0x28, 0x04, 0x52, 0x0f, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x65, 0x64, 0x48, 0x65, - 0x69, 0x67, 0x68, 0x74, 0x4a, 0x04, 0x08, 0x05, 0x10, 0x06, 0x22, 0xba, 0x01, 0x0a, 0x05, 0x43, - 0x68, 0x69, 0x74, 0x73, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, - 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x21, - 0x0a, 0x0c, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0b, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, 0x64, 0x49, - 0x64, 0x12, 0x1f, 0x0a, 0x0b, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, 0x5f, 0x69, 0x64, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x0a, 0x61, 0x63, 0x63, 0x65, 0x70, 0x74, 0x65, 0x64, - 0x49, 0x64, 0x12, 0x33, 0x0a, 0x16, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, 0x64, 0x5f, - 0x69, 0x64, 0x5f, 0x61, 0x74, 0x5f, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x18, 0x05, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x13, 0x70, 0x72, 0x65, 0x66, 0x65, 0x72, 0x72, 0x65, 0x64, 0x49, 0x64, 0x41, - 0x74, 0x48, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, 0x7f, 0x0a, 0x0a, 0x41, 0x70, 0x70, 0x52, 0x65, - 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, - 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, - 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, - 0x1a, 0x0a, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, - 0x04, 0x52, 0x08, 0x64, 0x65, 0x61, 0x64, 0x6c, 0x69, 0x6e, 0x65, 0x12, 0x1b, 0x0a, 0x09, 0x61, - 0x70, 0x70, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, - 0x61, 0x70, 0x70, 0x42, 0x79, 0x74, 0x65, 0x73, 0x22, 0x64, 0x0a, 0x0b, 0x41, 0x70, 0x70, 0x52, - 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, - 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, - 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, - 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x61, 0x70, 0x70, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x03, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x61, 0x70, 0x70, 0x42, 0x79, 0x74, 0x65, 0x73, 0x22, 0x88, - 0x01, 0x0a, 0x08, 0x41, 0x70, 0x70, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x12, 0x19, 0x0a, 0x08, 0x63, - 0x68, 0x61, 0x69, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, - 0x68, 0x61, 0x69, 0x6e, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, - 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, - 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x63, - 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x11, 0x52, 0x09, 0x65, 0x72, 0x72, 0x6f, 0x72, - 0x43, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x6d, 0x65, - 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, 0x72, 0x72, - 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x43, 0x0a, 0x09, 0x41, 0x70, 0x70, - 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x5f, - 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, 0x6e, 0x49, - 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x61, 0x70, 0x70, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x61, 0x70, 0x70, 0x42, 0x79, 0x74, 0x65, 0x73, 0x2a, 0x5d, - 0x0a, 0x0a, 0x45, 0x6e, 0x67, 0x69, 0x6e, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1b, 0x0a, 0x17, - 0x45, 0x4e, 0x47, 0x49, 0x4e, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, 0x53, 0x50, - 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x19, 0x0a, 0x15, 0x45, 0x4e, 0x47, - 0x49, 0x4e, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x41, 0x56, 0x41, 0x4c, 0x41, 0x4e, 0x43, - 0x48, 0x45, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x45, 0x4e, 0x47, 0x49, 0x4e, 0x45, 0x5f, 0x54, - 0x59, 0x50, 0x45, 0x5f, 0x53, 0x4e, 0x4f, 0x57, 0x4d, 0x41, 0x4e, 0x10, 0x02, 0x42, 0x2e, 0x5a, - 0x2c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x76, 0x61, 0x2d, - 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x61, 0x76, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x68, 0x65, 0x67, 0x6f, - 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x70, 0x62, 0x2f, 0x70, 0x32, 0x70, 0x62, 0x06, 0x70, - 0x72, 0x6f, 0x74, 0x6f, 0x33, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, 0x65, 0x72, 0x72, 0x6f, 0x72, + 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x11, 0x52, 0x09, 0x65, 0x72, 0x72, + 0x6f, 0x72, 0x43, 0x6f, 0x64, 0x65, 0x12, 0x23, 0x0a, 0x0d, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, + 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0c, 0x65, + 0x72, 0x72, 0x6f, 0x72, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x43, 0x0a, 0x09, 0x41, + 0x70, 0x70, 0x47, 0x6f, 0x73, 0x73, 0x69, 0x70, 0x12, 0x19, 0x0a, 0x08, 0x63, 0x68, 0x61, 0x69, + 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x63, 0x68, 0x61, 0x69, + 0x6e, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x61, 0x70, 0x70, 0x5f, 0x62, 0x79, 0x74, 0x65, 0x73, + 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x61, 0x70, 0x70, 0x42, 0x79, 0x74, 0x65, 0x73, + 0x2a, 0x5d, 0x0a, 0x0a, 0x45, 0x6e, 0x67, 0x69, 0x6e, 0x65, 0x54, 0x79, 0x70, 0x65, 0x12, 0x1b, + 0x0a, 0x17, 0x45, 0x4e, 0x47, 0x49, 0x4e, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x55, 0x4e, + 0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x19, 0x0a, 0x15, 0x45, + 0x4e, 0x47, 0x49, 0x4e, 0x45, 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x41, 0x56, 0x41, 0x4c, 0x41, + 0x4e, 0x43, 0x48, 0x45, 0x10, 0x01, 0x12, 0x17, 0x0a, 0x13, 0x45, 0x4e, 0x47, 0x49, 0x4e, 0x45, + 0x5f, 0x54, 0x59, 0x50, 0x45, 0x5f, 0x53, 0x4e, 0x4f, 0x57, 0x4d, 0x41, 0x4e, 0x10, 0x02, 0x42, + 0x2e, 0x5a, 0x2c, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x61, 0x76, + 0x61, 0x2d, 0x6c, 0x61, 0x62, 0x73, 0x2f, 0x61, 0x76, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x68, 0x65, + 0x67, 0x6f, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x70, 0x62, 0x2f, 0x70, 0x32, 0x70, 0x62, + 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( From df91c2f4ab993c45ec088a8bc796d4d443bd9eb8 Mon Sep 17 00:00:00 2001 From: marun Date: Mon, 19 Aug 2024 12:29:39 -0700 Subject: [PATCH 27/69] [antithesis] Enable custom plugin dir for subnet-evm (#3305) --- .../avalanchego/gencomposeconfig/main.go | 2 +- tests/antithesis/compose.go | 23 ++++++++++++------- .../antithesis/xsvm/gencomposeconfig/main.go | 2 +- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/tests/antithesis/avalanchego/gencomposeconfig/main.go b/tests/antithesis/avalanchego/gencomposeconfig/main.go index ab1ca9255072..7425a3df9bba 100644 --- a/tests/antithesis/avalanchego/gencomposeconfig/main.go +++ b/tests/antithesis/avalanchego/gencomposeconfig/main.go @@ -15,7 +15,7 @@ const baseImageName = "antithesis-avalanchego" // Creates docker-compose.yml and its associated volumes in the target path. func main() { network := tmpnet.LocalNetworkOrPanic() - if err := antithesis.GenerateComposeConfig(network, baseImageName); err != nil { + if err := antithesis.GenerateComposeConfig(network, baseImageName, "" /* runtimePluginDir */); err != nil { log.Fatalf("failed to generate compose config: %v", err) } } diff --git a/tests/antithesis/compose.go b/tests/antithesis/compose.go index f11ac0288ea2..f10ffe5471d7 100644 --- a/tests/antithesis/compose.go +++ b/tests/antithesis/compose.go @@ -29,11 +29,11 @@ var ( errPluginDirEnvVarNotSet = errors.New("AVALANCHEGO_PLUGIN_DIR environment variable not set") ) -// Creates docker compose configuration for an antithesis test -// setup. Configuration is via env vars to simplify usage by main entrypoints. If -// the provided network includes a subnet, the initial DB state for the subnet -// will be created and written to the target path. -func GenerateComposeConfig(network *tmpnet.Network, baseImageName string) error { +// Creates docker compose configuration for an antithesis test setup. Configuration is via env vars to +// simplify usage by main entrypoints. If the provided network includes a subnet, the initial DB state for +// the subnet will be created and written to the target path. The runtimePluginDir should be set if the node +// image used for the test setup uses a path other than the default (~/.avalanchego/plugins). +func GenerateComposeConfig(network *tmpnet.Network, baseImageName string, runtimePluginDir string) error { targetPath := os.Getenv("TARGET_PATH") if len(targetPath) == 0 { return errTargetPathEnvVarNotSet @@ -51,6 +51,7 @@ func GenerateComposeConfig(network *tmpnet.Network, baseImageName string) error return errAvalancheGoEvVarNotSet } + // Plugin dir configured here is only used for initializing the bootstrap db. pluginDir := os.Getenv(tmpnet.AvalancheGoPluginDirEnvName) if len(pluginDir) == 0 { return errPluginDirEnvVarNotSet @@ -69,7 +70,7 @@ func GenerateComposeConfig(network *tmpnet.Network, baseImageName string) error nodeImageName := fmt.Sprintf("%s-node:%s", baseImageName, imageTag) workloadImageName := fmt.Sprintf("%s-workload:%s", baseImageName, imageTag) - if err := initComposeConfig(network, nodeImageName, workloadImageName, targetPath); err != nil { + if err := initComposeConfig(network, nodeImageName, workloadImageName, targetPath, runtimePluginDir); err != nil { return fmt.Errorf("failed to generate compose config: %w", err) } @@ -83,9 +84,10 @@ func initComposeConfig( nodeImageName string, workloadImageName string, targetPath string, + pluginDir string, ) error { // Generate a compose project for the specified network - project, err := newComposeProject(network, nodeImageName, workloadImageName) + project, err := newComposeProject(network, nodeImageName, workloadImageName, pluginDir) if err != nil { return fmt.Errorf("failed to create compose project: %w", err) } @@ -123,7 +125,7 @@ func initComposeConfig( // Create a new docker compose project for an antithesis test setup // for the provided network configuration. -func newComposeProject(network *tmpnet.Network, nodeImageName string, workloadImageName string) (*types.Project, error) { +func newComposeProject(network *tmpnet.Network, nodeImageName string, workloadImageName string, pluginDir string) (*types.Project, error) { networkName := "avalanche-testnet" baseNetworkAddress := "10.0.20" @@ -160,6 +162,11 @@ func newComposeProject(network *tmpnet.Network, nodeImageName string, workloadIm config.StakingSignerKeyContentKey: signerKey, } + // Set a non-default plugin dir if provided + if len(pluginDir) > 0 { + env[config.PluginDirKey] = pluginDir + } + // Apply configuration appropriate to a test network for k, v := range tmpnet.DefaultTestFlags() { switch value := v.(type) { diff --git a/tests/antithesis/xsvm/gencomposeconfig/main.go b/tests/antithesis/xsvm/gencomposeconfig/main.go index 40e14db5e5a4..e038daac0893 100644 --- a/tests/antithesis/xsvm/gencomposeconfig/main.go +++ b/tests/antithesis/xsvm/gencomposeconfig/main.go @@ -20,7 +20,7 @@ func main() { network.Subnets = []*tmpnet.Subnet{ subnet.NewXSVMOrPanic("xsvm", genesis.VMRQKey, network.Nodes...), } - if err := antithesis.GenerateComposeConfig(network, baseImageName); err != nil { + if err := antithesis.GenerateComposeConfig(network, baseImageName, "" /* runtimePluginDir */); err != nil { log.Fatalf("failed to generate compose config: %v", err) } } From acfcfe4da3cf81567ceed19dd8f6b5bf73c3dede Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Mon, 19 Aug 2024 18:12:02 -0400 Subject: [PATCH 28/69] Refactor state tests to always use initialized state (#3310) --- vms/platformvm/genesis/genesistest/genesis.go | 107 ++++++++ vms/platformvm/state/diff_test.go | 19 +- vms/platformvm/state/stakers_test.go | 3 +- vms/platformvm/state/state.go | 72 ++---- vms/platformvm/state/state_test.go | 242 ++++++------------ 5 files changed, 220 insertions(+), 223 deletions(-) create mode 100644 vms/platformvm/genesis/genesistest/genesis.go diff --git a/vms/platformvm/genesis/genesistest/genesis.go b/vms/platformvm/genesis/genesistest/genesis.go new file mode 100644 index 000000000000..24e16ecf0934 --- /dev/null +++ b/vms/platformvm/genesis/genesistest/genesis.go @@ -0,0 +1,107 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package genesistest + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis" + "github.com/ava-labs/avalanchego/vms/platformvm/reward" + "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/secp256k1fx" +) + +var ( + AVAXAssetID = ids.GenerateTestID() + AVAXAsset = avax.Asset{ID: AVAXAssetID} + + ValidatorNodeID = ids.GenerateTestNodeID() + Time = time.Now().Round(time.Second) + TimeUnix = uint64(Time.Unix()) + ValidatorDuration = 28 * 24 * time.Hour + ValidatorEndTime = Time.Add(ValidatorDuration) + ValidatorEndTimeUnix = uint64(ValidatorEndTime.Unix()) + ValidatorWeight = units.Avax + ValidatorRewardsOwner = &secp256k1fx.OutputOwners{} + ValidatorDelegationShares uint32 = reward.PercentDenominator + + XChainName = "x" + + InitialBalance = units.Schmeckle + InitialSupply = ValidatorWeight + InitialBalance +) + +func New(t testing.TB) *genesis.Genesis { + require := require.New(t) + + genesisValidator := &txs.AddValidatorTx{ + Validator: txs.Validator{ + NodeID: ValidatorNodeID, + Start: TimeUnix, + End: ValidatorEndTimeUnix, + Wght: ValidatorWeight, + }, + StakeOuts: []*avax.TransferableOutput{ + { + Asset: AVAXAsset, + Out: &secp256k1fx.TransferOutput{ + Amt: ValidatorWeight, + }, + }, + }, + RewardsOwner: ValidatorRewardsOwner, + DelegationShares: ValidatorDelegationShares, + } + genesisValidatorTx := &txs.Tx{Unsigned: genesisValidator} + require.NoError(genesisValidatorTx.Initialize(txs.Codec)) + + genesisChain := &txs.CreateChainTx{ + SubnetID: constants.PrimaryNetworkID, + ChainName: XChainName, + VMID: constants.AVMID, + SubnetAuth: &secp256k1fx.Input{}, + } + genesisChainTx := &txs.Tx{Unsigned: genesisChain} + require.NoError(genesisChainTx.Initialize(txs.Codec)) + + return &genesis.Genesis{ + UTXOs: []*genesis.UTXO{ + { + UTXO: avax.UTXO{ + UTXOID: avax.UTXOID{ + TxID: AVAXAssetID, + OutputIndex: 0, + }, + Asset: AVAXAsset, + Out: &secp256k1fx.TransferOutput{ + Amt: InitialBalance, + }, + }, + Message: nil, + }, + }, + Validators: []*txs.Tx{ + genesisValidatorTx, + }, + Chains: []*txs.Tx{ + genesisChainTx, + }, + Timestamp: TimeUnix, + InitialSupply: InitialSupply, + } +} + +func NewBytes(t testing.TB) []byte { + g := New(t) + genesisBytes, err := genesis.Codec.Marshal(genesis.CodecVersion, g) + require.NoError(t, err) + return genesisBytes +} diff --git a/vms/platformvm/state/diff_test.go b/vms/platformvm/state/diff_test.go index 48f0d567b116..d76437f692df 100644 --- a/vms/platformvm/state/diff_test.go +++ b/vms/platformvm/state/diff_test.go @@ -11,6 +11,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" @@ -36,7 +37,7 @@ func TestDiffMissingState(t *testing.T) { func TestNewDiffOn(t *testing.T) { require := require.New(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) d, err := NewDiffOn(state) require.NoError(err) @@ -47,7 +48,7 @@ func TestNewDiffOn(t *testing.T) { func TestDiffFeeState(t *testing.T) { require := require.New(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) d, err := NewDiffOn(state) require.NoError(err) @@ -68,7 +69,7 @@ func TestDiffFeeState(t *testing.T) { func TestDiffCurrentSupply(t *testing.T) { require := require.New(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) d, err := NewDiffOn(state) require.NoError(err) @@ -256,7 +257,7 @@ func TestDiffSubnet(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) // Initialize parent with one subnet parentStateCreateSubnetTx := &txs.Tx{ @@ -305,7 +306,7 @@ func TestDiffSubnet(t *testing.T) { func TestDiffChain(t *testing.T) { require := require.New(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) subnetID := ids.GenerateTestID() // Initialize parent with one chain @@ -402,7 +403,7 @@ func TestDiffTx(t *testing.T) { func TestDiffRewardUTXO(t *testing.T) { require := require.New(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) // Initialize parent with one reward UTXO var ( @@ -531,7 +532,7 @@ func TestDiffSubnetOwner(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) var ( owner1 = fx.NewMockOwner(ctrl) @@ -589,7 +590,7 @@ func TestDiffSubnetManager(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) states := NewMockVersions(ctrl) lastAcceptedID := ids.GenerateTestID() @@ -638,7 +639,7 @@ func TestDiffStacking(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) var ( owner1 = fx.NewMockOwner(ctrl) diff --git a/vms/platformvm/state/stakers_test.go b/vms/platformvm/state/stakers_test.go index 5c6d9a8b28f8..d01593c0548e 100644 --- a/vms/platformvm/state/stakers_test.go +++ b/vms/platformvm/state/stakers_test.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) @@ -219,7 +220,7 @@ func TestDiffStakersDelegator(t *testing.T) { func newTestStaker() *Staker { startTime := time.Now().Round(time.Second) - endTime := startTime.Add(28 * 24 * time.Hour) + endTime := startTime.Add(genesistest.ValidatorDuration) return &Staker{ TxID: ids.GenerateTestID(), NodeID: ids.GenerateTestNodeID(), diff --git a/vms/platformvm/state/state.go b/vms/platformvm/state/state.go index da2564f55cc2..6923f2414e25 100644 --- a/vms/platformvm/state/state.go +++ b/vms/platformvm/state/state.go @@ -458,38 +458,6 @@ func New( metrics metrics.Metrics, rewards reward.Calculator, ) (State, error) { - s, err := newState( - db, - metrics, - cfg, - execCfg, - ctx, - metricsReg, - rewards, - ) - if err != nil { - return nil, err - } - - if err := s.sync(genesisBytes); err != nil { - // Drop any errors on close to return the first error - _ = s.Close() - - return nil, err - } - - return s, nil -} - -func newState( - db database.Database, - metrics metrics.Metrics, - cfg *config.Config, - execCfg *config.ExecutionConfig, - ctx *snow.Context, - metricsReg prometheus.Registerer, - rewards reward.Calculator, -) (*state, error) { blockIDCache, err := metercacher.New[uint64, ids.ID]( "block_id_cache", metricsReg, @@ -614,7 +582,7 @@ func newState( return nil, err } - return &state{ + s := &state{ validatorState: newValidatorState(), validators: cfg.Validators, @@ -694,7 +662,16 @@ func newState( chainDBCache: chainDBCache, singletonDB: prefixdb.New(SingletonPrefix, baseDB), - }, nil + } + + if err := s.sync(genesisBytes); err != nil { + return nil, errors.Join( + err, + s.Close(), + ) + } + + return s, nil } func (s *state) GetCurrentValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) { @@ -753,15 +730,6 @@ func (s *state) GetPendingStakerIterator() (StakerIterator, error) { return s.pendingStakers.GetStakerIterator(), nil } -func (s *state) shouldInit() (bool, error) { - has, err := s.singletonDB.Has(InitializedKey) - return !has, err -} - -func (s *state) doneInit() error { - return s.singletonDB.Put(InitializedKey, nil) -} - func (s *state) GetSubnetIDs() ([]ids.ID, error) { if s.cachedSubnetIDs != nil { return s.cachedSubnetIDs, nil @@ -1751,7 +1719,7 @@ func (s *state) Close() error { } func (s *state) sync(genesis []byte) error { - shouldInit, err := s.shouldInit() + wasInitialized, err := isInitialized(s.singletonDB) if err != nil { return fmt.Errorf( "failed to check if the database is initialized: %w", @@ -1759,9 +1727,9 @@ func (s *state) sync(genesis []byte) error { ) } - // If the database is empty, create the platform chain anew using the - // provided genesis state - if shouldInit { + // If the database wasn't previously initialized, create the platform chain + // anew using the provided genesis state. + if !wasInitialized { if err := s.init(genesis); err != nil { return fmt.Errorf( "failed to initialize the database: %w", @@ -1797,7 +1765,7 @@ func (s *state) init(genesisBytes []byte) error { return err } - if err := s.doneInit(); err != nil { + if err := markInitialized(s.singletonDB); err != nil { return err } @@ -2548,6 +2516,14 @@ func (s *state) ReindexBlocks(lock sync.Locker, log logging.Logger) error { return s.Commit() } +func markInitialized(db database.KeyValueWriter) error { + return db.Put(InitializedKey, nil) +} + +func isInitialized(db database.KeyValueReader) (bool, error) { + return db.Has(InitializedKey) +} + func putFeeState(db database.KeyValueWriter, feeState fee.State) error { feeStateBytes, err := block.GenesisCodec.Marshal(block.CodecVersion, feeState) if err != nil { diff --git a/vms/platformvm/state/state_test.go b/vms/platformvm/state/state_test.go index 52c6ac978929..21357874e434 100644 --- a/vms/platformvm/state/state_test.go +++ b/vms/platformvm/state/state_test.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/fx" - "github.com/ava-labs/avalanchego/vms/platformvm/genesis" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" @@ -45,41 +45,41 @@ import ( safemath "github.com/ava-labs/avalanchego/utils/math" ) -var ( - initialTxID = ids.GenerateTestID() - initialNodeID = ids.GenerateTestNodeID() - initialTime = time.Now().Round(time.Second) - initialValidatorEndTime = initialTime.Add(28 * 24 * time.Hour) -) - -func TestStateInitialization(t *testing.T) { - require := require.New(t) - s, db := newUninitializedState(require) - - shouldInit, err := s.shouldInit() - require.NoError(err) - require.True(shouldInit) - - require.NoError(s.doneInit()) - require.NoError(s.Commit()) - - s = newStateFromDB(require, db) - - shouldInit, err = s.shouldInit() - require.NoError(err) - require.False(shouldInit) +func newTestState(t testing.TB, db database.Database) *state { + s, err := New( + db, + genesistest.NewBytes(t), + prometheus.NewRegistry(), + &config.Config{ + Validators: validators.NewManager(), + }, + &config.DefaultExecutionConfig, + &snow.Context{ + Log: logging.NoLog{}, + }, + metrics.Noop, + reward.NewCalculator(reward.Config{ + MaxConsumptionRate: .12 * reward.PercentDenominator, + MinConsumptionRate: .1 * reward.PercentDenominator, + MintingPeriod: 365 * 24 * time.Hour, + SupplyCap: 720 * units.MegaAvax, + }), + ) + require.NoError(t, err) + require.IsType(t, (*state)(nil), s) + return s.(*state) } func TestStateSyncGenesis(t *testing.T) { require := require.New(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) - staker, err := state.GetCurrentValidator(constants.PrimaryNetworkID, initialNodeID) + staker, err := state.GetCurrentValidator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) require.NoError(err) require.NotNil(staker) - require.Equal(initialNodeID, staker.NodeID) + require.Equal(genesistest.ValidatorNodeID, staker.NodeID) - delegatorIterator, err := state.GetCurrentDelegatorIterator(constants.PrimaryNetworkID, initialNodeID) + delegatorIterator, err := state.GetCurrentDelegatorIterator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) require.NoError(err) assertIteratorsEqual(t, EmptyIterator, delegatorIterator) @@ -87,10 +87,10 @@ func TestStateSyncGenesis(t *testing.T) { require.NoError(err) assertIteratorsEqual(t, NewSliceIterator(staker), stakerIterator) - _, err = state.GetPendingValidator(constants.PrimaryNetworkID, initialNodeID) + _, err = state.GetPendingValidator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) require.ErrorIs(err, database.ErrNotFound) - delegatorIterator, err = state.GetPendingDelegatorIterator(constants.PrimaryNetworkID, initialNodeID) + delegatorIterator, err = state.GetPendingDelegatorIterator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) require.NoError(err) assertIteratorsEqual(t, EmptyIterator, delegatorIterator) } @@ -153,14 +153,15 @@ func TestPersistStakers(t *testing.T) { }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { valsMap := s.cfg.Validators.GetMap(staker.SubnetID) - r.Len(valsMap, 1) - valOut, found := valsMap[staker.NodeID] - r.True(found) - r.Equal(&validators.GetValidatorOutput{ - NodeID: staker.NodeID, - PublicKey: staker.PublicKey, - Weight: staker.Weight, - }, valOut) + r.Contains(valsMap, staker.NodeID) + r.Equal( + &validators.GetValidatorOutput{ + NodeID: staker.NodeID, + PublicKey: staker.PublicKey, + Weight: staker.Weight, + }, + valsMap[staker.NodeID], + ) }, checkValidatorUptimes: func(r *require.Assertions, s *state, staker *Staker) { upDuration, lastUpdated, err := s.GetUptime(staker.NodeID, staker.SubnetID) @@ -258,9 +259,8 @@ func TestPersistStakers(t *testing.T) { r.NoError(err) valsMap := s.cfg.Validators.GetMap(staker.SubnetID) - r.Len(valsMap, 1) - valOut, found := valsMap[staker.NodeID] - r.True(found) + r.Contains(valsMap, staker.NodeID) + valOut := valsMap[staker.NodeID] r.Equal(valOut.NodeID, staker.NodeID) r.Equal(valOut.Weight, val.Weight+staker.Weight) }, @@ -314,7 +314,7 @@ func TestPersistStakers(t *testing.T) { checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { // pending validators are not showed in validators set valsMap := s.cfg.Validators.GetMap(staker.SubnetID) - r.Empty(valsMap) + r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(r *require.Assertions, s *state, staker *Staker) { // pending validators uptime is not tracked @@ -389,7 +389,7 @@ func TestPersistStakers(t *testing.T) { }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { valsMap := s.cfg.Validators.GetMap(staker.SubnetID) - r.Empty(valsMap) + r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(*require.Assertions, *state, *Staker) {}, checkDiffs: func(*require.Assertions, *state, *Staker, uint64) {}, @@ -436,7 +436,7 @@ func TestPersistStakers(t *testing.T) { checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { // deleted validators are not showed in the validators set anymore valsMap := s.cfg.Validators.GetMap(staker.SubnetID) - r.Empty(valsMap) + r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(r *require.Assertions, s *state, staker *Staker) { // uptimes of delete validators are dropped @@ -533,9 +533,8 @@ func TestPersistStakers(t *testing.T) { r.NoError(err) valsMap := s.cfg.Validators.GetMap(staker.SubnetID) - r.Len(valsMap, 1) - valOut, found := valsMap[staker.NodeID] - r.True(found) + r.Contains(valsMap, staker.NodeID) + valOut := valsMap[staker.NodeID] r.Equal(valOut.NodeID, staker.NodeID) r.Equal(valOut.Weight, val.Weight) }, @@ -591,7 +590,7 @@ func TestPersistStakers(t *testing.T) { }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { valsMap := s.cfg.Validators.GetMap(staker.SubnetID) - r.Empty(valsMap) + r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(r *require.Assertions, s *state, staker *Staker) { _, _, err := s.GetUptime(staker.NodeID, staker.SubnetID) @@ -662,7 +661,7 @@ func TestPersistStakers(t *testing.T) { }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { valsMap := s.cfg.Validators.GetMap(staker.SubnetID) - r.Empty(valsMap) + r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(*require.Assertions, *state, *Staker) {}, checkDiffs: func(*require.Assertions, *state, *Staker, uint64) {}, @@ -675,7 +674,8 @@ func TestPersistStakers(t *testing.T) { t.Run(fmt.Sprintf("%s - subnetID %s", name, subnetID), func(t *testing.T) { require := require.New(t) - state, db := newUninitializedState(require) + db := memdb.New() + state := newTestState(t, db) // create and store the staker staker := test.storeStaker(require, subnetID, state) @@ -687,120 +687,18 @@ func TestPersistStakers(t *testing.T) { test.checkDiffs(require, state, staker, 0 /*height*/) // rebuild the state - rebuiltState := newStateFromDB(require, db) - - // load relevant quantities - require.NoError(rebuiltState.loadCurrentValidators()) - require.NoError(rebuiltState.loadPendingValidators()) - require.NoError(rebuiltState.initValidatorSets()) + rebuiltState := newTestState(t, db) // check again that all relevant data are still available in rebuilt state - test.checkStakerInState(require, state, staker) - test.checkValidatorsSet(require, state, staker) - test.checkValidatorUptimes(require, state, staker) - test.checkDiffs(require, state, staker, 0 /*height*/) + test.checkStakerInState(require, rebuiltState, staker) + test.checkValidatorsSet(require, rebuiltState, staker) + test.checkValidatorUptimes(require, rebuiltState, staker) + test.checkDiffs(require, rebuiltState, staker, 0 /*height*/) }) } } } -func newInitializedState(require *require.Assertions) State { - s, _ := newUninitializedState(require) - initializeState(require, s) - return s -} - -func newUninitializedState(require *require.Assertions) (*state, database.Database) { - db := memdb.New() - return newStateFromDB(require, db), db -} - -func initializeState(require *require.Assertions, s *state) { - initialValidator := &txs.AddValidatorTx{ - Validator: txs.Validator{ - NodeID: initialNodeID, - Start: uint64(initialTime.Unix()), - End: uint64(initialValidatorEndTime.Unix()), - Wght: units.Avax, - }, - StakeOuts: []*avax.TransferableOutput{ - { - Asset: avax.Asset{ID: initialTxID}, - Out: &secp256k1fx.TransferOutput{ - Amt: units.Avax, - }, - }, - }, - RewardsOwner: &secp256k1fx.OutputOwners{}, - DelegationShares: reward.PercentDenominator, - } - initialValidatorTx := &txs.Tx{Unsigned: initialValidator} - require.NoError(initialValidatorTx.Initialize(txs.Codec)) - - initialChain := &txs.CreateChainTx{ - SubnetID: constants.PrimaryNetworkID, - ChainName: "x", - VMID: constants.AVMID, - SubnetAuth: &secp256k1fx.Input{}, - } - initialChainTx := &txs.Tx{Unsigned: initialChain} - require.NoError(initialChainTx.Initialize(txs.Codec)) - - genesisBlkID := ids.GenerateTestID() - genesisState := &genesis.Genesis{ - UTXOs: []*genesis.UTXO{ - { - UTXO: avax.UTXO{ - UTXOID: avax.UTXOID{ - TxID: initialTxID, - OutputIndex: 0, - }, - Asset: avax.Asset{ID: initialTxID}, - Out: &secp256k1fx.TransferOutput{ - Amt: units.Schmeckle, - }, - }, - Message: nil, - }, - }, - Validators: []*txs.Tx{ - initialValidatorTx, - }, - Chains: []*txs.Tx{ - initialChainTx, - }, - Timestamp: uint64(initialTime.Unix()), - InitialSupply: units.Schmeckle + units.Avax, - } - - genesisBlk, err := block.NewApricotCommitBlock(genesisBlkID, 0) - require.NoError(err) - require.NoError(s.syncGenesis(genesisBlk, genesisState)) -} - -func newStateFromDB(require *require.Assertions, db database.Database) *state { - execCfg, _ := config.GetExecutionConfig(nil) - state, err := newState( - db, - metrics.Noop, - &config.Config{ - Validators: validators.NewManager(), - }, - execCfg, - &snow.Context{}, - prometheus.NewRegistry(), - reward.NewCalculator(reward.Config{ - MaxConsumptionRate: .12 * reward.PercentDenominator, - MinConsumptionRate: .1 * reward.PercentDenominator, - MintingPeriod: 365 * 24 * time.Hour, - SupplyCap: 720 * units.MegaAvax, - }), - ) - require.NoError(err) - require.NotNil(state) - return state -} - func createPermissionlessValidatorTx(r *require.Assertions, subnetID ids.ID, validatorsData txs.Validator) *txs.AddPermissionlessValidatorTx { var sig signer.Signer = &signer.Empty{} if subnetID == constants.PrimaryNetworkID { @@ -1076,7 +974,7 @@ func TestValidatorWeightDiff(t *testing.T) { func TestStateAddRemoveValidator(t *testing.T) { require := require.New(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) var ( numNodes = 3 @@ -1331,7 +1229,7 @@ func TestParsedStateBlock(t *testing.T) { func TestReindexBlocks(t *testing.T) { var ( require = require.New(t) - s = newInitializedState(require).(*state) + s = newTestState(t, memdb.New()) blks = makeBlocks(require) ) @@ -1372,7 +1270,7 @@ func TestReindexBlocks(t *testing.T) { func TestStateSubnetOwner(t *testing.T) { require := require.New(t) - state := newInitializedState(require) + state := newTestState(t, memdb.New()) ctrl := gomock.NewController(t) var ( @@ -1435,7 +1333,7 @@ func TestStateSubnetManager(t *testing.T) { t.Run(test.name, func(t *testing.T) { require := require.New(t) - initializedState := newInitializedState(require) + initializedState := newTestState(t, memdb.New()) subnetID := ids.GenerateTestID() chainID, addr, err := initializedState.GetSubnetManager(subnetID) @@ -1549,8 +1447,8 @@ func makeBlocks(require *require.Assertions) []block.Block { func TestStateFeeStateCommitAndLoad(t *testing.T) { require := require.New(t) - s, db := newUninitializedState(require) - initializeState(require, s) + db := memdb.New() + s := newTestState(t, db) expectedFeeState := fee.State{ Capacity: 1, @@ -1559,11 +1457,25 @@ func TestStateFeeStateCommitAndLoad(t *testing.T) { s.SetFeeState(expectedFeeState) require.NoError(s.Commit()) - s = newStateFromDB(require, db) - require.NoError(s.load()) + s = newTestState(t, db) require.Equal(expectedFeeState, s.GetFeeState()) } +func TestMarkAndIsInitialized(t *testing.T) { + require := require.New(t) + + db := memdb.New() + defaultIsInitialized, err := isInitialized(db) + require.NoError(err) + require.False(defaultIsInitialized) + + require.NoError(markInitialized(db)) + + isInitializedAfterMarking, err := isInitialized(db) + require.NoError(err) + require.True(isInitializedAfterMarking) +} + // Verify that reading from the database returns the same value that was written // to it. func TestPutAndGetFeeState(t *testing.T) { From 76f19183bbb3fb81c264a04facb9f6a1ae8f1dc8 Mon Sep 17 00:00:00 2001 From: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> Date: Tue, 20 Aug 2024 16:12:01 -0400 Subject: [PATCH 29/69] Remove mock for `Versions` interface (#3312) --- scripts/mocks.mockgen.txt | 2 +- vms/platformvm/state/diff_test.go | 25 +++++++----------- vms/platformvm/state/mock_state.go | 42 ++---------------------------- 3 files changed, 12 insertions(+), 57 deletions(-) diff --git a/scripts/mocks.mockgen.txt b/scripts/mocks.mockgen.txt index 139252666ab0..688eee77a57b 100644 --- a/scripts/mocks.mockgen.txt +++ b/scripts/mocks.mockgen.txt @@ -29,7 +29,7 @@ github.com/ava-labs/avalanchego/vms/avm/txs/mempool=Mempool=vms/avm/txs/mempool/ github.com/ava-labs/avalanchego/vms/components/avax=TransferableIn=vms/components/avax/mock_transferable_in.go github.com/ava-labs/avalanchego/vms/components/verify=Verifiable=vms/components/verify/mock_verifiable.go github.com/ava-labs/avalanchego/vms/platformvm/block=Block=vms/platformvm/block/mock_block.go -github.com/ava-labs/avalanchego/vms/platformvm/state=Chain,Diff,State,Versions=vms/platformvm/state/mock_state.go +github.com/ava-labs/avalanchego/vms/platformvm/state=Chain,Diff,State=vms/platformvm/state/mock_state.go github.com/ava-labs/avalanchego/vms/platformvm/state=StakerIterator=vms/platformvm/state/mock_staker_iterator.go github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool=Mempool=vms/platformvm/txs/mempool/mock_mempool.go github.com/ava-labs/avalanchego/vms/platformvm/utxo=Verifier=vms/platformvm/utxo/mock_verifier.go diff --git a/vms/platformvm/state/diff_test.go b/vms/platformvm/state/diff_test.go index d76437f692df..2b2945591e5b 100644 --- a/vms/platformvm/state/diff_test.go +++ b/vms/platformvm/state/diff_test.go @@ -22,15 +22,15 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) -func TestDiffMissingState(t *testing.T) { - ctrl := gomock.NewController(t) +type nilStateGetter struct{} - versions := NewMockVersions(ctrl) +func (nilStateGetter) GetState(ids.ID) (Chain, bool) { + return nil, false +} +func TestDiffMissingState(t *testing.T) { parentID := ids.GenerateTestID() - versions.EXPECT().GetState(parentID).Times(1).Return(nil, false) - - _, err := NewDiff(parentID, versions) + _, err := NewDiff(parentID, nilStateGetter{}) require.ErrorIs(t, err, ErrMissingParentState) } @@ -587,16 +587,9 @@ func TestDiffSubnetOwner(t *testing.T) { } func TestDiffSubnetManager(t *testing.T) { - require := require.New(t) - ctrl := gomock.NewController(t) - - state := newTestState(t, memdb.New()) - - states := NewMockVersions(ctrl) - lastAcceptedID := ids.GenerateTestID() - states.EXPECT().GetState(lastAcceptedID).Return(state, true).AnyTimes() - var ( + require = require.New(t) + state = newTestState(t, memdb.New()) newManager = chainIDAndAddr{ids.GenerateTestID(), []byte{1, 2, 3, 4}} subnetID = ids.GenerateTestID() ) @@ -606,7 +599,7 @@ func TestDiffSubnetManager(t *testing.T) { require.Equal(ids.Empty, chainID) require.Nil(addr) - d, err := NewDiff(lastAcceptedID, states) + d, err := NewDiffOn(state) require.NoError(err) chainID, addr, err = d.GetSubnetManager(subnetID) diff --git a/vms/platformvm/state/mock_state.go b/vms/platformvm/state/mock_state.go index 3e90ddbfb6fa..caa1c12a5817 100644 --- a/vms/platformvm/state/mock_state.go +++ b/vms/platformvm/state/mock_state.go @@ -1,9 +1,9 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/platformvm/state (interfaces: Chain,Diff,State,Versions) +// Source: github.com/ava-labs/avalanchego/vms/platformvm/state (interfaces: Chain,Diff,State) // // Generated by this command: // -// mockgen -package=state -destination=vms/platformvm/state/mock_state.go github.com/ava-labs/avalanchego/vms/platformvm/state Chain,Diff,State,Versions +// mockgen -package=state -destination=vms/platformvm/state/mock_state.go github.com/ava-labs/avalanchego/vms/platformvm/state Chain,Diff,State // // Package state is a generated GoMock package. @@ -1843,41 +1843,3 @@ func (mr *MockStateMockRecorder) UTXOIDs(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UTXOIDs", reflect.TypeOf((*MockState)(nil).UTXOIDs), arg0, arg1, arg2) } - -// MockVersions is a mock of Versions interface. -type MockVersions struct { - ctrl *gomock.Controller - recorder *MockVersionsMockRecorder -} - -// MockVersionsMockRecorder is the mock recorder for MockVersions. -type MockVersionsMockRecorder struct { - mock *MockVersions -} - -// NewMockVersions creates a new mock instance. -func NewMockVersions(ctrl *gomock.Controller) *MockVersions { - mock := &MockVersions{ctrl: ctrl} - mock.recorder = &MockVersionsMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVersions) EXPECT() *MockVersionsMockRecorder { - return m.recorder -} - -// GetState mocks base method. -func (m *MockVersions) GetState(arg0 ids.ID) (Chain, bool) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetState", arg0) - ret0, _ := ret[0].(Chain) - ret1, _ := ret[1].(bool) - return ret0, ret1 -} - -// GetState indicates an expected call of GetState. -func (mr *MockVersionsMockRecorder) GetState(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetState", reflect.TypeOf((*MockVersions)(nil).GetState), arg0) -} From bfe9fbb0dac11d8460867b8cd75e8cadbf9939c4 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 20 Aug 2024 16:39:49 -0400 Subject: [PATCH 30/69] Allow P-chain wallet to be used by the platformvm (#3314) --- wallet/chain/p/builder_test.go | 23 +++---- wallet/chain/p/client.go | 54 ++++++++++++++++ wallet/chain/p/{ => wallet}/backend.go | 2 +- .../chain/p/{ => wallet}/backend_visitor.go | 2 +- wallet/chain/p/{ => wallet}/wallet.go | 61 +++++-------------- .../with_options.go} | 44 ++++++------- .../examples/get-p-chain-balance/main.go | 4 +- wallet/subnet/primary/wallet.go | 16 ++--- 8 files changed, 116 insertions(+), 90 deletions(-) create mode 100644 wallet/chain/p/client.go rename wallet/chain/p/{ => wallet}/backend.go (99%) rename wallet/chain/p/{ => wallet}/backend_visitor.go (99%) rename wallet/chain/p/{ => wallet}/wallet.go (94%) rename wallet/chain/p/{wallet_with_options.go => wallet/with_options.go} (82%) diff --git a/wallet/chain/p/builder_test.go b/wallet/chain/p/builder_test.go index 6885a3b4fc9e..69168e463b2e 100644 --- a/wallet/chain/p/builder_test.go +++ b/wallet/chain/p/builder_test.go @@ -25,6 +25,7 @@ import ( "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/vms/types" "github.com/ava-labs/avalanchego/wallet/chain/p/builder" + "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common/utxotest" @@ -174,7 +175,7 @@ func TestBaseTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, nil) + backend = wallet.NewBackend(e.context, chainUTXOs, nil) builder = builder.New(set.Of(utxoAddr), e.context, backend) ) @@ -214,7 +215,7 @@ func TestAddSubnetValidatorTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnetOwners) + backend = wallet.NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -246,7 +247,7 @@ func TestRemoveSubnetValidatorTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnetOwners) + backend = wallet.NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -287,7 +288,7 @@ func TestCreateChainTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnetOwners) + backend = wallet.NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -327,7 +328,7 @@ func TestCreateSubnetTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnetOwners) + backend = wallet.NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -359,7 +360,7 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnetOwners) + backend = wallet.NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -399,7 +400,7 @@ func TestImportTx(t *testing.T) { constants.PlatformChainID: utxos, sourceChainID: importedUTXOs, }) - backend = NewBackend(e.context, chainUTXOs, nil) + backend = wallet.NewBackend(e.context, chainUTXOs, nil) builder = builder.New(set.Of(utxoAddr), e.context, backend) ) @@ -436,7 +437,7 @@ func TestExportTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, nil) + backend = wallet.NewBackend(e.context, chainUTXOs, nil) builder = builder.New(set.Of(utxoAddr), e.context, backend) ) @@ -486,7 +487,7 @@ func TestTransformSubnetTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, subnetOwners) + backend = wallet.NewBackend(e.context, chainUTXOs, subnetOwners) builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) ) @@ -578,7 +579,7 @@ func TestAddPermissionlessValidatorTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, nil) + backend = wallet.NewBackend(e.context, chainUTXOs, nil) builder = builder.New(set.Of(utxoAddr, rewardAddr), e.context, backend) ) @@ -631,7 +632,7 @@ func TestAddPermissionlessDelegatorTx(t *testing.T) { chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ constants.PlatformChainID: utxos, }) - backend = NewBackend(e.context, chainUTXOs, nil) + backend = wallet.NewBackend(e.context, chainUTXOs, nil) builder = builder.New(set.Of(utxoAddr, rewardAddr), e.context, backend) ) diff --git a/wallet/chain/p/client.go b/wallet/chain/p/client.go new file mode 100644 index 000000000000..6575f5deed75 --- /dev/null +++ b/wallet/chain/p/client.go @@ -0,0 +1,54 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package p + +import ( + "github.com/ava-labs/avalanchego/vms/platformvm" + "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" + "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" +) + +var _ wallet.Client = (*Client)(nil) + +func NewClient( + c platformvm.Client, + b wallet.Backend, +) *Client { + return &Client{ + client: c, + backend: b, + } +} + +type Client struct { + client platformvm.Client + backend wallet.Backend +} + +func (c *Client) IssueTx( + tx *txs.Tx, + options ...common.Option, +) error { + ops := common.NewOptions(options) + ctx := ops.Context() + txID, err := c.client.IssueTx(ctx, tx.Bytes()) + if err != nil { + return err + } + + if f := ops.PostIssuanceFunc(); f != nil { + f(txID) + } + + if ops.AssumeDecided() { + return c.backend.AcceptTx(ctx, tx) + } + + if err := platformvm.AwaitTxAccepted(c.client, ctx, txID, ops.PollFrequency()); err != nil { + return err + } + + return c.backend.AcceptTx(ctx, tx) +} diff --git a/wallet/chain/p/backend.go b/wallet/chain/p/wallet/backend.go similarity index 99% rename from wallet/chain/p/backend.go rename to wallet/chain/p/wallet/backend.go index 8a1cd6b7806c..f46902fa8a51 100644 --- a/wallet/chain/p/backend.go +++ b/wallet/chain/p/wallet/backend.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package p +package wallet import ( "context" diff --git a/wallet/chain/p/backend_visitor.go b/wallet/chain/p/wallet/backend_visitor.go similarity index 99% rename from wallet/chain/p/backend_visitor.go rename to wallet/chain/p/wallet/backend_visitor.go index c7cec9544da1..61dc3e231da7 100644 --- a/wallet/chain/p/backend_visitor.go +++ b/wallet/chain/p/wallet/backend_visitor.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package p +package wallet import ( "context" diff --git a/wallet/chain/p/wallet.go b/wallet/chain/p/wallet/wallet.go similarity index 94% rename from wallet/chain/p/wallet.go rename to wallet/chain/p/wallet/wallet.go index 631553431ef7..d7414f1b3e28 100644 --- a/wallet/chain/p/wallet.go +++ b/wallet/chain/p/wallet/wallet.go @@ -1,15 +1,13 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package p +package wallet import ( - "errors" "time" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/platformvm" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/chain/p/builder" @@ -19,13 +17,19 @@ import ( walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) -var ( - ErrNotCommitted = errors.New("not committed") +var _ Wallet = (*wallet)(nil) - _ Wallet = (*wallet)(nil) -) +type Client interface { + // IssueTx issues the signed tx. + IssueTx( + tx *txs.Tx, + options ...common.Option, + ) error +} type Wallet interface { + Client + // Builder returns the builder that will be used to create the transactions. Builder() builder.Builder @@ -246,33 +250,24 @@ type Wallet interface { utx txs.UnsignedTx, options ...common.Option, ) (*txs.Tx, error) - - // IssueTx issues the signed tx. - IssueTx( - tx *txs.Tx, - options ...common.Option, - ) error } -func NewWallet( +func New( + client Client, builder builder.Builder, signer walletsigner.Signer, - client platformvm.Client, - backend Backend, ) Wallet { return &wallet{ - Backend: backend, + Client: client, builder: builder, signer: signer, - client: client, } } type wallet struct { - Backend + Client builder builder.Builder signer walletsigner.Signer - client platformvm.Client } func (w *wallet) Builder() builder.Builder { @@ -499,29 +494,3 @@ func (w *wallet) IssueUnsignedTx( return tx, w.IssueTx(tx, options...) } - -func (w *wallet) IssueTx( - tx *txs.Tx, - options ...common.Option, -) error { - ops := common.NewOptions(options) - ctx := ops.Context() - txID, err := w.client.IssueTx(ctx, tx.Bytes()) - if err != nil { - return err - } - - if f := ops.PostIssuanceFunc(); f != nil { - f(txID) - } - - if ops.AssumeDecided() { - return w.Backend.AcceptTx(ctx, tx) - } - - if err := platformvm.AwaitTxAccepted(w.client, ctx, txID, ops.PollFrequency()); err != nil { - return err - } - - return w.Backend.AcceptTx(ctx, tx) -} diff --git a/wallet/chain/p/wallet_with_options.go b/wallet/chain/p/wallet/with_options.go similarity index 82% rename from wallet/chain/p/wallet_with_options.go rename to wallet/chain/p/wallet/with_options.go index 92965f2e4f1f..64b22050a953 100644 --- a/wallet/chain/p/wallet_with_options.go +++ b/wallet/chain/p/wallet/with_options.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package p +package wallet import ( "time" @@ -17,35 +17,35 @@ import ( walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) -var _ Wallet = (*walletWithOptions)(nil) +var _ Wallet = (*withOptions)(nil) -func NewWalletWithOptions( +func WithOptions( wallet Wallet, options ...common.Option, ) Wallet { - return &walletWithOptions{ + return &withOptions{ wallet: wallet, options: options, } } -type walletWithOptions struct { +type withOptions struct { wallet Wallet options []common.Option } -func (w *walletWithOptions) Builder() builder.Builder { +func (w *withOptions) Builder() builder.Builder { return builder.NewWithOptions( w.wallet.Builder(), w.options..., ) } -func (w *walletWithOptions) Signer() walletsigner.Signer { +func (w *withOptions) Signer() walletsigner.Signer { return w.wallet.Signer() } -func (w *walletWithOptions) IssueBaseTx( +func (w *withOptions) IssueBaseTx( outputs []*avax.TransferableOutput, options ...common.Option, ) (*txs.Tx, error) { @@ -55,7 +55,7 @@ func (w *walletWithOptions) IssueBaseTx( ) } -func (w *walletWithOptions) IssueAddValidatorTx( +func (w *withOptions) IssueAddValidatorTx( vdr *txs.Validator, rewardsOwner *secp256k1fx.OutputOwners, shares uint32, @@ -69,7 +69,7 @@ func (w *walletWithOptions) IssueAddValidatorTx( ) } -func (w *walletWithOptions) IssueAddSubnetValidatorTx( +func (w *withOptions) IssueAddSubnetValidatorTx( vdr *txs.SubnetValidator, options ...common.Option, ) (*txs.Tx, error) { @@ -79,7 +79,7 @@ func (w *walletWithOptions) IssueAddSubnetValidatorTx( ) } -func (w *walletWithOptions) IssueRemoveSubnetValidatorTx( +func (w *withOptions) IssueRemoveSubnetValidatorTx( nodeID ids.NodeID, subnetID ids.ID, options ...common.Option, @@ -91,7 +91,7 @@ func (w *walletWithOptions) IssueRemoveSubnetValidatorTx( ) } -func (w *walletWithOptions) IssueAddDelegatorTx( +func (w *withOptions) IssueAddDelegatorTx( vdr *txs.Validator, rewardsOwner *secp256k1fx.OutputOwners, options ...common.Option, @@ -103,7 +103,7 @@ func (w *walletWithOptions) IssueAddDelegatorTx( ) } -func (w *walletWithOptions) IssueCreateChainTx( +func (w *withOptions) IssueCreateChainTx( subnetID ids.ID, genesis []byte, vmID ids.ID, @@ -121,7 +121,7 @@ func (w *walletWithOptions) IssueCreateChainTx( ) } -func (w *walletWithOptions) IssueCreateSubnetTx( +func (w *withOptions) IssueCreateSubnetTx( owner *secp256k1fx.OutputOwners, options ...common.Option, ) (*txs.Tx, error) { @@ -131,7 +131,7 @@ func (w *walletWithOptions) IssueCreateSubnetTx( ) } -func (w *walletWithOptions) IssueTransferSubnetOwnershipTx( +func (w *withOptions) IssueTransferSubnetOwnershipTx( subnetID ids.ID, owner *secp256k1fx.OutputOwners, options ...common.Option, @@ -143,7 +143,7 @@ func (w *walletWithOptions) IssueTransferSubnetOwnershipTx( ) } -func (w *walletWithOptions) IssueImportTx( +func (w *withOptions) IssueImportTx( sourceChainID ids.ID, to *secp256k1fx.OutputOwners, options ...common.Option, @@ -155,7 +155,7 @@ func (w *walletWithOptions) IssueImportTx( ) } -func (w *walletWithOptions) IssueExportTx( +func (w *withOptions) IssueExportTx( chainID ids.ID, outputs []*avax.TransferableOutput, options ...common.Option, @@ -167,7 +167,7 @@ func (w *walletWithOptions) IssueExportTx( ) } -func (w *walletWithOptions) IssueTransformSubnetTx( +func (w *withOptions) IssueTransformSubnetTx( subnetID ids.ID, assetID ids.ID, initialSupply uint64, @@ -203,7 +203,7 @@ func (w *walletWithOptions) IssueTransformSubnetTx( ) } -func (w *walletWithOptions) IssueAddPermissionlessValidatorTx( +func (w *withOptions) IssueAddPermissionlessValidatorTx( vdr *txs.SubnetValidator, signer vmsigner.Signer, assetID ids.ID, @@ -223,7 +223,7 @@ func (w *walletWithOptions) IssueAddPermissionlessValidatorTx( ) } -func (w *walletWithOptions) IssueAddPermissionlessDelegatorTx( +func (w *withOptions) IssueAddPermissionlessDelegatorTx( vdr *txs.SubnetValidator, assetID ids.ID, rewardsOwner *secp256k1fx.OutputOwners, @@ -237,7 +237,7 @@ func (w *walletWithOptions) IssueAddPermissionlessDelegatorTx( ) } -func (w *walletWithOptions) IssueUnsignedTx( +func (w *withOptions) IssueUnsignedTx( utx txs.UnsignedTx, options ...common.Option, ) (*txs.Tx, error) { @@ -247,7 +247,7 @@ func (w *walletWithOptions) IssueUnsignedTx( ) } -func (w *walletWithOptions) IssueTx( +func (w *withOptions) IssueTx( tx *txs.Tx, options ...common.Option, ) error { diff --git a/wallet/subnet/primary/examples/get-p-chain-balance/main.go b/wallet/subnet/primary/examples/get-p-chain-balance/main.go index e190247515bf..a23c4c9b8e81 100644 --- a/wallet/subnet/primary/examples/get-p-chain-balance/main.go +++ b/wallet/subnet/primary/examples/get-p-chain-balance/main.go @@ -11,8 +11,8 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/set" - "github.com/ava-labs/avalanchego/wallet/chain/p" "github.com/ava-labs/avalanchego/wallet/chain/p/builder" + "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" "github.com/ava-labs/avalanchego/wallet/subnet/primary" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) @@ -38,7 +38,7 @@ func main() { log.Printf("fetched state of %s in %s\n", addrStr, time.Since(fetchStartTime)) pUTXOs := common.NewChainUTXOs(constants.PlatformChainID, state.UTXOs) - pBackend := p.NewBackend(state.PCTX, pUTXOs, nil) + pBackend := wallet.NewBackend(state.PCTX, pUTXOs, nil) pBuilder := builder.New(addresses, state.PCTX, pBackend) currentBalances, err := pBuilder.GetBalance() diff --git a/wallet/subnet/primary/wallet.go b/wallet/subnet/primary/wallet.go index d2c9f4d45050..2b35c944c39c 100644 --- a/wallet/subnet/primary/wallet.go +++ b/wallet/subnet/primary/wallet.go @@ -17,6 +17,7 @@ import ( pbuilder "github.com/ava-labs/avalanchego/wallet/chain/p/builder" psigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" + pwallet "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" xbuilder "github.com/ava-labs/avalanchego/wallet/chain/x/builder" xsigner "github.com/ava-labs/avalanchego/wallet/chain/x/signer" ) @@ -25,18 +26,18 @@ var _ Wallet = (*wallet)(nil) // Wallet provides chain wallets for the primary network. type Wallet interface { - P() p.Wallet + P() pwallet.Wallet X() x.Wallet C() c.Wallet } type wallet struct { - p p.Wallet + p pwallet.Wallet x x.Wallet c c.Wallet } -func (w *wallet) P() p.Wallet { +func (w *wallet) P() pwallet.Wallet { return w.p } @@ -49,7 +50,7 @@ func (w *wallet) C() c.Wallet { } // Creates a new default wallet -func NewWallet(p p.Wallet, x x.Wallet, c c.Wallet) Wallet { +func NewWallet(p pwallet.Wallet, x x.Wallet, c c.Wallet) Wallet { return &wallet{ p: p, x: x, @@ -60,7 +61,7 @@ func NewWallet(p p.Wallet, x x.Wallet, c c.Wallet) Wallet { // Creates a Wallet with the given set of options func NewWalletWithOptions(w Wallet, options ...common.Option) Wallet { return NewWallet( - p.NewWalletWithOptions(w.P(), options...), + pwallet.WithOptions(w.P(), options...), x.NewWalletWithOptions(w.X(), options...), c.NewWalletWithOptions(w.C(), options...), ) @@ -105,7 +106,8 @@ func MakeWallet(ctx context.Context, config *WalletConfig) (Wallet, error) { return nil, err } pUTXOs := common.NewChainUTXOs(constants.PlatformChainID, avaxState.UTXOs) - pBackend := p.NewBackend(avaxState.PCTX, pUTXOs, subnetOwners) + pBackend := pwallet.NewBackend(avaxState.PCTX, pUTXOs, subnetOwners) + pClient := p.NewClient(avaxState.PClient, pBackend) pBuilder := pbuilder.New(avaxAddrs, avaxState.PCTX, pBackend) pSigner := psigner.New(config.AVAXKeychain, pBackend) @@ -122,7 +124,7 @@ func MakeWallet(ctx context.Context, config *WalletConfig) (Wallet, error) { cSigner := c.NewSigner(config.AVAXKeychain, config.EthKeychain, cBackend) return NewWallet( - p.NewWallet(pBuilder, pSigner, avaxState.PClient, pBackend), + pwallet.New(pClient, pBuilder, pSigner), x.NewWallet(xBuilder, xSigner, avaxState.XClient, xBackend), c.NewWallet(cBuilder, cSigner, avaxState.CClient, ethState.Client, cBackend), ), nil From a5acbaa34571e3a5b25dce2b41a26bc5d52d2de9 Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Wed, 21 Aug 2024 05:27:15 +0300 Subject: [PATCH 31/69] Remove crosschain leftovers (#3309) --- ids/request_id.go | 4 +- message/fields.go | 12 ---- snow/networking/router/chain_router.go | 64 +++++++-------------- snow/networking/router/chain_router_test.go | 13 +---- snow/networking/router/mock_router.go | 8 +-- snow/networking/router/router.go | 3 +- snow/networking/router/traced_router.go | 17 ++---- snow/networking/sender/sender.go | 9 --- snow/networking/sender/sender_test.go | 4 -- 9 files changed, 32 insertions(+), 102 deletions(-) diff --git a/ids/request_id.go b/ids/request_id.go index e1d9459866f7..fe4aeb15f003 100644 --- a/ids/request_id.go +++ b/ids/request_id.go @@ -7,10 +7,8 @@ package ids type RequestID struct { // The node this request came from NodeID NodeID - // The chain this request came from - SourceChainID ID // The chain the expected response should come from - DestinationChainID ID + ChainID ID // The unique identifier for this request RequestID uint32 // The message opcode diff --git a/message/fields.go b/message/fields.go index 453315f4323a..962532d06a2f 100644 --- a/message/fields.go +++ b/message/fields.go @@ -77,18 +77,6 @@ func GetChainID(m any) (ids.ID, error) { return ids.ToID(chainIDBytes) } -type sourceChainIDGetter interface { - GetSourceChainID() ids.ID -} - -func GetSourceChainID(m any) (ids.ID, error) { - msg, ok := m.(sourceChainIDGetter) - if !ok { - return GetChainID(m) - } - return msg.GetSourceChainID(), nil -} - type requestIDGetter interface { GetRequestId() uint32 } diff --git a/snow/networking/router/chain_router.go b/snow/networking/router/chain_router.go index 6af0984afc3f..d319e721c639 100644 --- a/snow/networking/router/chain_router.go +++ b/snow/networking/router/chain_router.go @@ -136,7 +136,7 @@ func (cr *ChainRouter) Initialize( } // RegisterRequest marks that we should expect to receive a reply for a request -// issued by [requestingChainID] from the given node's [respondingChainID] and +// from the given node's [chainID] and // the reply should have the given requestID. // // The type of message we expect is [op]. @@ -148,8 +148,7 @@ func (cr *ChainRouter) Initialize( func (cr *ChainRouter) RegisterRequest( ctx context.Context, nodeID ids.NodeID, - requestingChainID ids.ID, - respondingChainID ids.ID, + chainID ids.ID, requestID uint32, op message.Op, timeoutMsg message.InboundMessage, @@ -159,8 +158,7 @@ func (cr *ChainRouter) RegisterRequest( if cr.closing { cr.log.Debug("dropping request", zap.Stringer("nodeID", nodeID), - zap.Stringer("requestingChainID", requestingChainID), - zap.Stringer("respondingChainID", respondingChainID), + zap.Stringer("chainID", chainID), zap.Uint32("requestID", requestID), zap.Stringer("messageOp", op), zap.Error(errClosing), @@ -171,16 +169,11 @@ func (cr *ChainRouter) RegisterRequest( // When we receive a response message type (Chits, Put, Accepted, etc.) // we validate that we actually sent the corresponding request. // Give this request a unique ID so we can do that validation. - // - // For cross-chain messages, the responding chain is the source of the - // response which is sent to the requester which is the destination, - // which is why we flip the two in request id generation. uniqueRequestID := ids.RequestID{ - NodeID: nodeID, - SourceChainID: respondingChainID, - DestinationChainID: requestingChainID, - RequestID: requestID, - Op: byte(op), + NodeID: nodeID, + ChainID: chainID, + RequestID: requestID, + Op: byte(op), } // Add to the set of unfulfilled requests cr.timedRequests.Put(uniqueRequestID, requestEntry{ @@ -203,7 +196,7 @@ func (cr *ChainRouter) RegisterRequest( // Register a timeout to fire if we don't get a reply in time. cr.timeoutManager.RegisterRequest( nodeID, - respondingChainID, + chainID, shouldMeasureLatency, uniqueRequestID, func() { @@ -217,7 +210,7 @@ func (cr *ChainRouter) HandleInbound(ctx context.Context, msg message.InboundMes op := msg.Op() m := msg.Message() - destinationChainID, err := message.GetChainID(m) + chainID, err := message.GetChainID(m) if err != nil { cr.log.Debug("dropping message with invalid field", zap.Stringer("nodeID", nodeID), @@ -230,19 +223,6 @@ func (cr *ChainRouter) HandleInbound(ctx context.Context, msg message.InboundMes return } - sourceChainID, err := message.GetSourceChainID(m) - if err != nil { - cr.log.Debug("dropping message with invalid field", - zap.Stringer("nodeID", nodeID), - zap.Stringer("messageOp", op), - zap.String("field", "SourceChainID"), - zap.Error(err), - ) - - msg.OnFinishedHandling() - return - } - requestID, ok := message.GetRequestID(m) if !ok { cr.log.Debug("dropping message with invalid field", @@ -262,7 +242,7 @@ func (cr *ChainRouter) HandleInbound(ctx context.Context, msg message.InboundMes cr.log.Debug("dropping message", zap.Stringer("messageOp", op), zap.Stringer("nodeID", nodeID), - zap.Stringer("chainID", destinationChainID), + zap.Stringer("chainID", chainID), zap.Error(errClosing), ) msg.OnFinishedHandling() @@ -270,12 +250,12 @@ func (cr *ChainRouter) HandleInbound(ctx context.Context, msg message.InboundMes } // Get the chain, if it exists - chain, exists := cr.chainHandlers[destinationChainID] + chain, exists := cr.chainHandlers[chainID] if !exists { cr.log.Debug("dropping message", zap.Stringer("messageOp", op), zap.Stringer("nodeID", nodeID), - zap.Stringer("chainID", destinationChainID), + zap.Stringer("chainID", chainID), zap.Error(errUnknownChain), ) msg.OnFinishedHandling() @@ -286,7 +266,7 @@ func (cr *ChainRouter) HandleInbound(ctx context.Context, msg message.InboundMes cr.log.Debug("dropping message", zap.Stringer("messageOp", op), zap.Stringer("nodeID", nodeID), - zap.Stringer("chainID", destinationChainID), + zap.Stringer("chainID", chainID), zap.Error(errUnallowedNode), ) msg.OnFinishedHandling() @@ -321,7 +301,7 @@ func (cr *ChainRouter) HandleInbound(ctx context.Context, msg message.InboundMes if expectedResponse, isFailed := message.FailedToResponseOps[op]; isFailed { // Create the request ID of the request we sent that this message is in // response to. - uniqueRequestID, req := cr.clearRequest(expectedResponse, nodeID, sourceChainID, destinationChainID, requestID) + uniqueRequestID, req := cr.clearRequest(expectedResponse, nodeID, chainID, requestID) if req == nil { // This was a duplicated response. msg.OnFinishedHandling() @@ -352,7 +332,7 @@ func (cr *ChainRouter) HandleInbound(ctx context.Context, msg message.InboundMes return } - uniqueRequestID, req := cr.clearRequest(op, nodeID, sourceChainID, destinationChainID, requestID) + uniqueRequestID, req := cr.clearRequest(op, nodeID, chainID, requestID) if req == nil { // We didn't request this message. msg.OnFinishedHandling() @@ -363,7 +343,7 @@ func (cr *ChainRouter) HandleInbound(ctx context.Context, msg message.InboundMes latency := cr.clock.Time().Sub(req.time) // Tell the timeout manager we got a response - cr.timeoutManager.RegisterResponse(nodeID, destinationChainID, uniqueRequestID, req.op, latency) + cr.timeoutManager.RegisterResponse(nodeID, chainID, uniqueRequestID, req.op, latency) // Pass the response to the chain chain.Push( @@ -736,17 +716,15 @@ func (cr *ChainRouter) removeChain(ctx context.Context, chainID ids.ID) { func (cr *ChainRouter) clearRequest( op message.Op, nodeID ids.NodeID, - sourceChainID ids.ID, - destinationChainID ids.ID, + chainID ids.ID, requestID uint32, ) (ids.RequestID, *requestEntry) { // Create the request ID of the request we sent that this message is (allegedly) in response to. uniqueRequestID := ids.RequestID{ - NodeID: nodeID, - SourceChainID: sourceChainID, - DestinationChainID: destinationChainID, - RequestID: requestID, - Op: byte(op), + NodeID: nodeID, + ChainID: chainID, + RequestID: requestID, + Op: byte(op), } // Mark that an outstanding request has been fulfilled request, exists := cr.timedRequests.Get(uniqueRequestID) diff --git a/snow/networking/router/chain_router_test.go b/snow/networking/router/chain_router_test.go index 8dcdef0a2e74..b203cc50e131 100644 --- a/snow/networking/router/chain_router_test.go +++ b/snow/networking/router/chain_router_test.go @@ -634,7 +634,6 @@ func TestRouterTimeout(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.StateSummaryFrontierOp, message.InternalGetStateSummaryFrontierFailed( @@ -653,7 +652,6 @@ func TestRouterTimeout(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.AcceptedStateSummaryOp, message.InternalGetAcceptedStateSummaryFailed( @@ -672,7 +670,6 @@ func TestRouterTimeout(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.AcceptedFrontierOp, message.InternalGetAcceptedFrontierFailed( @@ -691,7 +688,6 @@ func TestRouterTimeout(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.AcceptedOp, message.InternalGetAcceptedFailed( @@ -710,7 +706,6 @@ func TestRouterTimeout(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.AncestorsOp, message.InternalGetAncestorsFailed( @@ -730,7 +725,6 @@ func TestRouterTimeout(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.PutOp, message.InternalGetFailed( @@ -749,7 +743,6 @@ func TestRouterTimeout(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.ChitsOp, message.InternalQueryFailed( @@ -768,7 +761,6 @@ func TestRouterTimeout(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.AppResponseOp, message.InboundAppError( @@ -856,7 +848,6 @@ func TestRouterHonorsRequestedEngine(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.StateSummaryFrontierOp, message.InternalGetStateSummaryFrontierFailed( @@ -885,7 +876,6 @@ func TestRouterHonorsRequestedEngine(t *testing.T) { context.Background(), nodeID, ctx.ChainID, - ctx.ChainID, requestID, message.AcceptedStateSummaryOp, message.InternalGetAcceptedStateSummaryFailed( @@ -993,7 +983,6 @@ func TestRouterClearTimeouts(t *testing.T) { context.Background(), ids.EmptyNodeID, ids.Empty, - ids.Empty, requestID, tt.responseOp, tt.timeoutMsg, @@ -1537,7 +1526,7 @@ func TestAppRequest(t *testing.T) { } ctx := context.Background() - chainRouter.RegisterRequest(ctx, ids.EmptyNodeID, ids.Empty, ids.Empty, wantRequestID, tt.responseOp, tt.timeoutMsg, engineType) + chainRouter.RegisterRequest(ctx, ids.EmptyNodeID, ids.Empty, wantRequestID, tt.responseOp, tt.timeoutMsg, engineType) chainRouter.lock.Lock() require.Equal(1, chainRouter.timedRequests.Len()) chainRouter.lock.Unlock() diff --git a/snow/networking/router/mock_router.go b/snow/networking/router/mock_router.go index 548b32110775..6105b807acd8 100644 --- a/snow/networking/router/mock_router.go +++ b/snow/networking/router/mock_router.go @@ -139,15 +139,15 @@ func (mr *MockRouterMockRecorder) Initialize(nodeID, log, timeouts, shutdownTime } // RegisterRequest mocks base method. -func (m *MockRouter) RegisterRequest(ctx context.Context, nodeID ids.NodeID, sourceChainID, destinationChainID ids.ID, requestID uint32, op message.Op, failedMsg message.InboundMessage, engineType p2p.EngineType) { +func (m *MockRouter) RegisterRequest(ctx context.Context, nodeID ids.NodeID, chainID ids.ID, requestID uint32, op message.Op, failedMsg message.InboundMessage, engineType p2p.EngineType) { m.ctrl.T.Helper() - m.ctrl.Call(m, "RegisterRequest", ctx, nodeID, sourceChainID, destinationChainID, requestID, op, failedMsg, engineType) + m.ctrl.Call(m, "RegisterRequest", ctx, nodeID, chainID, requestID, op, failedMsg, engineType) } // RegisterRequest indicates an expected call of RegisterRequest. -func (mr *MockRouterMockRecorder) RegisterRequest(ctx, nodeID, sourceChainID, destinationChainID, requestID, op, failedMsg, engineType any) *gomock.Call { +func (mr *MockRouterMockRecorder) RegisterRequest(ctx, nodeID, chainID, requestID, op, failedMsg, engineType any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRequest", reflect.TypeOf((*MockRouter)(nil).RegisterRequest), ctx, nodeID, sourceChainID, destinationChainID, requestID, op, failedMsg, engineType) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRequest", reflect.TypeOf((*MockRouter)(nil).RegisterRequest), ctx, nodeID, chainID, requestID, op, failedMsg, engineType) } // Shutdown mocks base method. diff --git a/snow/networking/router/router.go b/snow/networking/router/router.go index ef4765cb0965..6e8c3df9cfea 100644 --- a/snow/networking/router/router.go +++ b/snow/networking/router/router.go @@ -50,8 +50,7 @@ type InternalHandler interface { RegisterRequest( ctx context.Context, nodeID ids.NodeID, - sourceChainID ids.ID, - destinationChainID ids.ID, + chainID ids.ID, requestID uint32, op message.Op, failedMsg message.InboundMessage, diff --git a/snow/networking/router/traced_router.go b/snow/networking/router/traced_router.go index cbd2b6ed1205..4be96ea93868 100644 --- a/snow/networking/router/traced_router.go +++ b/snow/networking/router/traced_router.go @@ -66,8 +66,7 @@ func (r *tracedRouter) Initialize( func (r *tracedRouter) RegisterRequest( ctx context.Context, nodeID ids.NodeID, - requestingChainID ids.ID, - respondingChainID ids.ID, + chainID ids.ID, requestID uint32, op message.Op, failedMsg message.InboundMessage, @@ -76,8 +75,7 @@ func (r *tracedRouter) RegisterRequest( r.router.RegisterRequest( ctx, nodeID, - requestingChainID, - respondingChainID, + chainID, requestID, op, failedMsg, @@ -87,13 +85,7 @@ func (r *tracedRouter) RegisterRequest( func (r *tracedRouter) HandleInbound(ctx context.Context, msg message.InboundMessage) { m := msg.Message() - destinationChainID, err := message.GetChainID(m) - if err != nil { - r.router.HandleInbound(ctx, msg) - return - } - - sourceChainID, err := message.GetSourceChainID(m) + chainID, err := message.GetChainID(m) if err != nil { r.router.HandleInbound(ctx, msg) return @@ -102,8 +94,7 @@ func (r *tracedRouter) HandleInbound(ctx context.Context, msg message.InboundMes ctx, span := r.tracer.Start(ctx, "tracedRouter.HandleInbound", oteltrace.WithAttributes( attribute.Stringer("nodeID", msg.NodeID()), attribute.Stringer("messageOp", msg.Op()), - attribute.Stringer("chainID", destinationChainID), - attribute.Stringer("sourceChainID", sourceChainID), + attribute.Stringer("chainID", chainID), )) defer span.End() diff --git a/snow/networking/sender/sender.go b/snow/networking/sender/sender.go index b8742fae0ff4..7db929517a72 100644 --- a/snow/networking/sender/sender.go +++ b/snow/networking/sender/sender.go @@ -100,7 +100,6 @@ func (s *sender) SendGetStateSummaryFrontier(ctx context.Context, nodeIDs set.Se ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.StateSummaryFrontierOp, inMsg, @@ -245,7 +244,6 @@ func (s *sender) SendGetAcceptedStateSummary(ctx context.Context, nodeIDs set.Se ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.AcceptedStateSummaryOp, inMsg, @@ -383,7 +381,6 @@ func (s *sender) SendGetAcceptedFrontier(ctx context.Context, nodeIDs set.Set[id ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.AcceptedFrontierOp, inMsg, @@ -519,7 +516,6 @@ func (s *sender) SendGetAccepted(ctx context.Context, nodeIDs set.Set[ids.NodeID ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.AcceptedOp, inMsg, @@ -646,7 +642,6 @@ func (s *sender) SendGetAncestors(ctx context.Context, nodeID ids.NodeID, reques ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.AncestorsOp, inMsg, @@ -768,7 +763,6 @@ func (s *sender) SendGet(ctx context.Context, nodeID ids.NodeID, requestID uint3 ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.PutOp, inMsg, @@ -908,7 +902,6 @@ func (s *sender) SendPushQuery( ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.ChitsOp, inMsg, @@ -1046,7 +1039,6 @@ func (s *sender) SendPullQuery( ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.ChitsOp, inMsg, @@ -1232,7 +1224,6 @@ func (s *sender) SendAppRequest(ctx context.Context, nodeIDs set.Set[ids.NodeID] ctx, nodeID, s.ctx.ChainID, - s.ctx.ChainID, requestID, message.AppResponseOp, inMsg, diff --git a/snow/networking/sender/sender_test.go b/snow/networking/sender/sender_test.go index fb1565865034..10033ada9b12 100644 --- a/snow/networking/sender/sender_test.go +++ b/snow/networking/sender/sender_test.go @@ -845,7 +845,6 @@ func TestSender_Bootstrap_Requests(t *testing.T) { router.EXPECT().RegisterRequest( gomock.Any(), // Context nodeID, // Node ID - ctx.ChainID, // Source Chain ctx.ChainID, // Destination Chain requestID, // Request ID tt.expectedResponseOp, // Operation @@ -1228,7 +1227,6 @@ func TestSender_Single_Request(t *testing.T) { router.EXPECT().RegisterRequest( gomock.Any(), // Context ctx.NodeID, // Node ID - ctx.ChainID, // Source Chain ctx.ChainID, // Destination Chain requestID, // Request ID tt.expectedResponseOp, // Operation @@ -1268,7 +1266,6 @@ func TestSender_Single_Request(t *testing.T) { router.EXPECT().RegisterRequest( gomock.Any(), // Context destinationNodeID, // Node ID - ctx.ChainID, // Source Chain ctx.ChainID, // Destination Chain requestID, // Request ID tt.expectedResponseOp, // Operation @@ -1304,7 +1301,6 @@ func TestSender_Single_Request(t *testing.T) { router.EXPECT().RegisterRequest( gomock.Any(), // Context destinationNodeID, // Node ID - ctx.ChainID, // Source Chain ctx.ChainID, // Destination Chain requestID, // Request ID tt.expectedResponseOp, // Operation From 34aa2a360818cea38f38df2bc7df4812a5e5515c Mon Sep 17 00:00:00 2001 From: cam-schultz <78878559+cam-schultz@users.noreply.github.com> Date: Tue, 20 Aug 2024 22:50:49 -0500 Subject: [PATCH 32/69] Rename race condition image tags (#3311) --- scripts/build_image.sh | 8 ++++---- scripts/tests.build_image.sh | 6 +++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/scripts/build_image.sh b/scripts/build_image.sh index 3a7b7e588d05..d587f41373e8 100755 --- a/scripts/build_image.sh +++ b/scripts/build_image.sh @@ -28,8 +28,8 @@ AVALANCHE_PATH=$( cd "$( dirname "${BASH_SOURCE[0]}" )"; cd .. && pwd ) # Load the constants source "$AVALANCHE_PATH"/scripts/constants.sh -if [[ $image_tag == *"-race" ]]; then - echo "Branch name must not end in '-race'" +if [[ $image_tag == *"-r" ]]; then + echo "Branch name must not end in '-r'" exit 1 fi @@ -84,8 +84,8 @@ echo "Building Docker Image with tags: $DOCKER_IMAGE:$commit_hash , $DOCKER_IMAG ${DOCKER_CMD} -t "$DOCKER_IMAGE:$commit_hash" -t "$DOCKER_IMAGE:$image_tag" \ "$AVALANCHE_PATH" -f "$AVALANCHE_PATH/Dockerfile" -echo "Building Docker Image with tags: $DOCKER_IMAGE:$commit_hash-race , $DOCKER_IMAGE:$image_tag-race" -${DOCKER_CMD} --build-arg="RACE_FLAG=-r" -t "$DOCKER_IMAGE:$commit_hash-race" -t "$DOCKER_IMAGE:$image_tag-race" \ +echo "Building Docker Image with tags: $DOCKER_IMAGE:$commit_hash-r , $DOCKER_IMAGE:$image_tag-r" +${DOCKER_CMD} --build-arg="RACE_FLAG=-r" -t "$DOCKER_IMAGE:$commit_hash-r" -t "$DOCKER_IMAGE:$image_tag-r" \ "$AVALANCHE_PATH" -f "$AVALANCHE_PATH/Dockerfile" # Only tag the latest image for the master branch when images are pushed to a registry diff --git a/scripts/tests.build_image.sh b/scripts/tests.build_image.sh index af3cea84f1da..a383b3190f96 100755 --- a/scripts/tests.build_image.sh +++ b/scripts/tests.build_image.sh @@ -36,13 +36,13 @@ build_and_test() { local target_images=( "$image_name:$commit_hash" "$image_name:$image_tag" - "$image_name:$commit_hash-race" - "$image_name:$image_tag-race" + "$image_name:$commit_hash-r" + "$image_name:$image_tag-r" ) for arch in "${arches[@]}"; do for target_image in "${target_images[@]}"; do - if [[ "$host_arch" == "amd64" && "$arch" == "arm64" && "$target_image" =~ "-race" ]]; then + if [[ "$host_arch" == "amd64" && "$arch" == "arm64" && "$target_image" =~ "-r" ]]; then # Error reported when trying to sanity check this configuration in github ci: # # FATAL: ThreadSanitizer: unsupported VMA range From 315496f5942300c5f7ea19e7f6afbcfb09e452b6 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Wed, 21 Aug 2024 00:57:02 -0400 Subject: [PATCH 33/69] Add .String() to Fork testing utility (#3315) --- upgrade/upgradetest/fork.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/upgrade/upgradetest/fork.go b/upgrade/upgradetest/fork.go index 01c9b2ea03ee..706fcb50fdd8 100644 --- a/upgrade/upgradetest/fork.go +++ b/upgrade/upgradetest/fork.go @@ -23,3 +23,36 @@ const ( // Fork is an enum of all the major network upgrades. type Fork int + +func (f Fork) String() string { + switch f { + case Etna: + return "Etna" + case Durango: + return "Durango" + case Cortina: + return "Cortina" + case Banff: + return "Banff" + case ApricotPhasePost6: + return "ApricotPhasePost6" + case ApricotPhase6: + return "ApricotPhase6" + case ApricotPhasePre6: + return "ApricotPhasePre6" + case ApricotPhase5: + return "ApricotPhase5" + case ApricotPhase4: + return "ApricotPhase4" + case ApricotPhase3: + return "ApricotPhase3" + case ApricotPhase2: + return "ApricotPhase2" + case ApricotPhase1: + return "ApricotPhase1" + case NoUpgrades: + return "NoUpgrades" + default: + return "Unknown" + } +} From f71b8d76ffd7e37d656405d58e3d6a93ca5cccba Mon Sep 17 00:00:00 2001 From: marun Date: Wed, 21 Aug 2024 09:04:12 -0700 Subject: [PATCH 34/69] [antithesis] Update schedule to make room for subnet-evm (#3317) --- .github/workflows/trigger-antithesis-avalanchego.yml | 2 +- .github/workflows/trigger-antithesis-xsvm.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/trigger-antithesis-avalanchego.yml b/.github/workflows/trigger-antithesis-avalanchego.yml index f02394fac4ec..cc12f3421617 100644 --- a/.github/workflows/trigger-antithesis-avalanchego.yml +++ b/.github/workflows/trigger-antithesis-avalanchego.yml @@ -37,5 +37,5 @@ jobs: email_recipients: ${{ github.event.inputs.recipients || secrets.ANTITHESIS_RECIPIENTS }} # Duration is in hours additional_parameters: |- - custom.duration=${{ github.event.inputs.duration || '11.25' }} + custom.duration=${{ github.event.inputs.duration || '7.5' }} custom.workload=avalanchego diff --git a/.github/workflows/trigger-antithesis-xsvm.yml b/.github/workflows/trigger-antithesis-xsvm.yml index ce9c43f74613..2bc083dcb045 100644 --- a/.github/workflows/trigger-antithesis-xsvm.yml +++ b/.github/workflows/trigger-antithesis-xsvm.yml @@ -2,7 +2,7 @@ name: Trigger Antithesis XSVM Setup on: schedule: - - cron: '0 10 * * *' # Every day at 10AM UTC + - cron: '0 6 * * *' # Every day at 6AM UTC workflow_dispatch: inputs: duration: @@ -37,5 +37,5 @@ jobs: email_recipients: ${{ github.event.inputs.recipients || secrets.ANTITHESIS_RECIPIENTS }} # Duration is in hours additional_parameters: |- - custom.duration=${{ github.event.inputs.duration || '11.25' }} + custom.duration=${{ github.event.inputs.duration || '7.5' }} custom.workload=xsvm From 35c66e33f0dcc607779f04717eb5e24ce7647296 Mon Sep 17 00:00:00 2001 From: marun Date: Wed, 21 Aug 2024 10:51:19 -0700 Subject: [PATCH 35/69] [tmpnet] Update monitoring urls from *-experimental to *-poc (#3306) --- .github/actions/run-monitored-tmpnet-cmd/action.yml | 2 +- scripts/run_prometheus.sh | 2 +- scripts/run_promtail.sh | 2 +- tests/fixture/tmpnet/README.md | 6 +++--- tests/fixture/tmpnet/network.go | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/actions/run-monitored-tmpnet-cmd/action.yml b/.github/actions/run-monitored-tmpnet-cmd/action.yml index 65b47f2c3a6c..ef6a7930a795 100644 --- a/.github/actions/run-monitored-tmpnet-cmd/action.yml +++ b/.github/actions/run-monitored-tmpnet-cmd/action.yml @@ -56,7 +56,7 @@ runs: shell: bash run: ${{ github.action_path }}/notify-metrics-availability.sh env: - GRAFANA_URL: https://grafana-experimental.avax-dev.network/d/kBQpRdWnk/avalanche-main-dashboard?orgId=1&refresh=10s&var-filter=is_ephemeral_node%7C%3D%7Cfalse&var-filter=gh_repo%7C%3D%7C${{ inputs.repository_owner }}%2F${{ inputs.repository_name }}&var-filter=gh_run_id%7C%3D%7C${{ inputs.run_id }}&var-filter=gh_run_attempt%7C%3D%7C${{ inputs.run_attempt }} + GRAFANA_URL: https://grafana-poc.avax-dev.network/d/kBQpRdWnk/avalanche-main-dashboard?orgId=1&refresh=10s&var-filter=is_ephemeral_node%7C%3D%7Cfalse&var-filter=gh_repo%7C%3D%7C${{ inputs.repository_owner }}%2F${{ inputs.repository_name }}&var-filter=gh_run_id%7C%3D%7C${{ inputs.run_id }}&var-filter=gh_run_attempt%7C%3D%7C${{ inputs.run_attempt }} GH_JOB_ID: ${{ inputs.job }} FILTER_BY_OWNER: ${{ inputs.filter_by_owner }} - name: Run command diff --git a/scripts/run_prometheus.sh b/scripts/run_prometheus.sh index 195222723107..dce9ef1e30cb 100755 --- a/scripts/run_prometheus.sh +++ b/scripts/run_prometheus.sh @@ -31,7 +31,7 @@ if pgrep --pidfile="${PIDFILE}" -f 'prometheus.*enable-feature=agent' &> /dev/nu exit 0 fi -PROMETHEUS_URL="${PROMETHEUS_URL:-https://prometheus-experimental.avax-dev.network}" +PROMETHEUS_URL="${PROMETHEUS_URL:-https://prometheus-poc.avax-dev.network}" if [[ -z "${PROMETHEUS_URL}" ]]; then echo "Please provide a value for PROMETHEUS_URL" exit 1 diff --git a/scripts/run_promtail.sh b/scripts/run_promtail.sh index 9b386d3d55f2..5811dcf06f2f 100755 --- a/scripts/run_promtail.sh +++ b/scripts/run_promtail.sh @@ -30,7 +30,7 @@ if pgrep --pidfile="${PIDFILE}" &> /dev/null; then exit 0 fi -LOKI_URL="${LOKI_URL:-https://loki-experimental.avax-dev.network}" +LOKI_URL="${LOKI_URL:-https://loki-poc.avax-dev.network}" if [[ -z "${LOKI_URL}" ]]; then echo "Please provide a value for LOKI_URL" exit 1 diff --git a/tests/fixture/tmpnet/README.md b/tests/fixture/tmpnet/README.md index 3f84e5c3acd7..e48deef3b34b 100644 --- a/tests/fixture/tmpnet/README.md +++ b/tests/fixture/tmpnet/README.md @@ -282,7 +282,7 @@ configured to scrape metrics from configured nodes and forward the metrics to a persistent prometheus instance. The script requires that the `PROMETHEUS_ID` and `PROMETHEUS_PASSWORD` env vars be set. By default the prometheus instance at -https://prometheus-experimental.avax-dev.network will be targeted and +https://prometheus-poc.avax-dev.network will be targeted and this can be overridden via the `PROMETHEUS_URL` env var. ### Log collection @@ -300,7 +300,7 @@ The `scripts/run_promtail.sh` script starts promtail configured to collect logs from configured nodes and forward the results to loki. The script requires that the `LOKI_ID` and `LOKI_PASSWORD` env vars be set. By default the loki instance at -https://loki-experimental.avax-dev.network will be targeted and this +https://loki-poc.avax-dev.network will be targeted and this can be overridden via the `LOKI_URL` env var. ### Labels @@ -336,7 +336,7 @@ https://docs.github.com/en/actions/learn-github-actions/contexts#github-context. #### Local networks When a network is started with tmpnet, a link to the [default grafana -instance](https://grafana-experimental.avax-dev.network) will be +instance](https://grafana-poc.avax-dev.network) will be emitted. The dashboards will only be populated if prometheus and promtail are running locally (as per previous sections) to collect metrics and logs. diff --git a/tests/fixture/tmpnet/network.go b/tests/fixture/tmpnet/network.go index 68b4a7173e00..3eec5cdf7a06 100644 --- a/tests/fixture/tmpnet/network.go +++ b/tests/fixture/tmpnet/network.go @@ -373,7 +373,7 @@ func (n *Network) StartNodes(ctx context.Context, w io.Writer, nodesToStart ...* return err } // Provide a link to the main dashboard filtered by the uuid and showing results from now till whenever the link is viewed - if _, err := fmt.Fprintf(w, "\nMetrics: https://grafana-experimental.avax-dev.network/d/kBQpRdWnk/avalanche-main-dashboard?&var-filter=network_uuid%%7C%%3D%%7C%s&var-filter=is_ephemeral_node%%7C%%3D%%7Cfalse&from=%d&to=now\n", n.UUID, startTime.UnixMilli()); err != nil { + if _, err := fmt.Fprintf(w, "\nMetrics: https://grafana-poc.avax-dev.network/d/kBQpRdWnk/avalanche-main-dashboard?&var-filter=network_uuid%%7C%%3D%%7C%s&var-filter=is_ephemeral_node%%7C%%3D%%7Cfalse&from=%d&to=now\n", n.UUID, startTime.UnixMilli()); err != nil { return err } From 5c67c8f4477f83cde7c10fa2b4be3d6f9bf35e76 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Wed, 21 Aug 2024 16:27:00 -0400 Subject: [PATCH 36/69] Add statetest to replace common test state initialization (#3319) --- vms/platformvm/block/builder/helpers_test.go | 39 ++------ vms/platformvm/block/executor/helpers_test.go | 48 +++------- .../block/executor/proposal_block_test.go | 2 +- vms/platformvm/state/state.go | 12 +-- vms/platformvm/state/state_test.go | 22 ++--- vms/platformvm/state/statetest/state.go | 90 +++++++++++++++++++ vms/platformvm/txs/executor/helpers_test.go | 45 +++------- .../validators/manager_benchmark_test.go | 38 ++------ vms/platformvm/vm.go | 3 +- vms/platformvm/vm_regression_test.go | 42 ++++----- 10 files changed, 162 insertions(+), 179 deletions(-) create mode 100644 vms/platformvm/state/statetest/state.go diff --git a/vms/platformvm/block/builder/helpers_test.go b/vms/platformvm/block/builder/helpers_test.go index 0ed61f930d01..1d7436485e17 100644 --- a/vms/platformvm/block/builder/helpers_test.go +++ b/vms/platformvm/block/builder/helpers_test.go @@ -15,7 +15,6 @@ import ( "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/codec/linearcodec" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/database/versiondb" @@ -43,6 +42,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/network" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" @@ -139,7 +139,13 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { //nolint:un res.fx = defaultFx(t, res.clk, res.ctx.Log, res.isBootstrapped.Get()) rewardsCalc := reward.NewCalculator(res.config.RewardConfig) - res.state = defaultState(t, res.config, res.ctx, res.baseDB, rewardsCalc) + res.state = statetest.New(t, statetest.Config{ + DB: res.baseDB, + Genesis: buildGenesisTest(t, res.ctx), + Validators: res.config.Validators, + Context: res.ctx, + Rewards: rewardsCalc, + }) res.uptimes = uptime.NewManager(res.state, res.clk) res.utxosVerifier = utxo.NewVerifier(res.ctx, res.clk, res.fx) @@ -263,35 +269,6 @@ func addSubnet(t *testing.T, env *environment) { require.NoError(env.state.Commit()) } -func defaultState( - t *testing.T, - cfg *config.Config, - ctx *snow.Context, - db database.Database, - rewards reward.Calculator, -) state.State { - require := require.New(t) - - execCfg, _ := config.GetExecutionConfig([]byte(`{}`)) - genesisBytes := buildGenesisTest(t, ctx) - state, err := state.New( - db, - genesisBytes, - prometheus.NewRegistry(), - cfg, - execCfg, - ctx, - metrics.Noop, - rewards, - ) - require.NoError(err) - - // persist and reload to init a bunch of in-memory stuff - state.SetHeight(0) - require.NoError(state.Commit()) - return state -} - func defaultConfig(f upgradetest.Fork) *config.Config { upgrades := upgradetest.GetConfigWithUpgradeTime(f, time.Time{}) // This package neglects fork ordering diff --git a/vms/platformvm/block/executor/helpers_test.go b/vms/platformvm/block/executor/helpers_test.go index 22305de07ac7..08b1d334d4df 100644 --- a/vms/platformvm/block/executor/helpers_test.go +++ b/vms/platformvm/block/executor/helpers_test.go @@ -17,7 +17,6 @@ import ( "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/codec/linearcodec" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/database/versiondb" @@ -43,6 +42,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" @@ -77,8 +77,7 @@ var ( avaxAssetID = ids.ID{'y', 'e', 'e', 't'} defaultTxFee = uint64(100) - genesisBlkID ids.ID - testSubnet1 *txs.Tx + testSubnet1 *txs.Tx // Node IDs of genesis validators. Initialized in init function genesisNodeIDs []ids.NodeID @@ -148,7 +147,14 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * rewardsCalc := reward.NewCalculator(res.config.RewardConfig) if ctrl == nil { - res.state = defaultState(res.config, res.ctx, res.baseDB, rewardsCalc) + res.state = statetest.New(t, statetest.Config{ + DB: res.baseDB, + Genesis: buildGenesisTest(res.ctx), + Validators: res.config.Validators, + Context: res.ctx, + Rewards: rewardsCalc, + }) + res.uptimes = uptime.NewManager(res.state, res.clk) res.utxosVerifier = utxo.NewVerifier(res.ctx, res.clk, res.fx) res.factory = txstest.NewWalletFactory( @@ -157,7 +163,6 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * res.state, ) } else { - genesisBlkID = ids.GenerateTestID() res.mockedState = state.NewMockState(ctrl) res.uptimes = uptime.NewManager(res.mockedState, res.clk) res.utxosVerifier = utxo.NewVerifier(res.ctx, res.clk, res.fx) @@ -168,7 +173,7 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * ) // setup expectations strictly needed for environment creation - res.mockedState.EXPECT().GetLastAccepted().Return(genesisBlkID).Times(1) + res.mockedState.EXPECT().GetLastAccepted().Return(ids.GenerateTestID()).Times(1) } res.backend = &executor.Backend{ @@ -292,37 +297,6 @@ func addSubnet(env *environment) { } } -func defaultState( - cfg *config.Config, - ctx *snow.Context, - db database.Database, - rewards reward.Calculator, -) state.State { - genesisBytes := buildGenesisTest(ctx) - execCfg, _ := config.GetExecutionConfig([]byte(`{}`)) - state, err := state.New( - db, - genesisBytes, - prometheus.NewRegistry(), - cfg, - execCfg, - ctx, - metrics.Noop, - rewards, - ) - if err != nil { - panic(err) - } - - // persist and reload to init a bunch of in-memory stuff - state.SetHeight(0) - if err := state.Commit(); err != nil { - panic(err) - } - genesisBlkID = state.GetLastAccepted() - return state -} - func defaultConfig(f upgradetest.Fork) *config.Config { upgrades := upgradetest.GetConfigWithUpgradeTime(f, time.Time{}) // This package neglects fork ordering diff --git a/vms/platformvm/block/executor/proposal_block_test.go b/vms/platformvm/block/executor/proposal_block_test.go index 0dbcb74c11d5..a7f38e28850c 100644 --- a/vms/platformvm/block/executor/proposal_block_test.go +++ b/vms/platformvm/block/executor/proposal_block_test.go @@ -148,7 +148,7 @@ func TestBanffProposalBlockTimeVerification(t *testing.T) { parentHeight := uint64(2022) banffParentBlk, err := block.NewApricotStandardBlock( - genesisBlkID, // does not matter + ids.GenerateTestID(), // does not matter parentHeight, nil, // txs do not matter in this test ) diff --git a/vms/platformvm/state/state.go b/vms/platformvm/state/state.go index 6923f2414e25..9002293f6511 100644 --- a/vms/platformvm/state/state.go +++ b/vms/platformvm/state/state.go @@ -26,6 +26,7 @@ import ( "github.com/ava-labs/avalanchego/snow/choices" "github.com/ava-labs/avalanchego/snow/uptime" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/hashing" @@ -285,7 +286,7 @@ type state struct { validators validators.Manager ctx *snow.Context - cfg *config.Config + upgrades upgrade.Config metrics metrics.Metrics rewards reward.Calculator @@ -452,7 +453,8 @@ func New( db database.Database, genesisBytes []byte, metricsReg prometheus.Registerer, - cfg *config.Config, + validators validators.Manager, + upgrades upgrade.Config, execCfg *config.ExecutionConfig, ctx *snow.Context, metrics metrics.Metrics, @@ -585,9 +587,9 @@ func New( s := &state{ validatorState: newValidatorState(), - validators: cfg.Validators, + validators: validators, ctx: ctx, - cfg: cfg, + upgrades: upgrades, metrics: metrics, rewards: rewards, baseDB: baseDB, @@ -1670,7 +1672,7 @@ func (s *state) initValidatorSets() error { func (s *state) write(updateValidators bool, height uint64) error { codecVersion := CodecVersion1 - if !s.cfg.UpgradeConfig.IsDurangoActivated(s.GetTimestamp()) { + if !s.upgrades.IsDurangoActivated(s.GetTimestamp()) { codecVersion = CodecVersion0 } diff --git a/vms/platformvm/state/state_test.go b/vms/platformvm/state/state_test.go index 21357874e434..2bd5798bc721 100644 --- a/vms/platformvm/state/state_test.go +++ b/vms/platformvm/state/state_test.go @@ -23,6 +23,7 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/choices" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/logging" @@ -50,9 +51,8 @@ func newTestState(t testing.TB, db database.Database) *state { db, genesistest.NewBytes(t), prometheus.NewRegistry(), - &config.Config{ - Validators: validators.NewManager(), - }, + validators.NewManager(), + upgradetest.GetConfig(upgradetest.Latest), &config.DefaultExecutionConfig, &snow.Context{ Log: logging.NoLog{}, @@ -152,7 +152,7 @@ func TestPersistStakers(t *testing.T) { r.Equal(staker, retrievedStaker) }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { - valsMap := s.cfg.Validators.GetMap(staker.SubnetID) + valsMap := s.validators.GetMap(staker.SubnetID) r.Contains(valsMap, staker.NodeID) r.Equal( &validators.GetValidatorOutput{ @@ -258,7 +258,7 @@ func TestPersistStakers(t *testing.T) { val, err := s.GetCurrentValidator(staker.SubnetID, staker.NodeID) r.NoError(err) - valsMap := s.cfg.Validators.GetMap(staker.SubnetID) + valsMap := s.validators.GetMap(staker.SubnetID) r.Contains(valsMap, staker.NodeID) valOut := valsMap[staker.NodeID] r.Equal(valOut.NodeID, staker.NodeID) @@ -313,7 +313,7 @@ func TestPersistStakers(t *testing.T) { }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { // pending validators are not showed in validators set - valsMap := s.cfg.Validators.GetMap(staker.SubnetID) + valsMap := s.validators.GetMap(staker.SubnetID) r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(r *require.Assertions, s *state, staker *Staker) { @@ -388,7 +388,7 @@ func TestPersistStakers(t *testing.T) { r.Equal(staker, retrievedDelegator) }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { - valsMap := s.cfg.Validators.GetMap(staker.SubnetID) + valsMap := s.validators.GetMap(staker.SubnetID) r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(*require.Assertions, *state, *Staker) {}, @@ -435,7 +435,7 @@ func TestPersistStakers(t *testing.T) { }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { // deleted validators are not showed in the validators set anymore - valsMap := s.cfg.Validators.GetMap(staker.SubnetID) + valsMap := s.validators.GetMap(staker.SubnetID) r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(r *require.Assertions, s *state, staker *Staker) { @@ -532,7 +532,7 @@ func TestPersistStakers(t *testing.T) { val, err := s.GetCurrentValidator(staker.SubnetID, staker.NodeID) r.NoError(err) - valsMap := s.cfg.Validators.GetMap(staker.SubnetID) + valsMap := s.validators.GetMap(staker.SubnetID) r.Contains(valsMap, staker.NodeID) valOut := valsMap[staker.NodeID] r.Equal(valOut.NodeID, staker.NodeID) @@ -589,7 +589,7 @@ func TestPersistStakers(t *testing.T) { r.ErrorIs(err, database.ErrNotFound) }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { - valsMap := s.cfg.Validators.GetMap(staker.SubnetID) + valsMap := s.validators.GetMap(staker.SubnetID) r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(r *require.Assertions, s *state, staker *Staker) { @@ -660,7 +660,7 @@ func TestPersistStakers(t *testing.T) { delIt.Release() }, checkValidatorsSet: func(r *require.Assertions, s *state, staker *Staker) { - valsMap := s.cfg.Validators.GetMap(staker.SubnetID) + valsMap := s.validators.GetMap(staker.SubnetID) r.NotContains(valsMap, staker.NodeID) }, checkValidatorUptimes: func(*require.Assertions, *state, *Staker) {}, diff --git a/vms/platformvm/state/statetest/state.go b/vms/platformvm/state/statetest/state.go new file mode 100644 index 000000000000..fbc71381ec51 --- /dev/null +++ b/vms/platformvm/state/statetest/state.go @@ -0,0 +1,90 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package statetest + +import ( + "testing" + "time" + + "github.com/prometheus/client_golang/prometheus" + "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/memdb" + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" + "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/utils/logging" + "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" + "github.com/ava-labs/avalanchego/vms/platformvm/metrics" + "github.com/ava-labs/avalanchego/vms/platformvm/reward" + "github.com/ava-labs/avalanchego/vms/platformvm/state" +) + +type Config struct { + DB database.Database + Genesis []byte + Registerer prometheus.Registerer + Validators validators.Manager + Upgrades upgrade.Config + ExecutionConfig config.ExecutionConfig + Context *snow.Context + Metrics metrics.Metrics + Rewards reward.Calculator +} + +func New(t testing.TB, c Config) state.State { + if c.DB == nil { + c.DB = memdb.New() + } + if len(c.Genesis) == 0 { + c.Genesis = genesistest.NewBytes(t) + } + if c.Registerer == nil { + c.Registerer = prometheus.NewRegistry() + } + if c.Upgrades == (upgrade.Config{}) { + c.Upgrades = upgradetest.GetConfig(upgradetest.Latest) + } + if c.ExecutionConfig == (config.ExecutionConfig{}) { + c.ExecutionConfig = config.DefaultExecutionConfig + } + if c.Context == nil { + c.Context = &snow.Context{ + NetworkID: constants.UnitTestID, + NodeID: ids.GenerateTestNodeID(), + Log: logging.NoLog{}, + } + } + if c.Metrics == nil { + c.Metrics = metrics.Noop + } + if c.Rewards == nil { + c.Rewards = reward.NewCalculator(reward.Config{ + MaxConsumptionRate: .12 * reward.PercentDenominator, + MinConsumptionRate: .1 * reward.PercentDenominator, + MintingPeriod: 365 * 24 * time.Hour, + SupplyCap: 720 * units.MegaAvax, + }) + } + + s, err := state.New( + c.DB, + c.Genesis, + c.Registerer, + c.Validators, + c.Upgrades, + &c.ExecutionConfig, + c.Context, + c.Metrics, + c.Rewards, + ) + require.NoError(t, err) + return s +} diff --git a/vms/platformvm/txs/executor/helpers_test.go b/vms/platformvm/txs/executor/helpers_test.go index 2342f2270d43..4005c32fddaa 100644 --- a/vms/platformvm/txs/executor/helpers_test.go +++ b/vms/platformvm/txs/executor/helpers_test.go @@ -10,14 +10,12 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/chains" "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/codec" "github.com/ava-labs/avalanchego/codec/linearcodec" - "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" @@ -38,9 +36,9 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/api" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/fx" - "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" @@ -133,7 +131,15 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { fx := defaultFx(clk, ctx.Log, isBootstrapped.Get()) rewards := reward.NewCalculator(config.RewardConfig) - baseState := defaultState(config, ctx, baseDB, rewards) + baseState := statetest.New(t, statetest.Config{ + DB: baseDB, + Genesis: buildGenesisTest(ctx), + Validators: config.Validators, + Upgrades: config.UpgradeConfig, + Context: ctx, + Rewards: rewards, + }) + lastAcceptedID = baseState.GetLastAccepted() uptimes := uptime.NewManager(baseState, clk) utxosVerifier := utxo.NewVerifier(ctx, clk, fx) @@ -235,37 +241,6 @@ func addSubnet(t *testing.T, env *environment) { require.NoError(env.state.Commit()) } -func defaultState( - cfg *config.Config, - ctx *snow.Context, - db database.Database, - rewards reward.Calculator, -) state.State { - genesisBytes := buildGenesisTest(ctx) - execCfg, _ := config.GetExecutionConfig(nil) - state, err := state.New( - db, - genesisBytes, - prometheus.NewRegistry(), - cfg, - execCfg, - ctx, - metrics.Noop, - rewards, - ) - if err != nil { - panic(err) - } - - // persist and reload to init a bunch of in-memory stuff - state.SetHeight(0) - if err := state.Commit(); err != nil { - panic(err) - } - lastAcceptedID = state.GetLastAccepted() - return state -} - func defaultConfig(f upgradetest.Fork) *config.Config { upgrades := upgradetest.GetConfigWithUpgradeTime( f, diff --git a/vms/platformvm/validators/manager_benchmark_test.go b/vms/platformvm/validators/manager_benchmark_test.go index 8215a54475a4..905bb8fc2a1d 100644 --- a/vms/platformvm/validators/manager_benchmark_test.go +++ b/vms/platformvm/validators/manager_benchmark_test.go @@ -14,7 +14,6 @@ import ( "github.com/ava-labs/avalanchego/database/leveldb" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" @@ -30,6 +29,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) @@ -99,35 +99,11 @@ func BenchmarkGetValidatorSet(b *testing.B) { require.NoError(err) vdrs := validators.NewManager() - - execConfig, err := config.GetExecutionConfig(nil) - require.NoError(err) - - metrics, err := metrics.New(prometheus.NewRegistry()) - require.NoError(err) - - s, err := state.New( - db, - genesisBytes, - prometheus.NewRegistry(), - &config.Config{ - Validators: vdrs, - }, - execConfig, - &snow.Context{ - NetworkID: constants.UnitTestID, - NodeID: ids.GenerateTestNodeID(), - Log: logging.NoLog{}, - }, - metrics, - reward.NewCalculator(reward.Config{ - MaxConsumptionRate: .12 * reward.PercentDenominator, - MinConsumptionRate: .10 * reward.PercentDenominator, - MintingPeriod: 365 * 24 * time.Hour, - SupplyCap: 720 * units.MegaAvax, - }), - ) - require.NoError(err) + s := statetest.New(b, statetest.Config{ + DB: db, + Genesis: genesisBytes, + Validators: vdrs, + }) m := NewManager( logging.NoLog{}, @@ -135,7 +111,7 @@ func BenchmarkGetValidatorSet(b *testing.B) { Validators: vdrs, }, s, - metrics, + metrics.Noop, new(mockable.Clock), ) diff --git a/vms/platformvm/vm.go b/vms/platformvm/vm.go index d6b97a441270..ba86190e953b 100644 --- a/vms/platformvm/vm.go +++ b/vms/platformvm/vm.go @@ -139,7 +139,8 @@ func (vm *VM) Initialize( vm.db, genesisBytes, registerer, - &vm.Config, + vm.Config.Validators, + vm.Config.UpgradeConfig, execConfig, vm.ctx, vm.metrics, diff --git a/vms/platformvm/vm_regression_test.go b/vms/platformvm/vm_regression_test.go index 3146a8372518..851117920bcf 100644 --- a/vms/platformvm/vm_regression_test.go +++ b/vms/platformvm/vm_regression_test.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" "golang.org/x/sync/errgroup" @@ -36,10 +35,9 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" - "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" - "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" @@ -764,18 +762,13 @@ func TestRejectedStateRegressionInvalidValidatorTimestamp(t *testing.T) { // Force a reload of the state from the database. vm.Config.Validators = validators.NewManager() - execCfg, _ := config.GetExecutionConfig(nil) - newState, err := state.New( - vm.db, - nil, - prometheus.NewRegistry(), - &vm.Config, - execCfg, - vm.ctx, - metrics.Noop, - reward.NewCalculator(vm.Config.RewardConfig), - ) - require.NoError(err) + newState := statetest.New(t, statetest.Config{ + DB: vm.db, + Validators: vm.Config.Validators, + Upgrades: vm.Config.UpgradeConfig, + Context: vm.ctx, + Rewards: reward.NewCalculator(vm.Config.RewardConfig), + }) // Verify that new validator is now in the current validator set. { @@ -1067,18 +1060,13 @@ func TestRejectedStateRegressionInvalidValidatorReward(t *testing.T) { // Force a reload of the state from the database. vm.Config.Validators = validators.NewManager() - execCfg, _ := config.GetExecutionConfig(nil) - newState, err := state.New( - vm.db, - nil, - prometheus.NewRegistry(), - &vm.Config, - execCfg, - vm.ctx, - metrics.Noop, - reward.NewCalculator(vm.Config.RewardConfig), - ) - require.NoError(err) + newState := statetest.New(t, statetest.Config{ + DB: vm.db, + Validators: vm.Config.Validators, + Upgrades: vm.Config.UpgradeConfig, + Context: vm.ctx, + Rewards: reward.NewCalculator(vm.Config.RewardConfig), + }) // Verify that validators are in the current validator set with the correct // reward calculated. From fccd19ee0bc09cfc4d9c56fee85f7e7b1524f050 Mon Sep 17 00:00:00 2001 From: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> Date: Wed, 21 Aug 2024 19:53:36 -0400 Subject: [PATCH 37/69] Rename `components/fee` pkg to `components/gas` (#3321) --- config/config.go | 29 ++- config/flags.go | 18 +- genesis/genesis_fuji.go | 27 +- genesis/genesis_local.go | 27 +- genesis/genesis_mainnet.go | 27 +- genesis/params.go | 11 +- vms/components/{fee => gas}/config.go | 12 +- vms/components/{fee => gas}/dimensions.go | 2 +- .../{fee => gas}/dimensions_test.go | 2 +- vms/components/{fee => gas}/gas.go | 18 +- vms/components/{fee => gas}/gas_test.go | 26 +- vms/components/{fee => gas}/state.go | 18 +- vms/components/{fee => gas}/state_test.go | 50 ++-- .../block/executor/proposal_block_test.go | 6 +- .../block/executor/standard_block_test.go | 6 +- .../block/executor/verifier_test.go | 12 +- vms/platformvm/client.go | 12 +- vms/platformvm/config/config.go | 9 +- vms/platformvm/service.go | 14 +- vms/platformvm/service_test.go | 18 +- vms/platformvm/state/diff.go | 8 +- vms/platformvm/state/diff_test.go | 16 +- vms/platformvm/state/mock_state.go | 20 +- vms/platformvm/state/state.go | 24 +- vms/platformvm/state/state_test.go | 14 +- vms/platformvm/txs/fee/calculator_test.go | 134 +++++----- vms/platformvm/txs/fee/complexity.go | 236 +++++++++--------- vms/platformvm/txs/fee/complexity_test.go | 226 ++++++++--------- vms/platformvm/txs/fee/dynamic_calculator.go | 10 +- vms/platformvm/vm_test.go | 26 +- wallet/chain/p/builder/builder.go | 111 ++++---- wallet/chain/p/builder/context.go | 15 +- wallet/chain/p/builder_test.go | 25 +- 33 files changed, 600 insertions(+), 609 deletions(-) rename vms/components/{fee => gas}/config.go (73%) rename vms/components/{fee => gas}/dimensions.go (99%) rename vms/components/{fee => gas}/dimensions_test.go (99%) rename vms/components/{fee => gas}/gas.go (91%) rename vms/components/{fee => gas}/gas_test.go (87%) rename vms/components/{fee => gas}/state.go (78%) rename vms/components/{fee => gas}/state_test.go (74%) diff --git a/config/config.go b/config/config.go index 4c98b6a47fda..4d7937086073 100644 --- a/config/config.go +++ b/config/config.go @@ -45,11 +45,10 @@ import ( "github.com/ava-labs/avalanchego/utils/storage" "github.com/ava-labs/avalanchego/utils/timer" "github.com/ava-labs/avalanchego/version" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/reward" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/proposervm" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) const ( @@ -769,7 +768,7 @@ func getTxFeeConfig(v *viper.Viper, networkID uint32) genesis.TxFeeConfig { if networkID != constants.MainnetID && networkID != constants.FujiID { return genesis.TxFeeConfig{ CreateAssetTxFee: v.GetUint64(CreateAssetTxFeeKey), - StaticFeeConfig: txfee.StaticConfig{ + StaticFeeConfig: fee.StaticConfig{ TxFee: v.GetUint64(TxFeeKey), CreateSubnetTxFee: v.GetUint64(CreateSubnetTxFeeKey), TransformSubnetTxFee: v.GetUint64(TransformSubnetTxFeeKey), @@ -779,18 +778,18 @@ func getTxFeeConfig(v *viper.Viper, networkID uint32) genesis.TxFeeConfig { AddSubnetValidatorFee: v.GetUint64(AddSubnetValidatorFeeKey), AddSubnetDelegatorFee: v.GetUint64(AddSubnetDelegatorFeeKey), }, - DynamicFeeConfig: feecomponent.Config{ - Weights: feecomponent.Dimensions{ - feecomponent.Bandwidth: v.GetUint64(DynamicFeesBandwidthWeightKey), - feecomponent.DBRead: v.GetUint64(DynamicFeesDBReadWeightKey), - feecomponent.DBWrite: v.GetUint64(DynamicFeesDBWriteWeightKey), - feecomponent.Compute: v.GetUint64(DynamicFeesComputeWeightKey), + DynamicFeeConfig: gas.Config{ + Weights: gas.Dimensions{ + gas.Bandwidth: v.GetUint64(DynamicFeesBandwidthWeightKey), + gas.DBRead: v.GetUint64(DynamicFeesDBReadWeightKey), + gas.DBWrite: v.GetUint64(DynamicFeesDBWriteWeightKey), + gas.Compute: v.GetUint64(DynamicFeesComputeWeightKey), }, - MaxGasCapacity: feecomponent.Gas(v.GetUint64(DynamicFeesMaxGasCapacityKey)), - MaxGasPerSecond: feecomponent.Gas(v.GetUint64(DynamicFeesMaxGasPerSecondKey)), - TargetGasPerSecond: feecomponent.Gas(v.GetUint64(DynamicFeesTargetGasPerSecondKey)), - MinGasPrice: feecomponent.GasPrice(v.GetUint64(DynamicFeesMinGasPriceKey)), - ExcessConversionConstant: feecomponent.Gas(v.GetUint64(DynamicFeesExcessConversionConstantKey)), + MaxCapacity: gas.Gas(v.GetUint64(DynamicFeesMaxGasCapacityKey)), + MaxPerSecond: gas.Gas(v.GetUint64(DynamicFeesMaxGasPerSecondKey)), + TargetPerSecond: gas.Gas(v.GetUint64(DynamicFeesTargetGasPerSecondKey)), + MinPrice: gas.Price(v.GetUint64(DynamicFeesMinGasPriceKey)), + ExcessConversionConstant: gas.Gas(v.GetUint64(DynamicFeesExcessConversionConstantKey)), }, } } diff --git a/config/flags.go b/config/flags.go index 6351161e69a2..9f092c563b32 100644 --- a/config/flags.go +++ b/config/flags.go @@ -24,7 +24,7 @@ import ( "github.com/ava-labs/avalanchego/utils/dynamicip" "github.com/ava-labs/avalanchego/utils/ulimit" "github.com/ava-labs/avalanchego/utils/units" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" ) const ( @@ -106,14 +106,14 @@ func addNodeFlags(fs *pflag.FlagSet) { // AVAX fees: // Dynamic fees: - fs.Uint64(DynamicFeesBandwidthWeightKey, genesis.LocalParams.DynamicFeeConfig.Weights[fee.Bandwidth], "Complexity multiplier used to convert Bandwidth into Gas") - fs.Uint64(DynamicFeesDBReadWeightKey, genesis.LocalParams.DynamicFeeConfig.Weights[fee.DBRead], "Complexity multiplier used to convert DB Reads into Gas") - fs.Uint64(DynamicFeesDBWriteWeightKey, genesis.LocalParams.DynamicFeeConfig.Weights[fee.DBWrite], "Complexity multiplier used to convert DB Writes into Gas") - fs.Uint64(DynamicFeesComputeWeightKey, genesis.LocalParams.DynamicFeeConfig.Weights[fee.Compute], "Complexity multiplier used to convert Compute into Gas") - fs.Uint64(DynamicFeesMaxGasCapacityKey, uint64(genesis.LocalParams.DynamicFeeConfig.MaxGasCapacity), "Maximum amount of Gas the chain is allowed to store for future use") - fs.Uint64(DynamicFeesMaxGasPerSecondKey, uint64(genesis.LocalParams.DynamicFeeConfig.MaxGasPerSecond), "Rate at which Gas is stored for future use") - fs.Uint64(DynamicFeesTargetGasPerSecondKey, uint64(genesis.LocalParams.DynamicFeeConfig.TargetGasPerSecond), "Target rate of Gas usage") - fs.Uint64(DynamicFeesMinGasPriceKey, uint64(genesis.LocalParams.DynamicFeeConfig.MinGasPrice), "Minimum Gas price") + fs.Uint64(DynamicFeesBandwidthWeightKey, genesis.LocalParams.DynamicFeeConfig.Weights[gas.Bandwidth], "Complexity multiplier used to convert Bandwidth into Gas") + fs.Uint64(DynamicFeesDBReadWeightKey, genesis.LocalParams.DynamicFeeConfig.Weights[gas.DBRead], "Complexity multiplier used to convert DB Reads into Gas") + fs.Uint64(DynamicFeesDBWriteWeightKey, genesis.LocalParams.DynamicFeeConfig.Weights[gas.DBWrite], "Complexity multiplier used to convert DB Writes into Gas") + fs.Uint64(DynamicFeesComputeWeightKey, genesis.LocalParams.DynamicFeeConfig.Weights[gas.Compute], "Complexity multiplier used to convert Compute into Gas") + fs.Uint64(DynamicFeesMaxGasCapacityKey, uint64(genesis.LocalParams.DynamicFeeConfig.MaxCapacity), "Maximum amount of Gas the chain is allowed to store for future use") + fs.Uint64(DynamicFeesMaxGasPerSecondKey, uint64(genesis.LocalParams.DynamicFeeConfig.MaxPerSecond), "Rate at which Gas is stored for future use") + fs.Uint64(DynamicFeesTargetGasPerSecondKey, uint64(genesis.LocalParams.DynamicFeeConfig.TargetPerSecond), "Target rate of Gas usage") + fs.Uint64(DynamicFeesMinGasPriceKey, uint64(genesis.LocalParams.DynamicFeeConfig.MinPrice), "Minimum Gas price") fs.Uint64(DynamicFeesExcessConversionConstantKey, uint64(genesis.LocalParams.DynamicFeeConfig.ExcessConversionConstant), "Constant to convert excess Gas to the Gas price") // Static fees: fs.Uint64(TxFeeKey, genesis.LocalParams.StaticFeeConfig.TxFee, "Transaction fee, in nAVAX") diff --git a/genesis/genesis_fuji.go b/genesis/genesis_fuji.go index a267765e03ae..3d59bb725756 100644 --- a/genesis/genesis_fuji.go +++ b/genesis/genesis_fuji.go @@ -9,10 +9,9 @@ import ( _ "embed" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/reward" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) var ( @@ -23,7 +22,7 @@ var ( FujiParams = Params{ TxFeeConfig: TxFeeConfig{ CreateAssetTxFee: 10 * units.MilliAvax, - StaticFeeConfig: txfee.StaticConfig{ + StaticFeeConfig: fee.StaticConfig{ TxFee: units.MilliAvax, CreateSubnetTxFee: 100 * units.MilliAvax, TransformSubnetTxFee: 1 * units.Avax, @@ -34,17 +33,17 @@ var ( AddSubnetDelegatorFee: units.MilliAvax, }, // TODO: Set these values to something more reasonable - DynamicFeeConfig: feecomponent.Config{ - Weights: feecomponent.Dimensions{ - feecomponent.Bandwidth: 1, - feecomponent.DBRead: 1, - feecomponent.DBWrite: 1, - feecomponent.Compute: 1, + DynamicFeeConfig: gas.Config{ + Weights: gas.Dimensions{ + gas.Bandwidth: 1, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 1, }, - MaxGasCapacity: 1_000_000, - MaxGasPerSecond: 1_000, - TargetGasPerSecond: 500, - MinGasPrice: 1, + MaxCapacity: 1_000_000, + MaxPerSecond: 1_000, + TargetPerSecond: 500, + MinPrice: 1, ExcessConversionConstant: 5_000, }, }, diff --git a/genesis/genesis_local.go b/genesis/genesis_local.go index f5bbf5c4c7b7..d3ce77aec961 100644 --- a/genesis/genesis_local.go +++ b/genesis/genesis_local.go @@ -12,10 +12,9 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/reward" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) // PrivateKey-vmRQiZeXEXYMyJhEiqdC2z5JhuDbxL8ix9UVvjgMu2Er1NepE => P-local1g65uqn6t77p656w64023nh8nd9updzmxyymev2 @@ -41,7 +40,7 @@ var ( LocalParams = Params{ TxFeeConfig: TxFeeConfig{ CreateAssetTxFee: units.MilliAvax, - StaticFeeConfig: txfee.StaticConfig{ + StaticFeeConfig: fee.StaticConfig{ TxFee: units.MilliAvax, CreateSubnetTxFee: 100 * units.MilliAvax, TransformSubnetTxFee: 100 * units.MilliAvax, @@ -52,17 +51,17 @@ var ( AddSubnetDelegatorFee: units.MilliAvax, }, // TODO: Set these values to something more reasonable - DynamicFeeConfig: feecomponent.Config{ - Weights: feecomponent.Dimensions{ - feecomponent.Bandwidth: 1, - feecomponent.DBRead: 1, - feecomponent.DBWrite: 1, - feecomponent.Compute: 1, + DynamicFeeConfig: gas.Config{ + Weights: gas.Dimensions{ + gas.Bandwidth: 1, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 1, }, - MaxGasCapacity: 1_000_000, - MaxGasPerSecond: 1_000, - TargetGasPerSecond: 500, - MinGasPrice: 1, + MaxCapacity: 1_000_000, + MaxPerSecond: 1_000, + TargetPerSecond: 500, + MinPrice: 1, ExcessConversionConstant: 5_000, }, }, diff --git a/genesis/genesis_mainnet.go b/genesis/genesis_mainnet.go index 790a8e007630..8d4a6d4f777f 100644 --- a/genesis/genesis_mainnet.go +++ b/genesis/genesis_mainnet.go @@ -9,10 +9,9 @@ import ( _ "embed" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/reward" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) var ( @@ -23,7 +22,7 @@ var ( MainnetParams = Params{ TxFeeConfig: TxFeeConfig{ CreateAssetTxFee: 10 * units.MilliAvax, - StaticFeeConfig: txfee.StaticConfig{ + StaticFeeConfig: fee.StaticConfig{ TxFee: units.MilliAvax, CreateSubnetTxFee: 1 * units.Avax, TransformSubnetTxFee: 10 * units.Avax, @@ -34,17 +33,17 @@ var ( AddSubnetDelegatorFee: units.MilliAvax, }, // TODO: Set these values to something more reasonable - DynamicFeeConfig: feecomponent.Config{ - Weights: feecomponent.Dimensions{ - feecomponent.Bandwidth: 1, - feecomponent.DBRead: 1, - feecomponent.DBWrite: 1, - feecomponent.Compute: 1, + DynamicFeeConfig: gas.Config{ + Weights: gas.Dimensions{ + gas.Bandwidth: 1, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 1, }, - MaxGasCapacity: 1_000_000, - MaxGasPerSecond: 1_000, - TargetGasPerSecond: 500, - MinGasPrice: 1, + MaxCapacity: 1_000_000, + MaxPerSecond: 1_000, + TargetPerSecond: 500, + MinPrice: 1, ExcessConversionConstant: 5_000, }, }, diff --git a/genesis/params.go b/genesis/params.go index 01eb7067d816..e51af8b81c1b 100644 --- a/genesis/params.go +++ b/genesis/params.go @@ -7,10 +7,9 @@ import ( "time" "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/reward" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) type StakingConfig struct { @@ -37,9 +36,9 @@ type StakingConfig struct { } type TxFeeConfig struct { - CreateAssetTxFee uint64 `json:"createAssetTxFee"` - StaticFeeConfig txfee.StaticConfig `json:"staticFeeConfig"` - DynamicFeeConfig feecomponent.Config `json:"dynamicFeeConfig"` + CreateAssetTxFee uint64 `json:"createAssetTxFee"` + StaticFeeConfig fee.StaticConfig `json:"staticFeeConfig"` + DynamicFeeConfig gas.Config `json:"dynamicFeeConfig"` } type Params struct { diff --git a/vms/components/fee/config.go b/vms/components/gas/config.go similarity index 73% rename from vms/components/fee/config.go rename to vms/components/gas/config.go index ca56f872b627..2aa65423fc93 100644 --- a/vms/components/fee/config.go +++ b/vms/components/gas/config.go @@ -1,22 +1,22 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -// The fee package implements dynamic gas pricing specified in ACP-103: +// The gas package implements dynamic gas pricing specified in ACP-103: // https://github.com/avalanche-foundation/ACPs/tree/main/ACPs/103-dynamic-fees -package fee +package gas type Config struct { // Weights to merge fee dimensions into a single gas value. Weights Dimensions `json:"weights"` // Maximum amount of gas the chain is allowed to store for future use. - MaxGasCapacity Gas `json:"maxGasCapacity"` + MaxCapacity Gas `json:"maxCapacity"` // Maximum amount of gas the chain is allowed to consume per second. - MaxGasPerSecond Gas `json:"maxGasPerSecond"` + MaxPerSecond Gas `json:"maxPerSecond"` // Target amount of gas the chain should consume per second to keep the fees // stable. - TargetGasPerSecond Gas `json:"targetGasPerSecond"` + TargetPerSecond Gas `json:"targetPerSecond"` // Minimum price per unit of gas. - MinGasPrice GasPrice `json:"minGasPrice"` + MinPrice Price `json:"minPrice"` // Constant used to convert excess gas to a gas price. ExcessConversionConstant Gas `json:"excessConversionConstant"` } diff --git a/vms/components/fee/dimensions.go b/vms/components/gas/dimensions.go similarity index 99% rename from vms/components/fee/dimensions.go rename to vms/components/gas/dimensions.go index b9e0a3449e0f..1ec85077d7f3 100644 --- a/vms/components/fee/dimensions.go +++ b/vms/components/gas/dimensions.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package fee +package gas import "github.com/ava-labs/avalanchego/utils/math" diff --git a/vms/components/fee/dimensions_test.go b/vms/components/gas/dimensions_test.go similarity index 99% rename from vms/components/fee/dimensions_test.go rename to vms/components/gas/dimensions_test.go index 0ca31a5818d6..666ee6337ac1 100644 --- a/vms/components/fee/dimensions_test.go +++ b/vms/components/gas/dimensions_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package fee +package gas import ( "math" diff --git a/vms/components/fee/gas.go b/vms/components/gas/gas.go similarity index 91% rename from vms/components/fee/gas.go rename to vms/components/gas/gas.go index 0c4a905ce783..dc03bcd70768 100644 --- a/vms/components/fee/gas.go +++ b/vms/components/gas/gas.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package fee +package gas import ( "math" @@ -14,14 +14,14 @@ import ( var maxUint64 = new(uint256.Int).SetUint64(math.MaxUint64) type ( - Gas uint64 - GasPrice uint64 + Gas uint64 + Price uint64 ) // Cost converts the gas to nAVAX based on the price. // // If overflow would occur, an error is returned. -func (g Gas) Cost(price GasPrice) (uint64, error) { +func (g Gas) Cost(price Price) (uint64, error) { return safemath.Mul(uint64(g), uint64(price)) } @@ -55,7 +55,7 @@ func (g Gas) SubPerSecond(gasPerSecond Gas, seconds uint64) Gas { return Gas(totalGas) } -// CalculateGasPrice returns the gas price given the minimum gas price, the +// CalculatePrice returns the gas price given the minimum gas price, the // excess gas, and the excess conversion constant. // // It is defined as an approximation of: @@ -82,11 +82,11 @@ func (g Gas) SubPerSecond(gasPerSecond Gas, seconds uint64) Gas { // This function does not perform any memory allocations. // //nolint:dupword // The python is copied from the EIP-4844 specification -func CalculateGasPrice( - minPrice GasPrice, +func CalculatePrice( + minPrice Price, excess Gas, excessConversionConstant Gas, -) GasPrice { +) Price { var ( numerator uint256.Int denominator uint256.Int @@ -117,5 +117,5 @@ func CalculateGasPrice( i.AddUint64(&i, 1) } - return GasPrice(output.Div(&output, &denominator).Uint64()) + return Price(output.Div(&output, &denominator).Uint64()) } diff --git a/vms/components/fee/gas_test.go b/vms/components/gas/gas_test.go similarity index 87% rename from vms/components/fee/gas_test.go rename to vms/components/gas/gas_test.go index b9e2dc99edfe..edc90d9197e6 100644 --- a/vms/components/fee/gas_test.go +++ b/vms/components/gas/gas_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package fee +package gas import ( "fmt" @@ -11,11 +11,11 @@ import ( "github.com/stretchr/testify/require" ) -var calculateGasPriceTests = []struct { - minPrice GasPrice +var calculatePriceTests = []struct { + minPrice Price excess Gas excessConversionConstant Gas - expected GasPrice + expected Price }{ { minPrice: 1, @@ -83,9 +83,9 @@ func Test_Gas_Cost(t *testing.T) { require := require.New(t) const ( - gas Gas = 40 - price GasPrice = 100 - expected uint64 = 4000 + gas Gas = 40 + price Price = 100 + expected uint64 = 4000 ) actual, err := gas.Cost(price) require.NoError(err) @@ -172,20 +172,20 @@ func Test_Gas_SubPerSecond(t *testing.T) { } } -func Test_CalculateGasPrice(t *testing.T) { - for _, test := range calculateGasPriceTests { +func Test_CalculatePrice(t *testing.T) { + for _, test := range calculatePriceTests { t.Run(fmt.Sprintf("%d*e^(%d/%d)=%d", test.minPrice, test.excess, test.excessConversionConstant, test.expected), func(t *testing.T) { - actual := CalculateGasPrice(test.minPrice, test.excess, test.excessConversionConstant) + actual := CalculatePrice(test.minPrice, test.excess, test.excessConversionConstant) require.Equal(t, test.expected, actual) }) } } -func Benchmark_CalculateGasPrice(b *testing.B) { - for _, test := range calculateGasPriceTests { +func Benchmark_CalculatePrice(b *testing.B) { + for _, test := range calculatePriceTests { b.Run(fmt.Sprintf("%d*e^(%d/%d)=%d", test.minPrice, test.excess, test.excessConversionConstant, test.expected), func(b *testing.B) { for i := 0; i < b.N; i++ { - CalculateGasPrice(test.minPrice, test.excess, test.excessConversionConstant) + CalculatePrice(test.minPrice, test.excess, test.excessConversionConstant) } }) } diff --git a/vms/components/fee/state.go b/vms/components/gas/state.go similarity index 78% rename from vms/components/fee/state.go rename to vms/components/gas/state.go index da72374f6e8f..e3c1c3eb3603 100644 --- a/vms/components/fee/state.go +++ b/vms/components/gas/state.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package fee +package gas import ( "errors" @@ -17,23 +17,23 @@ type State struct { Excess Gas `serialize:"true" json:"excess"` } -// AdvanceTime adds maxGasPerSecond to capacity and subtracts targetGasPerSecond +// AdvanceTime adds maxPerSecond to capacity and subtracts targetPerSecond // from excess over the provided duration. // -// Capacity is capped at maxGasCapacity. +// Capacity is capped at maxCapacity. // Excess to be removed is capped at excess. func (s State) AdvanceTime( - maxGasCapacity Gas, - maxGasPerSecond Gas, - targetGasPerSecond Gas, + maxCapacity Gas, + maxPerSecond Gas, + targetPerSecond Gas, duration uint64, ) State { return State{ Capacity: min( - s.Capacity.AddPerSecond(maxGasPerSecond, duration), - maxGasCapacity, + s.Capacity.AddPerSecond(maxPerSecond, duration), + maxCapacity, ), - Excess: s.Excess.SubPerSecond(targetGasPerSecond, duration), + Excess: s.Excess.SubPerSecond(targetPerSecond, duration), } } diff --git a/vms/components/fee/state_test.go b/vms/components/gas/state_test.go similarity index 74% rename from vms/components/fee/state_test.go rename to vms/components/gas/state_test.go index 2a48f33a4cc0..841c2cd14066 100644 --- a/vms/components/fee/state_test.go +++ b/vms/components/gas/state_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package fee +package gas import ( "math" @@ -12,13 +12,13 @@ import ( func Test_State_AdvanceTime(t *testing.T) { tests := []struct { - name string - initial State - maxGasCapacity Gas - maxGasPerSecond Gas - targetGasPerSecond Gas - duration uint64 - expected State + name string + initial State + maxCapacity Gas + maxPerSecond Gas + targetPerSecond Gas + duration uint64 + expected State }{ { name: "cap capacity", @@ -26,10 +26,10 @@ func Test_State_AdvanceTime(t *testing.T) { Capacity: 10, Excess: 0, }, - maxGasCapacity: 20, - maxGasPerSecond: 10, - targetGasPerSecond: 0, - duration: 2, + maxCapacity: 20, + maxPerSecond: 10, + targetPerSecond: 0, + duration: 2, expected: State{ Capacity: 20, Excess: 0, @@ -41,10 +41,10 @@ func Test_State_AdvanceTime(t *testing.T) { Capacity: 10, Excess: 0, }, - maxGasCapacity: 30, - maxGasPerSecond: 10, - targetGasPerSecond: 0, - duration: 1, + maxCapacity: 30, + maxPerSecond: 10, + targetPerSecond: 0, + duration: 1, expected: State{ Capacity: 20, Excess: 0, @@ -56,10 +56,10 @@ func Test_State_AdvanceTime(t *testing.T) { Capacity: 10, Excess: 10, }, - maxGasCapacity: 20, - maxGasPerSecond: 10, - targetGasPerSecond: 10, - duration: 2, + maxCapacity: 20, + maxPerSecond: 10, + targetPerSecond: 10, + duration: 2, expected: State{ Capacity: 20, Excess: 0, @@ -71,10 +71,10 @@ func Test_State_AdvanceTime(t *testing.T) { Capacity: 10, Excess: 10, }, - maxGasCapacity: 20, - maxGasPerSecond: 10, - targetGasPerSecond: 5, - duration: 1, + maxCapacity: 20, + maxPerSecond: 10, + targetPerSecond: 5, + duration: 1, expected: State{ Capacity: 20, Excess: 5, @@ -83,7 +83,7 @@ func Test_State_AdvanceTime(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - actual := test.initial.AdvanceTime(test.maxGasCapacity, test.maxGasPerSecond, test.targetGasPerSecond, test.duration) + actual := test.initial.AdvanceTime(test.maxCapacity, test.maxPerSecond, test.targetPerSecond, test.duration) require.Equal(t, test.expected, actual) }) } diff --git a/vms/platformvm/block/executor/proposal_block_test.go b/vms/platformvm/block/executor/proposal_block_test.go index a7f38e28850c..59141140b04a 100644 --- a/vms/platformvm/block/executor/proposal_block_test.go +++ b/vms/platformvm/block/executor/proposal_block_test.go @@ -21,7 +21,7 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" @@ -88,7 +88,7 @@ func TestApricotProposalBlockTimeVerification(t *testing.T) { // setup state to validate proposal block transaction onParentAccept.EXPECT().GetTimestamp().Return(chainTime).AnyTimes() - onParentAccept.EXPECT().GetFeeState().Return(fee.State{}).AnyTimes() + onParentAccept.EXPECT().GetFeeState().Return(gas.State{}).AnyTimes() currentStakersIt := state.NewMockStakerIterator(ctrl) currentStakersIt.EXPECT().Next().Return(true) @@ -159,7 +159,7 @@ func TestBanffProposalBlockTimeVerification(t *testing.T) { chainTime := parentTime onParentAccept := state.NewMockDiff(ctrl) onParentAccept.EXPECT().GetTimestamp().Return(parentTime).AnyTimes() - onParentAccept.EXPECT().GetFeeState().Return(fee.State{}).AnyTimes() + onParentAccept.EXPECT().GetFeeState().Return(gas.State{}).AnyTimes() onParentAccept.EXPECT().GetCurrentSupply(constants.PrimaryNetworkID).Return(uint64(1000), nil).AnyTimes() env.blkManager.(*manager).blkIDToState[parentID] = &blockState{ diff --git a/vms/platformvm/block/executor/standard_block_test.go b/vms/platformvm/block/executor/standard_block_test.go index 3dc1f999e789..45f297dc48f7 100644 --- a/vms/platformvm/block/executor/standard_block_test.go +++ b/vms/platformvm/block/executor/standard_block_test.go @@ -18,7 +18,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -57,7 +57,7 @@ func TestApricotStandardBlockTimeVerification(t *testing.T) { chainTime := env.clk.Time().Truncate(time.Second) onParentAccept.EXPECT().GetTimestamp().Return(chainTime).AnyTimes() - onParentAccept.EXPECT().GetFeeState().Return(fee.State{}).AnyTimes() + onParentAccept.EXPECT().GetFeeState().Return(gas.State{}).AnyTimes() // wrong height apricotChildBlk, err := block.NewApricotStandardBlock( @@ -134,7 +134,7 @@ func TestBanffStandardBlockTimeVerification(t *testing.T) { onParentAccept.EXPECT().GetPendingStakerIterator().Return(pendingIt, nil).AnyTimes() onParentAccept.EXPECT().GetTimestamp().Return(chainTime).AnyTimes() - onParentAccept.EXPECT().GetFeeState().Return(fee.State{}).AnyTimes() + onParentAccept.EXPECT().GetFeeState().Return(gas.State{}).AnyTimes() txID := ids.GenerateTestID() utxo := &avax.UTXO{ diff --git a/vms/platformvm/block/executor/verifier_test.go b/vms/platformvm/block/executor/verifier_test.go index 535e7d70f37e..0d8baaca106f 100644 --- a/vms/platformvm/block/executor/verifier_test.go +++ b/vms/platformvm/block/executor/verifier_test.go @@ -19,7 +19,7 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/timer/mockable" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" @@ -42,7 +42,7 @@ func TestVerifierVisitProposalBlock(t *testing.T) { timestamp := time.Now() // One call for each of onCommitState and onAbortState. parentOnAcceptState.EXPECT().GetTimestamp().Return(timestamp).Times(2) - parentOnAcceptState.EXPECT().GetFeeState().Return(fee.State{}).Times(2) + parentOnAcceptState.EXPECT().GetFeeState().Return(gas.State{}).Times(2) backend := &backend{ lastAccepted: parentID, @@ -273,7 +273,7 @@ func TestVerifierVisitStandardBlock(t *testing.T) { // Set expectations for dependencies. timestamp := time.Now() parentState.EXPECT().GetTimestamp().Return(timestamp).Times(1) - parentState.EXPECT().GetFeeState().Return(fee.State{}).Times(1) + parentState.EXPECT().GetFeeState().Return(gas.State{}).Times(1) parentStatelessBlk.EXPECT().Height().Return(uint64(1)).Times(1) mempool.EXPECT().Remove(apricotBlk.Txs()).Times(1) @@ -534,7 +534,7 @@ func TestBanffAbortBlockTimestampChecks(t *testing.T) { parentTime := defaultGenesisTime s.EXPECT().GetLastAccepted().Return(parentID).Times(3) s.EXPECT().GetTimestamp().Return(parentTime).Times(3) - s.EXPECT().GetFeeState().Return(fee.State{}).Times(3) + s.EXPECT().GetFeeState().Return(gas.State{}).Times(3) onDecisionState, err := state.NewDiff(parentID, backend) require.NoError(err) @@ -631,7 +631,7 @@ func TestBanffCommitBlockTimestampChecks(t *testing.T) { parentTime := defaultGenesisTime s.EXPECT().GetLastAccepted().Return(parentID).Times(3) s.EXPECT().GetTimestamp().Return(parentTime).Times(3) - s.EXPECT().GetFeeState().Return(fee.State{}).Times(3) + s.EXPECT().GetFeeState().Return(gas.State{}).Times(3) onDecisionState, err := state.NewDiff(parentID, backend) require.NoError(err) @@ -746,7 +746,7 @@ func TestVerifierVisitStandardBlockWithDuplicateInputs(t *testing.T) { timestamp := time.Now() parentStatelessBlk.EXPECT().Height().Return(uint64(1)).Times(1) parentState.EXPECT().GetTimestamp().Return(timestamp).Times(1) - parentState.EXPECT().GetFeeState().Return(fee.State{}).Times(1) + parentState.EXPECT().GetFeeState().Return(gas.State{}).Times(1) parentStatelessBlk.EXPECT().Parent().Return(grandParentID).Times(1) err = verifier.ApricotStandardBlock(blk) diff --git a/vms/platformvm/client.go b/vms/platformvm/client.go index d8880d5b204e..e5338fbae3f8 100644 --- a/vms/platformvm/client.go +++ b/vms/platformvm/client.go @@ -16,7 +16,7 @@ import ( "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/rpc" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -125,9 +125,9 @@ type Client interface { // GetBlockByHeight returns the block at the given [height]. GetBlockByHeight(ctx context.Context, height uint64, options ...rpc.Option) ([]byte, error) // GetFeeConfig returns the dynamic fee config of the chain. - GetFeeConfig(ctx context.Context, options ...rpc.Option) (*fee.Config, error) + GetFeeConfig(ctx context.Context, options ...rpc.Option) (*gas.Config, error) // GetFeeState returns the current fee state of the chain. - GetFeeState(ctx context.Context, options ...rpc.Option) (fee.State, fee.GasPrice, time.Time, error) + GetFeeState(ctx context.Context, options ...rpc.Option) (gas.State, gas.Price, time.Time, error) } // Client implementation for interacting with the P Chain endpoint @@ -522,13 +522,13 @@ func (c *client) GetBlockByHeight(ctx context.Context, height uint64, options .. return formatting.Decode(res.Encoding, res.Block) } -func (c *client) GetFeeConfig(ctx context.Context, options ...rpc.Option) (*fee.Config, error) { - res := &fee.Config{} +func (c *client) GetFeeConfig(ctx context.Context, options ...rpc.Option) (*gas.Config, error) { + res := &gas.Config{} err := c.requester.SendRequest(ctx, "platform.getFeeConfig", struct{}{}, res, options...) return res, err } -func (c *client) GetFeeState(ctx context.Context, options ...rpc.Option) (fee.State, fee.GasPrice, time.Time, error) { +func (c *client) GetFeeState(ctx context.Context, options ...rpc.Option) (gas.State, gas.Price, time.Time, error) { res := &GetFeeStateReply{} err := c.requester.SendRequest(ctx, "platform.getFeeState", struct{}{}, res, options...) return res.State, res.Price, res.Time, err diff --git a/vms/platformvm/config/config.go b/vms/platformvm/config/config.go index 4cb6c981feac..406285f0e59c 100644 --- a/vms/platformvm/config/config.go +++ b/vms/platformvm/config/config.go @@ -13,11 +13,10 @@ import ( "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/set" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/txs" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) // Struct collecting all foundational parameters of PlatformVM @@ -35,10 +34,10 @@ type Config struct { // Static fees are active before the E-upgrade CreateAssetTxFee uint64 // Override for CreateSubnet and CreateChain before AP3 - StaticFeeConfig txfee.StaticConfig + StaticFeeConfig fee.StaticConfig // Dynamic fees are active after the E-upgrade - DynamicFeeConfig feecomponent.Config + DynamicFeeConfig gas.Config // Provides access to the uptime manager as a thread safe data structure UptimeLockedCalculator uptime.LockedCalculator diff --git a/vms/platformvm/service.go b/vms/platformvm/service.go index 600b03231f8f..411919ecaa8d 100644 --- a/vms/platformvm/service.go +++ b/vms/platformvm/service.go @@ -28,7 +28,7 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/components/keystore" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/reward" @@ -1830,7 +1830,7 @@ func (s *Service) GetBlockByHeight(_ *http.Request, args *api.GetBlockByHeightAr } // GetFeeConfig returns the dynamic fee config of the chain. -func (s *Service) GetFeeConfig(_ *http.Request, _ *struct{}, reply *fee.Config) error { +func (s *Service) GetFeeConfig(_ *http.Request, _ *struct{}, reply *gas.Config) error { s.vm.ctx.Log.Debug("API called", zap.String("service", "platform"), zap.String("method", "getFeeConfig"), @@ -1847,9 +1847,9 @@ func (s *Service) GetFeeConfig(_ *http.Request, _ *struct{}, reply *fee.Config) } type GetFeeStateReply struct { - fee.State - Price fee.GasPrice `json:"price"` - Time time.Time `json:"timestamp"` + gas.State + Price gas.Price `json:"price"` + Time time.Time `json:"timestamp"` } // GetFeeState returns the current fee state of the chain. @@ -1863,8 +1863,8 @@ func (s *Service) GetFeeState(_ *http.Request, _ *struct{}, reply *GetFeeStateRe defer s.vm.ctx.Lock.Unlock() reply.State = s.vm.state.GetFeeState() - reply.Price = fee.CalculateGasPrice( - s.vm.DynamicFeeConfig.MinGasPrice, + reply.Price = gas.CalculatePrice( + s.vm.DynamicFeeConfig.MinPrice, reply.State.Excess, s.vm.DynamicFeeConfig.ExcessConversionConstant, ) diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index 3c89f712adf7..a7043f37cc57 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -34,7 +34,7 @@ import ( "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -1114,12 +1114,12 @@ func TestGetFeeConfig(t *testing.T) { tests := []struct { name string etnaTime time.Time - expected fee.Config + expected gas.Config }{ { name: "pre-etna", etnaTime: time.Now().Add(time.Hour), - expected: fee.Config{}, + expected: gas.Config{}, }, { name: "post-etna", @@ -1134,7 +1134,7 @@ func TestGetFeeConfig(t *testing.T) { service, _, _ := defaultService(t) service.vm.Config.UpgradeConfig.EtnaTime = test.etnaTime - var reply fee.Config + var reply gas.Config require.NoError(service.GetFeeConfig(nil, nil, &reply)) require.Equal(test.expected, reply) }) @@ -1148,15 +1148,15 @@ func FuzzGetFeeState(f *testing.F) { service, _, _ := defaultService(t) var ( - expectedState = fee.State{ - Capacity: fee.Gas(capacity), - Excess: fee.Gas(excess), + expectedState = gas.State{ + Capacity: gas.Gas(capacity), + Excess: gas.Gas(excess), } expectedTime = time.Now() expectedReply = GetFeeStateReply{ State: expectedState, - Price: fee.CalculateGasPrice( - defaultDynamicFeeConfig.MinGasPrice, + Price: gas.CalculatePrice( + defaultDynamicFeeConfig.MinPrice, expectedState.Excess, defaultDynamicFeeConfig.ExcessConversionConstant, ), diff --git a/vms/platformvm/state/diff.go b/vms/platformvm/state/diff.go index faf395624778..8c530c75f045 100644 --- a/vms/platformvm/state/diff.go +++ b/vms/platformvm/state/diff.go @@ -11,7 +11,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" @@ -35,7 +35,7 @@ type diff struct { stateVersions Versions timestamp time.Time - feeState fee.State + feeState gas.State // Subnet ID --> supply of native asset of the subnet currentSupply map[ids.ID]uint64 @@ -103,11 +103,11 @@ func (d *diff) SetTimestamp(timestamp time.Time) { d.timestamp = timestamp } -func (d *diff) GetFeeState() fee.State { +func (d *diff) GetFeeState() gas.State { return d.feeState } -func (d *diff) SetFeeState(feeState fee.State) { +func (d *diff) SetFeeState(feeState gas.State) { d.feeState = feeState } diff --git a/vms/platformvm/state/diff_test.go b/vms/platformvm/state/diff_test.go index 2b2945591e5b..edb8e627e5b3 100644 --- a/vms/platformvm/state/diff_test.go +++ b/vms/platformvm/state/diff_test.go @@ -16,7 +16,7 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" @@ -54,7 +54,7 @@ func TestDiffFeeState(t *testing.T) { require.NoError(err) initialFeeState := state.GetFeeState() - newFeeState := fee.State{ + newFeeState := gas.State{ Capacity: initialFeeState.Capacity + 1, Excess: initialFeeState.Excess + 1, } @@ -100,7 +100,7 @@ func TestDiffCurrentValidator(t *testing.T) { state := NewMockState(ctrl) // Called in NewDiffOn state.EXPECT().GetTimestamp().Return(time.Now()).Times(1) - state.EXPECT().GetFeeState().Return(fee.State{}).Times(1) + state.EXPECT().GetFeeState().Return(gas.State{}).Times(1) d, err := NewDiffOn(state) require.NoError(err) @@ -134,7 +134,7 @@ func TestDiffPendingValidator(t *testing.T) { state := NewMockState(ctrl) // Called in NewDiffOn state.EXPECT().GetTimestamp().Return(time.Now()).Times(1) - state.EXPECT().GetFeeState().Return(fee.State{}).Times(1) + state.EXPECT().GetFeeState().Return(gas.State{}).Times(1) d, err := NewDiffOn(state) require.NoError(err) @@ -174,7 +174,7 @@ func TestDiffCurrentDelegator(t *testing.T) { state := NewMockState(ctrl) // Called in NewDiffOn state.EXPECT().GetTimestamp().Return(time.Now()).Times(1) - state.EXPECT().GetFeeState().Return(fee.State{}).Times(1) + state.EXPECT().GetFeeState().Return(gas.State{}).Times(1) d, err := NewDiffOn(state) require.NoError(err) @@ -220,7 +220,7 @@ func TestDiffPendingDelegator(t *testing.T) { state := NewMockState(ctrl) // Called in NewDiffOn state.EXPECT().GetTimestamp().Return(time.Now()).Times(1) - state.EXPECT().GetFeeState().Return(fee.State{}).Times(1) + state.EXPECT().GetFeeState().Return(gas.State{}).Times(1) d, err := NewDiffOn(state) require.NoError(err) @@ -360,7 +360,7 @@ func TestDiffTx(t *testing.T) { state := NewMockState(ctrl) // Called in NewDiffOn state.EXPECT().GetTimestamp().Return(time.Now()).Times(1) - state.EXPECT().GetFeeState().Return(fee.State{}).Times(1) + state.EXPECT().GetFeeState().Return(gas.State{}).Times(1) d, err := NewDiffOn(state) require.NoError(err) @@ -457,7 +457,7 @@ func TestDiffUTXO(t *testing.T) { state := NewMockState(ctrl) // Called in NewDiffOn state.EXPECT().GetTimestamp().Return(time.Now()).Times(1) - state.EXPECT().GetFeeState().Return(fee.State{}).Times(1) + state.EXPECT().GetFeeState().Return(gas.State{}).Times(1) d, err := NewDiffOn(state) require.NoError(err) diff --git a/vms/platformvm/state/mock_state.go b/vms/platformvm/state/mock_state.go index caa1c12a5817..f6540df730dc 100644 --- a/vms/platformvm/state/mock_state.go +++ b/vms/platformvm/state/mock_state.go @@ -20,7 +20,7 @@ import ( validators "github.com/ava-labs/avalanchego/snow/validators" logging "github.com/ava-labs/avalanchego/utils/logging" avax "github.com/ava-labs/avalanchego/vms/components/avax" - fee "github.com/ava-labs/avalanchego/vms/components/fee" + gas "github.com/ava-labs/avalanchego/vms/components/gas" block "github.com/ava-labs/avalanchego/vms/platformvm/block" fx "github.com/ava-labs/avalanchego/vms/platformvm/fx" status "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -259,10 +259,10 @@ func (mr *MockChainMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call } // GetFeeState mocks base method. -func (m *MockChain) GetFeeState() fee.State { +func (m *MockChain) GetFeeState() gas.State { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetFeeState") - ret0, _ := ret[0].(fee.State) + ret0, _ := ret[0].(gas.State) return ret0 } @@ -483,7 +483,7 @@ func (mr *MockChainMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomoc } // SetFeeState mocks base method. -func (m *MockChain) SetFeeState(arg0 fee.State) { +func (m *MockChain) SetFeeState(arg0 gas.State) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetFeeState", arg0) } @@ -775,10 +775,10 @@ func (mr *MockDiffMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call } // GetFeeState mocks base method. -func (m *MockDiff) GetFeeState() fee.State { +func (m *MockDiff) GetFeeState() gas.State { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetFeeState") - ret0, _ := ret[0].(fee.State) + ret0, _ := ret[0].(gas.State) return ret0 } @@ -999,7 +999,7 @@ func (mr *MockDiffMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomock } // SetFeeState mocks base method. -func (m *MockDiff) SetFeeState(arg0 fee.State) { +func (m *MockDiff) SetFeeState(arg0 gas.State) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetFeeState", arg0) } @@ -1416,10 +1416,10 @@ func (mr *MockStateMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call } // GetFeeState mocks base method. -func (m *MockState) GetFeeState() fee.State { +func (m *MockState) GetFeeState() gas.State { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetFeeState") - ret0, _ := ret[0].(fee.State) + ret0, _ := ret[0].(gas.State) return ret0 } @@ -1744,7 +1744,7 @@ func (mr *MockStateMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomoc } // SetFeeState mocks base method. -func (m *MockState) SetFeeState(arg0 fee.State) { +func (m *MockState) SetFeeState(arg0 gas.State) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetFeeState", arg0) } diff --git a/vms/platformvm/state/state.go b/vms/platformvm/state/state.go index 9002293f6511..952ffac01145 100644 --- a/vms/platformvm/state/state.go +++ b/vms/platformvm/state/state.go @@ -34,7 +34,7 @@ import ( "github.com/ava-labs/avalanchego/utils/timer" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/fx" @@ -102,8 +102,8 @@ type Chain interface { GetTimestamp() time.Time SetTimestamp(tm time.Time) - GetFeeState() fee.State - SetFeeState(f fee.State) + GetFeeState() gas.State + SetFeeState(f gas.State) GetCurrentSupply(subnetID ids.ID) (uint64, error) SetCurrentSupply(subnetID ids.ID, cs uint64) @@ -368,7 +368,7 @@ type state struct { // The persisted fields represent the current database value timestamp, persistedTimestamp time.Time - feeState, persistedFeeState fee.State + feeState, persistedFeeState gas.State currentSupply, persistedCurrentSupply uint64 // [lastAccepted] is the most recently accepted block. lastAccepted, persistedLastAccepted ids.ID @@ -1040,11 +1040,11 @@ func (s *state) SetTimestamp(tm time.Time) { s.timestamp = tm } -func (s *state) GetFeeState() fee.State { +func (s *state) GetFeeState() gas.State { return s.feeState } -func (s *state) SetFeeState(feeState fee.State) { +func (s *state) SetFeeState(feeState gas.State) { s.feeState = feeState } @@ -2526,7 +2526,7 @@ func isInitialized(db database.KeyValueReader) (bool, error) { return db.Has(InitializedKey) } -func putFeeState(db database.KeyValueWriter, feeState fee.State) error { +func putFeeState(db database.KeyValueWriter, feeState gas.State) error { feeStateBytes, err := block.GenesisCodec.Marshal(block.CodecVersion, feeState) if err != nil { return err @@ -2534,18 +2534,18 @@ func putFeeState(db database.KeyValueWriter, feeState fee.State) error { return db.Put(FeeStateKey, feeStateBytes) } -func getFeeState(db database.KeyValueReader) (fee.State, error) { +func getFeeState(db database.KeyValueReader) (gas.State, error) { feeStateBytes, err := db.Get(FeeStateKey) if err == database.ErrNotFound { - return fee.State{}, nil + return gas.State{}, nil } if err != nil { - return fee.State{}, err + return gas.State{}, err } - var feeState fee.State + var feeState gas.State if _, err := block.GenesisCodec.Unmarshal(feeStateBytes, &feeState); err != nil { - return fee.State{}, err + return gas.State{}, err } return feeState, nil } diff --git a/vms/platformvm/state/state_test.go b/vms/platformvm/state/state_test.go index 2bd5798bc721..fcfd02dfa1ce 100644 --- a/vms/platformvm/state/state_test.go +++ b/vms/platformvm/state/state_test.go @@ -30,7 +30,7 @@ import ( "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/fx" @@ -1450,7 +1450,7 @@ func TestStateFeeStateCommitAndLoad(t *testing.T) { db := memdb.New() s := newTestState(t, db) - expectedFeeState := fee.State{ + expectedFeeState := gas.State{ Capacity: 1, Excess: 2, } @@ -1484,12 +1484,12 @@ func TestPutAndGetFeeState(t *testing.T) { db := memdb.New() defaultFeeState, err := getFeeState(db) require.NoError(err) - require.Equal(fee.State{}, defaultFeeState) + require.Equal(gas.State{}, defaultFeeState) //nolint:gosec // This does not require a secure random number generator - expectedFeeState := fee.State{ - Capacity: fee.Gas(rand.Uint64()), - Excess: fee.Gas(rand.Uint64()), + expectedFeeState := gas.State{ + Capacity: gas.Gas(rand.Uint64()), + Excess: gas.Gas(rand.Uint64()), } require.NoError(putFeeState(db, expectedFeeState)) @@ -1542,7 +1542,7 @@ func TestGetFeeStateErrors(t *testing.T) { require.NoError(db.Put(FeeStateKey, test.value)) actualState, err := getFeeState(db) - require.Equal(fee.State{}, actualState) + require.Equal(gas.State{}, actualState) require.ErrorIs(err, test.expectedErr) }) } diff --git a/vms/platformvm/txs/fee/calculator_test.go b/vms/platformvm/txs/fee/calculator_test.go index 0e318bc6c93d..843f20d13e9d 100644 --- a/vms/platformvm/txs/fee/calculator_test.go +++ b/vms/platformvm/txs/fee/calculator_test.go @@ -5,7 +5,7 @@ package fee import ( "github.com/ava-labs/avalanchego/utils/units" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" ) const testDynamicPrice = 100 @@ -21,11 +21,11 @@ var ( AddSubnetValidatorFee: 7 * units.Avax, AddSubnetDelegatorFee: 8 * units.Avax, } - testDynamicWeights = fee.Dimensions{ - fee.Bandwidth: 1, - fee.DBRead: 200, - fee.DBWrite: 300, - fee.Compute: 0, // TODO: Populate + testDynamicWeights = gas.Dimensions{ + gas.Bandwidth: 1, + gas.DBRead: 200, + gas.DBWrite: 300, + gas.Compute: 0, // TODO: Populate } // TODO: Rather than hardcoding transactions, consider implementing and @@ -35,7 +35,7 @@ var ( tx string expectedStaticFee uint64 expectedStaticFeeErr error - expectedComplexity fee.Dimensions + expectedComplexity gas.Dimensions expectedComplexityErr error expectedDynamicFee uint64 expectedDynamicFeeErr error @@ -72,11 +72,11 @@ var ( name: "AddPermissionlessValidatorTx for primary network", tx: "00000000001900003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db0000000700238520ba8b1e00000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c00000001043c91e9d508169329034e2a68110427a311f945efc53ed3f3493d335b393fd100000000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000005002386f263d53e00000000010000000000000000c582872c37c81efa2c94ea347af49cdc23a830aa00000000669ae35f0000000066b692df000001d1a94a200000000000000000000000000000000000000000000000000000000000000000000000001ca3783a891cb41cadbfcf456da149f30e7af972677a162b984bef0779f254baac51ec042df1781d1295df80fb41c801269731fc6c25e1e5940dc3cb8509e30348fa712742cfdc83678acc9f95908eb98b89b28802fb559b4a2a6ff3216707c07f0ceb0b45a95f4f9a9540bbd3331d8ab4f233bffa4abb97fad9d59a1695f31b92a2b89e365facf7ab8c30de7c4a496d1e00000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000007000001d1a94a2000000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000b000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000b000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0007a12000000001000000090000000135f122f90bcece0d6c43e07fed1829578a23bc1734f8a4b46203f9f192ea1aec7526f3dca8fddec7418988615e6543012452bae1544275aae435313ec006ec9000", expectedStaticFee: testStaticConfig.AddPrimaryNetworkValidatorFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 691, // The length of the tx in bytes - fee.DBRead: IntrinsicAddPermissionlessValidatorTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicAddPermissionlessValidatorTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + 2*intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 691, // The length of the tx in bytes + gas.DBRead: IntrinsicAddPermissionlessValidatorTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicAddPermissionlessValidatorTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + 2*intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 229_100, }, @@ -84,11 +84,11 @@ var ( name: "AddPermissionlessValidatorTx for subnet", tx: "000000000019000030390000000000000000000000000000000000000000000000000000000000000000000000022f6399f3e626fe1e75f9daa5e726cb64b7bfec0b6e6d8930eaa9dfa336edca7a000000070000000000006091000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29cdbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db0000000700238520ba6c9980000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c00000002038b42b73d3dc695c76ca12f966e97fe0681b1200f9a5e28d088720a18ea23c9000000002f6399f3e626fe1e75f9daa5e726cb64b7bfec0b6e6d8930eaa9dfa336edca7a00000005000000000000609b0000000100000000a378b74b3293a9d885bd9961f2cc2e1b3364d393c9be875964f2bd614214572c00000000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db0000000500238520ba7bdbc0000000010000000000000000c582872c37c81efa2c94ea347af49cdc23a830aa0000000066a57a160000000066b7ef16000000000000000a97ea88082100491617204ed70c19fc1a2fce4474bee962904359d0b59e84c1240000001b000000012f6399f3e626fe1e75f9daa5e726cb64b7bfec0b6e6d8930eaa9dfa336edca7a00000007000000000000000a000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000b000000000000000000000000000000000000000b00000000000000000000000000000000000f4240000000020000000900000001593fc20f88a8ce0b3470b0bb103e5f7e09f65023b6515d36660da53f9a15dedc1037ee27a8c4a27c24e20ad3b0ab4bd1ff3a02a6fcc2cbe04282bfe9902c9ae6000000000900000001593fc20f88a8ce0b3470b0bb103e5f7e09f65023b6515d36660da53f9a15dedc1037ee27a8c4a27c24e20ad3b0ab4bd1ff3a02a6fcc2cbe04282bfe9902c9ae600", expectedStaticFee: testStaticConfig.AddSubnetValidatorFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 748, // The length of the tx in bytes - fee.DBRead: IntrinsicAddPermissionlessValidatorTxComplexities[fee.DBRead] + 2*intrinsicInputDBRead, - fee.DBWrite: IntrinsicAddPermissionlessValidatorTxComplexities[fee.DBWrite] + 2*intrinsicInputDBWrite + 3*intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 748, // The length of the tx in bytes + gas.DBRead: IntrinsicAddPermissionlessValidatorTxComplexities[gas.DBRead] + 2*intrinsicInputDBRead, + gas.DBWrite: IntrinsicAddPermissionlessValidatorTxComplexities[gas.DBWrite] + 2*intrinsicInputDBWrite + 3*intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 314_800, }, @@ -96,11 +96,11 @@ var ( name: "AddPermissionlessDelegatorTx for primary network", tx: "00000000001a00003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000070023834f1140fe00000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c000000017d199179744b3b82d0071c83c2fb7dd6b95a2cdbe9dde295e0ae4f8c2287370300000000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db0000000500238520ba8b1e00000000010000000000000000c582872c37c81efa2c94ea347af49cdc23a830aa00000000669ae6080000000066ad5b08000001d1a94a2000000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000007000001d1a94a2000000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000b000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000100000009000000012261556f74a29f02ffc2725a567db2c81f75d0892525dbebaa1cf8650534cc70061123533a9553184cb02d899943ff0bf0b39c77b173c133854bc7c8bc7ab9a400", expectedStaticFee: testStaticConfig.AddPrimaryNetworkDelegatorFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 499, // The length of the tx in bytes - fee.DBRead: IntrinsicAddPermissionlessDelegatorTxComplexities[fee.DBRead] + 1*intrinsicInputDBRead, - fee.DBWrite: IntrinsicAddPermissionlessDelegatorTxComplexities[fee.DBWrite] + 1*intrinsicInputDBWrite + 2*intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 499, // The length of the tx in bytes + gas.DBRead: IntrinsicAddPermissionlessDelegatorTxComplexities[gas.DBRead] + 1*intrinsicInputDBRead, + gas.DBWrite: IntrinsicAddPermissionlessDelegatorTxComplexities[gas.DBWrite] + 1*intrinsicInputDBWrite + 2*intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 209_900, }, @@ -108,11 +108,11 @@ var ( name: "AddPermissionlessDelegatorTx for subnet", tx: "00000000001a000030390000000000000000000000000000000000000000000000000000000000000000000000022f6399f3e626fe1e75f9daa5e726cb64b7bfec0b6e6d8930eaa9dfa336edca7a000000070000000000006087000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29cdbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db0000000700470c1336195b80000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c000000029494c80361884942e4292c3531e8e790fcf7561e74404ded27eab8634e3fb30f000000002f6399f3e626fe1e75f9daa5e726cb64b7bfec0b6e6d8930eaa9dfa336edca7a00000005000000000000609100000001000000009494c80361884942e4292c3531e8e790fcf7561e74404ded27eab8634e3fb30f00000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db0000000500470c1336289dc0000000010000000000000000c582872c37c81efa2c94ea347af49cdc23a830aa0000000066a57c1d0000000066b7f11d000000000000000a97ea88082100491617204ed70c19fc1a2fce4474bee962904359d0b59e84c124000000012f6399f3e626fe1e75f9daa5e726cb64b7bfec0b6e6d8930eaa9dfa336edca7a00000007000000000000000a000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000b00000000000000000000000000000000000000020000000900000001764190e2405fef72fce0d355e3dcc58a9f5621e583ae718cb2c23b55957995d1206d0b5efcc3cef99815e17a4b2cccd700147a759b7279a131745b237659666a000000000900000001764190e2405fef72fce0d355e3dcc58a9f5621e583ae718cb2c23b55957995d1206d0b5efcc3cef99815e17a4b2cccd700147a759b7279a131745b237659666a00", expectedStaticFee: testStaticConfig.AddSubnetDelegatorFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 720, // The length of the tx in bytes - fee.DBRead: IntrinsicAddPermissionlessDelegatorTxComplexities[fee.DBRead] + 2*intrinsicInputDBRead, - fee.DBWrite: IntrinsicAddPermissionlessDelegatorTxComplexities[fee.DBWrite] + 2*intrinsicInputDBWrite + 3*intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 720, // The length of the tx in bytes + gas.DBRead: IntrinsicAddPermissionlessDelegatorTxComplexities[gas.DBRead] + 2*intrinsicInputDBRead, + gas.DBWrite: IntrinsicAddPermissionlessDelegatorTxComplexities[gas.DBWrite] + 2*intrinsicInputDBWrite + 3*intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 312_000, }, @@ -120,11 +120,11 @@ var ( name: "AddSubnetValidatorTx", tx: "00000000000d00003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000070023834f1131bbc0000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000138f94d1a0514eaabdaf4c52cad8d62b26cee61eaa951f5b75a5e57c2ee3793c800000000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000050023834f1140fe00000000010000000000000000c582872c37c81efa2c94ea347af49cdc23a830aa00000000669ae7c90000000066ad5cc9000000000000c13797ea88082100491617204ed70c19fc1a2fce4474bee962904359d0b59e84c1240000000a00000001000000000000000200000009000000012127130d37877fb1ec4b2374ef72571d49cd7b0319a3769e5da19041a138166c10b1a5c07cf5ccf0419066cbe3bab9827cf29f9fa6213ebdadf19d4849501eb60000000009000000012127130d37877fb1ec4b2374ef72571d49cd7b0319a3769e5da19041a138166c10b1a5c07cf5ccf0419066cbe3bab9827cf29f9fa6213ebdadf19d4849501eb600", expectedStaticFee: testStaticConfig.AddSubnetValidatorFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 460, // The length of the tx in bytes - fee.DBRead: IntrinsicAddSubnetValidatorTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicAddSubnetValidatorTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 460, // The length of the tx in bytes + gas.DBRead: IntrinsicAddSubnetValidatorTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicAddSubnetValidatorTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 196_000, }, @@ -132,11 +132,11 @@ var ( name: "BaseTx", tx: "00000000002200003039000000000000000000000000000000000000000000000000000000000000000000000002dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000007000000003b9aca00000000000000000100000002000000024a177205df5c29929d06db9d941f83d5ea985de3e902a9a86640bfdb1cd0e36c0cc982b83e5765fadbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000070023834ed587af80000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c00000001fa4ff39749d44f29563ed9da03193d4a19ef419da4ce326594817ca266fda5ed00000000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000050023834f1131bbc00000000100000000000000000000000100000009000000014a7b54c63dd25a532b5fe5045b6d0e1db876e067422f12c9c327333c2c792d9273405ac8bbbc2cce549bbd3d0f9274242085ee257adfdb859b0f8d55bdd16fb000", expectedStaticFee: testStaticConfig.TxFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 399, // The length of the tx in bytes - fee.DBRead: IntrinsicBaseTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicBaseTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + 2*intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 399, // The length of the tx in bytes + gas.DBRead: IntrinsicBaseTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicBaseTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + 2*intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 149_900, }, @@ -144,11 +144,11 @@ var ( name: "CreateChainTx", tx: "00000000000f00003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000007002386f263d53e00000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000197ea88082100491617204ed70c19fc1a2fce4474bee962904359d0b59e84c12400000000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000005002386f269cb1f0000000001000000000000000097ea88082100491617204ed70c19fc1a2fce4474bee962904359d0b59e84c12400096c65742074686572657873766d00000000000000000000000000000000000000000000000000000000000000000000002a000000000000669ae21e000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29cffffffffffffffff0000000a0000000100000000000000020000000900000001cf8104877b1a59b472f4f34d360c0e4f38e92c5fa334215430d0b99cf78eae8f621b6daf0b0f5c3a58a9497601f978698a1e5545d1873db8f2f38ecb7496c2f8010000000900000001cf8104877b1a59b472f4f34d360c0e4f38e92c5fa334215430d0b99cf78eae8f621b6daf0b0f5c3a58a9497601f978698a1e5545d1873db8f2f38ecb7496c2f801", expectedStaticFee: testStaticConfig.CreateBlockchainTxFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 509, // The length of the tx in bytes - fee.DBRead: IntrinsicCreateChainTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicCreateChainTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 509, // The length of the tx in bytes + gas.DBRead: IntrinsicCreateChainTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicCreateChainTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 180_900, }, @@ -156,11 +156,11 @@ var ( name: "CreateSubnetTx", tx: "00000000001000003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000007002386f269cb1f00000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c00000001000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000005002386f26fc100000000000100000000000000000000000b000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c000000010000000900000001b3c905e7227e619bd6b98c164a8b2b4a8ce89ac5142bbb1c42b139df2d17fd777c4c76eae66cef3de90800e567407945f58d918978f734f8ca4eda6923c78eb201", expectedStaticFee: testStaticConfig.CreateSubnetTxFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 339, // The length of the tx in bytes - fee.DBRead: IntrinsicCreateSubnetTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicCreateSubnetTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 339, // The length of the tx in bytes + gas.DBRead: IntrinsicCreateSubnetTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicCreateSubnetTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 143_900, }, @@ -168,11 +168,11 @@ var ( name: "ExportTx", tx: "00000000001200003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000070023834e99dda340000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c00000001f62c03574790b6a31a988f90c3e91c50fdd6f5d93baf200057463021ff23ec5c00000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000050023834ed587af800000000100000000000000009d0775f450604bd2fbc49ce0c5c1c6dfeb2dc2acb8c92c26eeae6e6df4502b1900000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000007000000003b9aca00000000000000000100000002000000024a177205df5c29929d06db9d941f83d5ea985de3e902a9a86640bfdb1cd0e36c0cc982b83e5765fa000000010000000900000001129a07c92045e0b9d0a203fcb5b53db7890fabce1397ff6a2ad16c98ef0151891ae72949d240122abf37b1206b95e05ff171df164a98e6bdf2384432eac2c30200", expectedStaticFee: testStaticConfig.TxFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 435, // The length of the tx in bytes - fee.DBRead: IntrinsicExportTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicExportTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + 2*intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 435, // The length of the tx in bytes + gas.DBRead: IntrinsicExportTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicExportTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + 2*intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 153_500, }, @@ -180,11 +180,11 @@ var ( name: "ImportTx", tx: "00000000001100003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000007000000003b8b87c0000000000000000100000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c0000000000000000d891ad56056d9c01f18f43f58b5c784ad07a4a49cf3d1f11623804b5cba2c6bf0000000163684415710a7d65f4ccb095edff59f897106b94d38937fc60e3ffc29892833b00000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db00000005000000003b9aca00000000010000000000000001000000090000000148ea12cb0950e47d852b99765208f5a811d3c8a47fa7b23fd524bd970019d157029f973abb91c31a146752ef8178434deb331db24c8dca5e61c961e6ac2f3b6700", expectedStaticFee: testStaticConfig.TxFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 335, // The length of the tx in bytes - fee.DBRead: IntrinsicImportTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicImportTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 335, // The length of the tx in bytes + gas.DBRead: IntrinsicImportTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicImportTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 113_500, }, @@ -192,11 +192,11 @@ var ( name: "RemoveSubnetValidatorTx", tx: "00000000001700003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000070023834e99ce6100000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c00000001cd4569cfd044d50636fa597c700710403b3b52d3b75c30c542a111cc52c911ec00000000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000050023834e99dda340000000010000000000000000c582872c37c81efa2c94ea347af49cdc23a830aa97ea88082100491617204ed70c19fc1a2fce4474bee962904359d0b59e84c1240000000a0000000100000000000000020000000900000001673ee3e5a3a1221935274e8ff5c45b27ebe570e9731948e393a8ebef6a15391c189a54de7d2396095492ae171103cd4bfccfc2a4dafa001d48c130694c105c2d010000000900000001673ee3e5a3a1221935274e8ff5c45b27ebe570e9731948e393a8ebef6a15391c189a54de7d2396095492ae171103cd4bfccfc2a4dafa001d48c130694c105c2d01", expectedStaticFee: testStaticConfig.TxFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 436, // The length of the tx in bytes - fee.DBRead: IntrinsicRemoveSubnetValidatorTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicRemoveSubnetValidatorTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 436, // The length of the tx in bytes + gas.DBRead: IntrinsicRemoveSubnetValidatorTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicRemoveSubnetValidatorTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 193_600, }, @@ -211,11 +211,11 @@ var ( name: "TransferSubnetOwnershipTx", tx: "00000000002100003039000000000000000000000000000000000000000000000000000000000000000000000001dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000070023834e99bf1ec0000000000000000000000001000000013cb7d3842e8cee6a0ebd09f1fe884f6861e1b29c000000018f6e5f2840e34f9a375f35627a44bb0b9974285d280dc3220aa9489f97b17ebd00000000dbcf890f77f49b96857648b72b77f9f82937f28a68704af05da0dc12ba53f2db000000050023834e99ce610000000001000000000000000097ea88082100491617204ed70c19fc1a2fce4474bee962904359d0b59e84c1240000000a00000001000000000000000b00000000000000000000000000000000000000020000000900000001e3479034ed8134dd23e154e1ec6e61b25073a20750ebf808e50ec1aae180ef430f8151347afdf6606bc7866f7f068b01719e4dad12e2976af1159fb048f73f7f010000000900000001e3479034ed8134dd23e154e1ec6e61b25073a20750ebf808e50ec1aae180ef430f8151347afdf6606bc7866f7f068b01719e4dad12e2976af1159fb048f73f7f01", expectedStaticFee: testStaticConfig.TxFee, - expectedComplexity: fee.Dimensions{ - fee.Bandwidth: 436, // The length of the tx in bytes - fee.DBRead: IntrinsicTransferSubnetOwnershipTxComplexities[fee.DBRead] + intrinsicInputDBRead, - fee.DBWrite: IntrinsicTransferSubnetOwnershipTxComplexities[fee.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, - fee.Compute: 0, // TODO: implement + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 436, // The length of the tx in bytes + gas.DBRead: IntrinsicTransferSubnetOwnershipTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicTransferSubnetOwnershipTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement }, expectedDynamicFee: 173_600, }, diff --git a/vms/platformvm/txs/fee/complexity.go b/vms/platformvm/txs/fee/complexity.go index 2334230078a8..4b06417b8462 100644 --- a/vms/platformvm/txs/fee/complexity.go +++ b/vms/platformvm/txs/fee/complexity.go @@ -13,7 +13,7 @@ import ( "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/wrappers" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/signer" @@ -74,8 +74,8 @@ const ( var ( _ txs.Visitor = (*complexityVisitor)(nil) - IntrinsicAddPermissionlessValidatorTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicAddPermissionlessValidatorTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + intrinsicValidatorBandwidth + // validator ids.IDLen + // subnetID wrappers.IntLen + // signer typeID @@ -83,31 +83,31 @@ var ( wrappers.IntLen + // validator rewards typeID wrappers.IntLen + // delegator rewards typeID wrappers.IntLen, // delegation shares - fee.DBRead: 1, - fee.DBWrite: 1, - fee.Compute: 0, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, } - IntrinsicAddPermissionlessDelegatorTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicAddPermissionlessDelegatorTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + intrinsicValidatorBandwidth + // validator ids.IDLen + // subnetID wrappers.IntLen + // num stake outs wrappers.IntLen, // delegator rewards typeID - fee.DBRead: 1, - fee.DBWrite: 1, - fee.Compute: 0, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, } - IntrinsicAddSubnetValidatorTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicAddSubnetValidatorTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + intrinsicSubnetValidatorBandwidth + // subnetValidator wrappers.IntLen + // subnetAuth typeID wrappers.IntLen, // subnetAuthCredential typeID - fee.DBRead: 2, - fee.DBWrite: 1, - fee.Compute: 0, + gas.DBRead: 2, + gas.DBWrite: 1, + gas.Compute: 0, } - IntrinsicBaseTxComplexities = fee.Dimensions{ - fee.Bandwidth: codec.VersionSize + // codecVersion + IntrinsicBaseTxComplexities = gas.Dimensions{ + gas.Bandwidth: codec.VersionSize + // codecVersion wrappers.IntLen + // typeID wrappers.IntLen + // networkID ids.IDLen + // blockchainID @@ -115,12 +115,12 @@ var ( wrappers.IntLen + // number of inputs wrappers.IntLen + // length of memo wrappers.IntLen, // number of credentials - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, } - IntrinsicCreateChainTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicCreateChainTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + ids.IDLen + // subnetID wrappers.ShortLen + // chainName length ids.IDLen + // vmID @@ -128,52 +128,52 @@ var ( wrappers.IntLen + // genesis length wrappers.IntLen + // subnetAuth typeID wrappers.IntLen, // subnetAuthCredential typeID - fee.DBRead: 1, - fee.DBWrite: 1, - fee.Compute: 0, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, } - IntrinsicCreateSubnetTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicCreateSubnetTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + wrappers.IntLen, // owner typeID - fee.DBRead: 0, - fee.DBWrite: 1, - fee.Compute: 0, + gas.DBRead: 0, + gas.DBWrite: 1, + gas.Compute: 0, } - IntrinsicExportTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicExportTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + ids.IDLen + // destination chainID wrappers.IntLen, // num exported outputs - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, } - IntrinsicImportTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicImportTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + ids.IDLen + // source chainID wrappers.IntLen, // num importing inputs - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, } - IntrinsicRemoveSubnetValidatorTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicRemoveSubnetValidatorTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + ids.NodeIDLen + // nodeID ids.IDLen + // subnetID wrappers.IntLen + // subnetAuth typeID wrappers.IntLen, // subnetAuthCredential typeID - fee.DBRead: 2, - fee.DBWrite: 1, - fee.Compute: 0, + gas.DBRead: 2, + gas.DBWrite: 1, + gas.Compute: 0, } - IntrinsicTransferSubnetOwnershipTxComplexities = fee.Dimensions{ - fee.Bandwidth: IntrinsicBaseTxComplexities[fee.Bandwidth] + + IntrinsicTransferSubnetOwnershipTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + ids.IDLen + // subnetID wrappers.IntLen + // subnetAuth typeID wrappers.IntLen + // owner typeID wrappers.IntLen, // subnetAuthCredential typeID - fee.DBRead: 1, - fee.DBWrite: 1, - fee.Compute: 0, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, } errUnsupportedOutput = errors.New("unsupported output type") @@ -183,127 +183,127 @@ var ( errUnsupportedSigner = errors.New("unsupported signer type") ) -func TxComplexity(tx txs.UnsignedTx) (fee.Dimensions, error) { +func TxComplexity(tx txs.UnsignedTx) (gas.Dimensions, error) { c := complexityVisitor{} err := tx.Visit(&c) return c.output, err } // OutputComplexity returns the complexity outputs add to a transaction. -func OutputComplexity(outs ...*avax.TransferableOutput) (fee.Dimensions, error) { - var complexity fee.Dimensions +func OutputComplexity(outs ...*avax.TransferableOutput) (gas.Dimensions, error) { + var complexity gas.Dimensions for _, out := range outs { outputComplexity, err := outputComplexity(out) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } complexity, err = complexity.Add(&outputComplexity) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } } return complexity, nil } -func outputComplexity(out *avax.TransferableOutput) (fee.Dimensions, error) { - complexity := fee.Dimensions{ - fee.Bandwidth: intrinsicOutputBandwidth + intrinsicSECP256k1FxOutputBandwidth, - fee.DBRead: 0, - fee.DBWrite: intrinsicOutputDBWrite, - fee.Compute: 0, +func outputComplexity(out *avax.TransferableOutput) (gas.Dimensions, error) { + complexity := gas.Dimensions{ + gas.Bandwidth: intrinsicOutputBandwidth + intrinsicSECP256k1FxOutputBandwidth, + gas.DBRead: 0, + gas.DBWrite: intrinsicOutputDBWrite, + gas.Compute: 0, } outIntf := out.Out if stakeableOut, ok := outIntf.(*stakeable.LockOut); ok { - complexity[fee.Bandwidth] += intrinsicStakeableLockedOutputBandwidth + complexity[gas.Bandwidth] += intrinsicStakeableLockedOutputBandwidth outIntf = stakeableOut.TransferableOut } secp256k1Out, ok := outIntf.(*secp256k1fx.TransferOutput) if !ok { - return fee.Dimensions{}, errUnsupportedOutput + return gas.Dimensions{}, errUnsupportedOutput } numAddresses := uint64(len(secp256k1Out.Addrs)) addressBandwidth, err := math.Mul(numAddresses, ids.ShortIDLen) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } - complexity[fee.Bandwidth], err = math.Add(complexity[fee.Bandwidth], addressBandwidth) + complexity[gas.Bandwidth], err = math.Add(complexity[gas.Bandwidth], addressBandwidth) return complexity, err } // InputComplexity returns the complexity inputs add to a transaction. // It includes the complexity that the corresponding credentials will add. -func InputComplexity(ins ...*avax.TransferableInput) (fee.Dimensions, error) { - var complexity fee.Dimensions +func InputComplexity(ins ...*avax.TransferableInput) (gas.Dimensions, error) { + var complexity gas.Dimensions for _, in := range ins { inputComplexity, err := inputComplexity(in) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } complexity, err = complexity.Add(&inputComplexity) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } } return complexity, nil } -func inputComplexity(in *avax.TransferableInput) (fee.Dimensions, error) { - complexity := fee.Dimensions{ - fee.Bandwidth: intrinsicInputBandwidth + intrinsicSECP256k1FxTransferableInputBandwidth, - fee.DBRead: intrinsicInputDBRead, - fee.DBWrite: intrinsicInputDBWrite, - fee.Compute: 0, // TODO: Add compute complexity +func inputComplexity(in *avax.TransferableInput) (gas.Dimensions, error) { + complexity := gas.Dimensions{ + gas.Bandwidth: intrinsicInputBandwidth + intrinsicSECP256k1FxTransferableInputBandwidth, + gas.DBRead: intrinsicInputDBRead, + gas.DBWrite: intrinsicInputDBWrite, + gas.Compute: 0, // TODO: Add compute complexity } inIntf := in.In if stakeableIn, ok := inIntf.(*stakeable.LockIn); ok { - complexity[fee.Bandwidth] += intrinsicStakeableLockedInputBandwidth + complexity[gas.Bandwidth] += intrinsicStakeableLockedInputBandwidth inIntf = stakeableIn.TransferableIn } secp256k1In, ok := inIntf.(*secp256k1fx.TransferInput) if !ok { - return fee.Dimensions{}, errUnsupportedInput + return gas.Dimensions{}, errUnsupportedInput } numSignatures := uint64(len(secp256k1In.SigIndices)) signatureBandwidth, err := math.Mul(numSignatures, intrinsicSECP256k1FxSignatureBandwidth) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } - complexity[fee.Bandwidth], err = math.Add(complexity[fee.Bandwidth], signatureBandwidth) + complexity[gas.Bandwidth], err = math.Add(complexity[gas.Bandwidth], signatureBandwidth) return complexity, err } // OwnerComplexity returns the complexity an owner adds to a transaction. // It does not include the typeID of the owner. -func OwnerComplexity(ownerIntf fx.Owner) (fee.Dimensions, error) { +func OwnerComplexity(ownerIntf fx.Owner) (gas.Dimensions, error) { owner, ok := ownerIntf.(*secp256k1fx.OutputOwners) if !ok { - return fee.Dimensions{}, errUnsupportedOwner + return gas.Dimensions{}, errUnsupportedOwner } numAddresses := uint64(len(owner.Addrs)) addressBandwidth, err := math.Mul(numAddresses, ids.ShortIDLen) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } bandwidth, err := math.Add(addressBandwidth, intrinsicSECP256k1FxOutputOwnersBandwidth) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } - return fee.Dimensions{ - fee.Bandwidth: bandwidth, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + return gas.Dimensions{ + gas.Bandwidth: bandwidth, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, }, nil } @@ -311,51 +311,51 @@ func OwnerComplexity(ownerIntf fx.Owner) (fee.Dimensions, error) { // It does not include the typeID of the authorization. // It does includes the complexity that the corresponding credential will add. // It does not include the typeID of the credential. -func AuthComplexity(authIntf verify.Verifiable) (fee.Dimensions, error) { +func AuthComplexity(authIntf verify.Verifiable) (gas.Dimensions, error) { auth, ok := authIntf.(*secp256k1fx.Input) if !ok { - return fee.Dimensions{}, errUnsupportedAuth + return gas.Dimensions{}, errUnsupportedAuth } numSignatures := uint64(len(auth.SigIndices)) signatureBandwidth, err := math.Mul(numSignatures, intrinsicSECP256k1FxSignatureBandwidth) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } bandwidth, err := math.Add(signatureBandwidth, intrinsicSECP256k1FxInputBandwidth) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } - return fee.Dimensions{ - fee.Bandwidth: bandwidth, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, // TODO: Add compute complexity + return gas.Dimensions{ + gas.Bandwidth: bandwidth, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, // TODO: Add compute complexity }, nil } // SignerComplexity returns the complexity a signer adds to a transaction. // It does not include the typeID of the signer. -func SignerComplexity(s signer.Signer) (fee.Dimensions, error) { +func SignerComplexity(s signer.Signer) (gas.Dimensions, error) { switch s.(type) { case *signer.Empty: - return fee.Dimensions{}, nil + return gas.Dimensions{}, nil case *signer.ProofOfPossession: - return fee.Dimensions{ - fee.Bandwidth: intrinsicPoPBandwidth, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, // TODO: Add compute complexity + return gas.Dimensions{ + gas.Bandwidth: intrinsicPoPBandwidth, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, // TODO: Add compute complexity }, nil default: - return fee.Dimensions{}, errUnsupportedSigner + return gas.Dimensions{}, errUnsupportedSigner } } type complexityVisitor struct { - output fee.Dimensions + output gas.Dimensions } func (*complexityVisitor) AddDelegatorTx(*txs.AddDelegatorTx) error { @@ -470,11 +470,11 @@ func (c *complexityVisitor) CreateChainTx(tx *txs.CreateChainTx) error { if err != nil { return err } - dynamicComplexity := fee.Dimensions{ - fee.Bandwidth: bandwidth, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + dynamicComplexity := gas.Dimensions{ + gas.Bandwidth: bandwidth, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, } baseTxComplexity, err := baseTxComplexity(&tx.BaseTx) @@ -580,21 +580,21 @@ func (c *complexityVisitor) TransferSubnetOwnershipTx(tx *txs.TransferSubnetOwne return err } -func baseTxComplexity(tx *txs.BaseTx) (fee.Dimensions, error) { +func baseTxComplexity(tx *txs.BaseTx) (gas.Dimensions, error) { outputsComplexity, err := OutputComplexity(tx.Outs...) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } inputsComplexity, err := InputComplexity(tx.Ins...) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } complexity, err := outputsComplexity.Add(&inputsComplexity) if err != nil { - return fee.Dimensions{}, err + return gas.Dimensions{}, err } - complexity[fee.Bandwidth], err = math.Add( - complexity[fee.Bandwidth], + complexity[gas.Bandwidth], err = math.Add( + complexity[gas.Bandwidth], uint64(len(tx.Memo)), ) return complexity, err diff --git a/vms/platformvm/txs/fee/complexity_test.go b/vms/platformvm/txs/fee/complexity_test.go index d918962fa07b..08bb3b2fc920 100644 --- a/vms/platformvm/txs/fee/complexity_test.go +++ b/vms/platformvm/txs/fee/complexity_test.go @@ -14,7 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/signer" @@ -47,7 +47,7 @@ func TestTxComplexity(t *testing.T) { return } - require.Len(txBytes, int(actual[fee.Bandwidth])) + require.Len(txBytes, int(actual[gas.Bandwidth])) }) } } @@ -75,7 +75,7 @@ func TestOutputComplexity(t *testing.T) { tests := []struct { name string out *avax.TransferableOutput - expected fee.Dimensions + expected gas.Dimensions expectedErr error }{ { @@ -87,11 +87,11 @@ func TestOutputComplexity(t *testing.T) { }, }, }, - expected: fee.Dimensions{ - fee.Bandwidth: 60, - fee.DBRead: 0, - fee.DBWrite: 1, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 60, + gas.DBRead: 0, + gas.DBWrite: 1, + gas.Compute: 0, }, expectedErr: nil, }, @@ -104,11 +104,11 @@ func TestOutputComplexity(t *testing.T) { }, }, }, - expected: fee.Dimensions{ - fee.Bandwidth: 80, - fee.DBRead: 0, - fee.DBWrite: 1, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 80, + gas.DBRead: 0, + gas.DBWrite: 1, + gas.Compute: 0, }, expectedErr: nil, }, @@ -121,11 +121,11 @@ func TestOutputComplexity(t *testing.T) { }, }, }, - expected: fee.Dimensions{ - fee.Bandwidth: 120, - fee.DBRead: 0, - fee.DBWrite: 1, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 120, + gas.DBRead: 0, + gas.DBWrite: 1, + gas.Compute: 0, }, expectedErr: nil, }, @@ -140,11 +140,11 @@ func TestOutputComplexity(t *testing.T) { }, }, }, - expected: fee.Dimensions{ - fee.Bandwidth: 132, - fee.DBRead: 0, - fee.DBWrite: 1, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 132, + gas.DBRead: 0, + gas.DBWrite: 1, + gas.Compute: 0, }, expectedErr: nil, }, @@ -153,11 +153,11 @@ func TestOutputComplexity(t *testing.T) { out: &avax.TransferableOutput{ Out: nil, }, - expected: fee.Dimensions{ - fee.Bandwidth: 0, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 0, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, }, expectedErr: errUnsupportedOutput, }, @@ -178,7 +178,7 @@ func TestOutputComplexity(t *testing.T) { require.NoError(err) numBytesWithoutCodecVersion := uint64(len(bytes) - codec.VersionSize) - require.Equal(numBytesWithoutCodecVersion, actual[fee.Bandwidth]) + require.Equal(numBytesWithoutCodecVersion, actual[gas.Bandwidth]) }) } } @@ -188,7 +188,7 @@ func TestInputComplexity(t *testing.T) { name string in *avax.TransferableInput cred verify.Verifiable - expected fee.Dimensions + expected gas.Dimensions expectedErr error }{ { @@ -203,11 +203,11 @@ func TestInputComplexity(t *testing.T) { cred: &secp256k1fx.Credential{ Sigs: make([][secp256k1.SignatureLen]byte, 0), }, - expected: fee.Dimensions{ - fee.Bandwidth: 92, - fee.DBRead: 1, - fee.DBWrite: 1, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 92, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, // TODO: implement }, expectedErr: nil, }, @@ -223,11 +223,11 @@ func TestInputComplexity(t *testing.T) { cred: &secp256k1fx.Credential{ Sigs: make([][secp256k1.SignatureLen]byte, 1), }, - expected: fee.Dimensions{ - fee.Bandwidth: 161, - fee.DBRead: 1, - fee.DBWrite: 1, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 161, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, // TODO: implement }, expectedErr: nil, }, @@ -243,11 +243,11 @@ func TestInputComplexity(t *testing.T) { cred: &secp256k1fx.Credential{ Sigs: make([][secp256k1.SignatureLen]byte, 3), }, - expected: fee.Dimensions{ - fee.Bandwidth: 299, - fee.DBRead: 1, - fee.DBWrite: 1, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 299, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, // TODO: implement }, expectedErr: nil, }, @@ -265,11 +265,11 @@ func TestInputComplexity(t *testing.T) { cred: &secp256k1fx.Credential{ Sigs: make([][secp256k1.SignatureLen]byte, 3), }, - expected: fee.Dimensions{ - fee.Bandwidth: 311, - fee.DBRead: 1, - fee.DBWrite: 1, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 311, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, // TODO: implement }, expectedErr: nil, }, @@ -279,11 +279,11 @@ func TestInputComplexity(t *testing.T) { In: nil, }, cred: nil, - expected: fee.Dimensions{ - fee.Bandwidth: 0, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 0, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, }, expectedErr: errUnsupportedInput, }, @@ -308,7 +308,7 @@ func TestInputComplexity(t *testing.T) { require.NoError(err) numBytesWithoutCodecVersion := uint64(len(inputBytes) + len(credentialBytes) - 2*codec.VersionSize) - require.Equal(numBytesWithoutCodecVersion, actual[fee.Bandwidth]) + require.Equal(numBytesWithoutCodecVersion, actual[gas.Bandwidth]) }) } } @@ -317,7 +317,7 @@ func TestOwnerComplexity(t *testing.T) { tests := []struct { name string owner fx.Owner - expected fee.Dimensions + expected gas.Dimensions expectedErr error }{ { @@ -325,11 +325,11 @@ func TestOwnerComplexity(t *testing.T) { owner: &secp256k1fx.OutputOwners{ Addrs: make([]ids.ShortID, 0), }, - expected: fee.Dimensions{ - fee.Bandwidth: 16, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 16, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, }, expectedErr: nil, }, @@ -338,11 +338,11 @@ func TestOwnerComplexity(t *testing.T) { owner: &secp256k1fx.OutputOwners{ Addrs: make([]ids.ShortID, 1), }, - expected: fee.Dimensions{ - fee.Bandwidth: 36, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 36, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, }, expectedErr: nil, }, @@ -351,18 +351,18 @@ func TestOwnerComplexity(t *testing.T) { owner: &secp256k1fx.OutputOwners{ Addrs: make([]ids.ShortID, 3), }, - expected: fee.Dimensions{ - fee.Bandwidth: 76, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 76, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, }, expectedErr: nil, }, { name: "invalid owner type", owner: nil, - expected: fee.Dimensions{}, + expected: gas.Dimensions{}, expectedErr: errUnsupportedOwner, }, } @@ -382,7 +382,7 @@ func TestOwnerComplexity(t *testing.T) { require.NoError(err) numBytesWithoutCodecVersion := uint64(len(ownerBytes) - codec.VersionSize) - require.Equal(numBytesWithoutCodecVersion, actual[fee.Bandwidth]) + require.Equal(numBytesWithoutCodecVersion, actual[gas.Bandwidth]) }) } } @@ -392,7 +392,7 @@ func TestAuthComplexity(t *testing.T) { name string auth verify.Verifiable cred verify.Verifiable - expected fee.Dimensions + expected gas.Dimensions expectedErr error }{ { @@ -403,11 +403,11 @@ func TestAuthComplexity(t *testing.T) { cred: &secp256k1fx.Credential{ Sigs: make([][secp256k1.SignatureLen]byte, 0), }, - expected: fee.Dimensions{ - fee.Bandwidth: 8, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 8, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, // TODO: implement }, expectedErr: nil, }, @@ -419,11 +419,11 @@ func TestAuthComplexity(t *testing.T) { cred: &secp256k1fx.Credential{ Sigs: make([][secp256k1.SignatureLen]byte, 1), }, - expected: fee.Dimensions{ - fee.Bandwidth: 77, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 77, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, // TODO: implement }, expectedErr: nil, }, @@ -435,11 +435,11 @@ func TestAuthComplexity(t *testing.T) { cred: &secp256k1fx.Credential{ Sigs: make([][secp256k1.SignatureLen]byte, 3), }, - expected: fee.Dimensions{ - fee.Bandwidth: 215, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 215, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, // TODO: implement }, expectedErr: nil, }, @@ -447,11 +447,11 @@ func TestAuthComplexity(t *testing.T) { name: "invalid auth type", auth: nil, cred: nil, - expected: fee.Dimensions{ - fee.Bandwidth: 0, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 0, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, // TODO: implement }, expectedErr: errUnsupportedAuth, }, @@ -475,7 +475,7 @@ func TestAuthComplexity(t *testing.T) { require.NoError(err) numBytesWithoutCodecVersion := uint64(len(authBytes) + len(credentialBytes) - 2*codec.VersionSize) - require.Equal(numBytesWithoutCodecVersion, actual[fee.Bandwidth]) + require.Equal(numBytesWithoutCodecVersion, actual[gas.Bandwidth]) }) } } @@ -484,39 +484,39 @@ func TestSignerComplexity(t *testing.T) { tests := []struct { name string signer signer.Signer - expected fee.Dimensions + expected gas.Dimensions expectedErr error }{ { name: "empty", signer: &signer.Empty{}, - expected: fee.Dimensions{ - fee.Bandwidth: 0, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 0, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, }, expectedErr: nil, }, { name: "bls pop", signer: &signer.ProofOfPossession{}, - expected: fee.Dimensions{ - fee.Bandwidth: 144, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, // TODO: implement + expected: gas.Dimensions{ + gas.Bandwidth: 144, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, // TODO: implement }, expectedErr: nil, }, { name: "invalid signer type", signer: nil, - expected: fee.Dimensions{ - fee.Bandwidth: 0, - fee.DBRead: 0, - fee.DBWrite: 0, - fee.Compute: 0, + expected: gas.Dimensions{ + gas.Bandwidth: 0, + gas.DBRead: 0, + gas.DBWrite: 0, + gas.Compute: 0, }, expectedErr: errUnsupportedSigner, }, @@ -537,7 +537,7 @@ func TestSignerComplexity(t *testing.T) { require.NoError(err) numBytesWithoutCodecVersion := uint64(len(signerBytes) - codec.VersionSize) - require.Equal(numBytesWithoutCodecVersion, actual[fee.Bandwidth]) + require.Equal(numBytesWithoutCodecVersion, actual[gas.Bandwidth]) }) } } diff --git a/vms/platformvm/txs/fee/dynamic_calculator.go b/vms/platformvm/txs/fee/dynamic_calculator.go index 6754e5c85ae2..8c51d32a8b90 100644 --- a/vms/platformvm/txs/fee/dynamic_calculator.go +++ b/vms/platformvm/txs/fee/dynamic_calculator.go @@ -7,7 +7,7 @@ import ( "errors" "fmt" - "github.com/ava-labs/avalanchego/vms/components/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) @@ -20,8 +20,8 @@ var ( ) func NewDynamicCalculator( - weights fee.Dimensions, - price fee.GasPrice, + weights gas.Dimensions, + price gas.Price, ) Calculator { return &dynamicCalculator{ weights: weights, @@ -30,8 +30,8 @@ func NewDynamicCalculator( } type dynamicCalculator struct { - weights fee.Dimensions - price fee.GasPrice + weights gas.Dimensions + price gas.Price } func (c *dynamicCalculator) CalculateFee(tx txs.UnsignedTx) (uint64, error) { diff --git a/vms/platformvm/vm_test.go b/vms/platformvm/vm_test.go index 4175c0346c70..89aac04ce947 100644 --- a/vms/platformvm/vm_test.go +++ b/vms/platformvm/vm_test.go @@ -51,6 +51,7 @@ import ( "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/api" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" @@ -58,6 +59,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -66,11 +68,9 @@ import ( smeng "github.com/ava-labs/avalanchego/snow/engine/snowman" snowgetter "github.com/ava-labs/avalanchego/snow/engine/snowman/getter" timetracker "github.com/ava-labs/avalanchego/snow/networking/tracker" - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" blockbuilder "github.com/ava-labs/avalanchego/vms/platformvm/block/builder" blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" walletbuilder "github.com/ava-labs/avalanchego/wallet/chain/p/builder" walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" @@ -112,23 +112,23 @@ var ( defaultMaxValidatorStake = 100 * defaultMinValidatorStake defaultBalance = 2 * defaultMaxValidatorStake // amount all genesis validators have in defaultVM - defaultStaticFeeConfig = txfee.StaticConfig{ + defaultStaticFeeConfig = fee.StaticConfig{ TxFee: defaultTxFee, CreateSubnetTxFee: 100 * defaultTxFee, TransformSubnetTxFee: 100 * defaultTxFee, CreateBlockchainTxFee: 100 * defaultTxFee, } - defaultDynamicFeeConfig = feecomponent.Config{ - Weights: feecomponent.Dimensions{ - feecomponent.Bandwidth: 1, - feecomponent.DBRead: 1, - feecomponent.DBWrite: 1, - feecomponent.Compute: 1, + defaultDynamicFeeConfig = gas.Config{ + Weights: gas.Dimensions{ + gas.Bandwidth: 1, + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 1, }, - MaxGasCapacity: 10_000, - MaxGasPerSecond: 1_000, - TargetGasPerSecond: 500, - MinGasPrice: 1, + MaxCapacity: 10_000, + MaxPerSecond: 1_000, + TargetPerSecond: 500, + MinPrice: 1, ExcessConversionConstant: 5_000, } diff --git a/wallet/chain/p/builder/builder.go b/wallet/chain/p/builder/builder.go index e15267893fcf..b665617e0e16 100644 --- a/wallet/chain/p/builder/builder.go +++ b/wallet/chain/p/builder/builder.go @@ -15,16 +15,15 @@ import ( "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) var ( @@ -329,14 +328,14 @@ func (b *builder) NewBaseTx( ops := common.NewOptions(options) memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - outputComplexity, err := txfee.OutputComplexity(outputs...) + outputComplexity, err := fee.OutputComplexity(outputs...) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicBaseTxComplexities.Add( + complexity, err := fee.IntrinsicBaseTxComplexities.Add( &memoComplexity, &outputComplexity, ) @@ -386,7 +385,7 @@ func (b *builder) NewAddValidatorTx( toBurn, toStake, 0, - feecomponent.Dimensions{}, + gas.Dimensions{}, nil, ops, ) @@ -427,14 +426,14 @@ func (b *builder) NewAddSubnetValidatorTx( } memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - authComplexity, err := txfee.AuthComplexity(subnetAuth) + authComplexity, err := fee.AuthComplexity(subnetAuth) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicAddSubnetValidatorTxComplexities.Add( + complexity, err := fee.IntrinsicAddSubnetValidatorTxComplexities.Add( &memoComplexity, &authComplexity, ) @@ -485,14 +484,14 @@ func (b *builder) NewRemoveSubnetValidatorTx( } memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - authComplexity, err := txfee.AuthComplexity(subnetAuth) + authComplexity, err := fee.AuthComplexity(subnetAuth) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicRemoveSubnetValidatorTxComplexities.Add( + complexity, err := fee.IntrinsicRemoveSubnetValidatorTxComplexities.Add( &memoComplexity, &authComplexity, ) @@ -544,7 +543,7 @@ func (b *builder) NewAddDelegatorTx( toBurn, toStake, 0, - feecomponent.Dimensions{}, + gas.Dimensions{}, nil, ops, ) @@ -604,14 +603,14 @@ func (b *builder) NewCreateChainTx( if err != nil { return nil, err } - dynamicComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: bandwidth, + dynamicComplexity := gas.Dimensions{ + gas.Bandwidth: bandwidth, } - authComplexity, err := txfee.AuthComplexity(subnetAuth) + authComplexity, err := fee.AuthComplexity(subnetAuth) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicCreateChainTxComplexities.Add( + complexity, err := fee.IntrinsicCreateChainTxComplexities.Add( &dynamicComplexity, &authComplexity, ) @@ -661,14 +660,14 @@ func (b *builder) NewCreateSubnetTx( ops := common.NewOptions(options) memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - ownerComplexity, err := txfee.OwnerComplexity(owner) + ownerComplexity, err := fee.OwnerComplexity(owner) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicCreateSubnetTxComplexities.Add( + complexity, err := fee.IntrinsicCreateSubnetTxComplexities.Add( &memoComplexity, &ownerComplexity, ) @@ -719,18 +718,18 @@ func (b *builder) NewTransferSubnetOwnershipTx( } memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - authComplexity, err := txfee.AuthComplexity(subnetAuth) + authComplexity, err := fee.AuthComplexity(subnetAuth) if err != nil { return nil, err } - ownerComplexity, err := txfee.OwnerComplexity(owner) + ownerComplexity, err := fee.OwnerComplexity(owner) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicTransferSubnetOwnershipTxComplexities.Add( + complexity, err := fee.IntrinsicTransferSubnetOwnershipTxComplexities.Add( &memoComplexity, &authComplexity, &ownerComplexity, @@ -843,18 +842,18 @@ func (b *builder) NewImportTx( } memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - inputComplexity, err := txfee.InputComplexity(importedInputs...) + inputComplexity, err := fee.InputComplexity(importedInputs...) if err != nil { return nil, err } - outputComplexity, err := txfee.OutputComplexity(outputs...) + outputComplexity, err := fee.OutputComplexity(outputs...) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicImportTxComplexities.Add( + complexity, err := fee.IntrinsicImportTxComplexities.Add( &memoComplexity, &inputComplexity, &outputComplexity, @@ -922,14 +921,14 @@ func (b *builder) NewExportTx( toStake := map[ids.ID]uint64{} ops := common.NewOptions(options) memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - outputComplexity, err := txfee.OutputComplexity(outputs...) + outputComplexity, err := fee.OutputComplexity(outputs...) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicExportTxComplexities.Add( + complexity, err := fee.IntrinsicExportTxComplexities.Add( &memoComplexity, &outputComplexity, ) @@ -997,7 +996,7 @@ func (b *builder) NewTransformSubnetTx( toBurn, toStake, 0, - feecomponent.Dimensions{}, + gas.Dimensions{}, nil, ops, ) @@ -1054,22 +1053,22 @@ func (b *builder) NewAddPermissionlessValidatorTx( ops := common.NewOptions(options) memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - signerComplexity, err := txfee.SignerComplexity(signer) + signerComplexity, err := fee.SignerComplexity(signer) if err != nil { return nil, err } - validatorOwnerComplexity, err := txfee.OwnerComplexity(validationRewardsOwner) + validatorOwnerComplexity, err := fee.OwnerComplexity(validationRewardsOwner) if err != nil { return nil, err } - delegatorOwnerComplexity, err := txfee.OwnerComplexity(delegationRewardsOwner) + delegatorOwnerComplexity, err := fee.OwnerComplexity(delegationRewardsOwner) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicAddPermissionlessValidatorTxComplexities.Add( + complexity, err := fee.IntrinsicAddPermissionlessValidatorTxComplexities.Add( &memoComplexity, &signerComplexity, &validatorOwnerComplexity, @@ -1131,14 +1130,14 @@ func (b *builder) NewAddPermissionlessDelegatorTx( ops := common.NewOptions(options) memo := ops.Memo() - memoComplexity := feecomponent.Dimensions{ - feecomponent.Bandwidth: uint64(len(memo)), + memoComplexity := gas.Dimensions{ + gas.Bandwidth: uint64(len(memo)), } - ownerComplexity, err := txfee.OwnerComplexity(rewardsOwner) + ownerComplexity, err := fee.OwnerComplexity(rewardsOwner) if err != nil { return nil, err } - complexity, err := txfee.IntrinsicAddPermissionlessDelegatorTxComplexities.Add( + complexity, err := fee.IntrinsicAddPermissionlessDelegatorTxComplexities.Add( &memoComplexity, &ownerComplexity, ) @@ -1245,7 +1244,7 @@ func (b *builder) spend( toBurn map[ids.ID]uint64, toStake map[ids.ID]uint64, excessAVAX uint64, - complexity feecomponent.Dimensions, + complexity gas.Dimensions, ownerOverride *secp256k1fx.OutputOwners, options *common.Options, ) ( @@ -1564,12 +1563,12 @@ func (b *builder) initCtx(tx txs.UnsignedTx) error { } type spendHelper struct { - weights feecomponent.Dimensions - gasPrice feecomponent.GasPrice + weights gas.Dimensions + gasPrice gas.Price toBurn map[ids.ID]uint64 toStake map[ids.ID]uint64 - complexity feecomponent.Dimensions + complexity gas.Dimensions inputs []*avax.TransferableInput changeOutputs []*avax.TransferableOutput @@ -1577,7 +1576,7 @@ type spendHelper struct { } func (s *spendHelper) addInput(input *avax.TransferableInput) error { - newInputComplexity, err := txfee.InputComplexity(input) + newInputComplexity, err := fee.InputComplexity(input) if err != nil { return err } @@ -1601,7 +1600,7 @@ func (s *spendHelper) addStakedOutput(output *avax.TransferableOutput) error { } func (s *spendHelper) addOutputComplexity(output *avax.TransferableOutput) error { - newOutputComplexity, err := txfee.OutputComplexity(output) + newOutputComplexity, err := fee.OutputComplexity(output) if err != nil { return err } diff --git a/wallet/chain/p/builder/context.go b/wallet/chain/p/builder/context.go index 3729edca2deb..2ddf168ad228 100644 --- a/wallet/chain/p/builder/context.go +++ b/wallet/chain/p/builder/context.go @@ -12,9 +12,8 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/avm" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/vms/components/gas" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) const Alias = "P" @@ -22,9 +21,9 @@ const Alias = "P" type Context struct { NetworkID uint32 AVAXAssetID ids.ID - StaticFeeConfig txfee.StaticConfig - ComplexityWeights feecomponent.Dimensions - GasPrice feecomponent.GasPrice + StaticFeeConfig fee.StaticConfig + ComplexityWeights gas.Dimensions + GasPrice gas.Price } func NewContextFromURI(ctx context.Context, uri string) (*Context, error) { @@ -56,7 +55,7 @@ func NewContextFromClients( return &Context{ NetworkID: networkID, AVAXAssetID: asset.AssetID, - StaticFeeConfig: txfee.StaticConfig{ + StaticFeeConfig: fee.StaticConfig{ TxFee: uint64(txFees.TxFee), CreateSubnetTxFee: uint64(txFees.CreateSubnetTxFee), TransformSubnetTxFee: uint64(txFees.TransformSubnetTxFee), @@ -68,7 +67,7 @@ func NewContextFromClients( }, // TODO: Populate these fields once they are exposed by the API - ComplexityWeights: feecomponent.Dimensions{}, + ComplexityWeights: gas.Dimensions{}, GasPrice: 0, }, nil } diff --git a/wallet/chain/p/builder_test.go b/wallet/chain/p/builder_test.go index 69168e463b2e..e2a970b909cc 100644 --- a/wallet/chain/p/builder_test.go +++ b/wallet/chain/p/builder_test.go @@ -17,20 +17,19 @@ import ( "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/fx" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/vms/types" "github.com/ava-labs/avalanchego/wallet/chain/p/builder" "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common/utxotest" - - feecomponent "github.com/ava-labs/avalanchego/vms/components/fee" - txfee "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) var ( @@ -93,7 +92,7 @@ var ( testContextPreEtna = &builder.Context{ NetworkID: constants.UnitTestID, AVAXAssetID: avaxAssetID, - StaticFeeConfig: txfee.StaticConfig{ + StaticFeeConfig: fee.StaticConfig{ TxFee: units.MicroAvax, CreateSubnetTxFee: 19 * units.MicroAvax, TransformSubnetTxFee: 789 * units.MicroAvax, @@ -104,7 +103,7 @@ var ( AddSubnetDelegatorFee: 9 * units.Avax, }, } - staticFeeCalculator = txfee.NewStaticCalculator( + staticFeeCalculator = fee.NewStaticCalculator( testContextPreEtna.StaticFeeConfig, ) @@ -112,15 +111,15 @@ var ( NetworkID: constants.UnitTestID, AVAXAssetID: avaxAssetID, - ComplexityWeights: feecomponent.Dimensions{ - feecomponent.Bandwidth: 1, - feecomponent.DBRead: 10, - feecomponent.DBWrite: 100, - feecomponent.Compute: 1000, + ComplexityWeights: gas.Dimensions{ + gas.Bandwidth: 1, + gas.DBRead: 10, + gas.DBWrite: 100, + gas.Compute: 1000, }, GasPrice: 1, } - dynamicFeeCalculator = txfee.NewDynamicCalculator( + dynamicFeeCalculator = fee.NewDynamicCalculator( testContextPostEtna.ComplexityWeights, testContextPostEtna.GasPrice, ) @@ -160,7 +159,7 @@ var ( type environment struct { name string context *builder.Context - feeCalculator txfee.Calculator + feeCalculator fee.Calculator memo []byte } @@ -761,7 +760,7 @@ func makeTestUTXOs(utxosKey *secp256k1.PrivateKey) []*avax.UTXO { // and verifies that the burned amount is exactly the required fee. func requireFeeIsCorrect( require *require.Assertions, - feeCalculator txfee.Calculator, + feeCalculator fee.Calculator, utx txs.UnsignedTx, baseTx *avax.BaseTx, additionalIns []*avax.TransferableInput, From 5a573bca66bba6dd852f8bf82ce9302cf11c38cd Mon Sep 17 00:00:00 2001 From: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> Date: Thu, 22 Aug 2024 13:11:24 -0400 Subject: [PATCH 38/69] Remove mocks for `Staker` and `ScheduledStaker` (#3322) --- scripts/mocks.mockgen.source.txt | 2 +- vms/platformvm/signer/mock_signer.go | 68 +++++++ vms/platformvm/state/staker_test.go | 130 ++++++------- vms/platformvm/txs/mock_staker_tx.go | 265 --------------------------- 4 files changed, 135 insertions(+), 330 deletions(-) create mode 100644 vms/platformvm/signer/mock_signer.go delete mode 100644 vms/platformvm/txs/mock_staker_tx.go diff --git a/scripts/mocks.mockgen.source.txt b/scripts/mocks.mockgen.source.txt index ba562d2e3c49..167c77ce5cc8 100644 --- a/scripts/mocks.mockgen.source.txt +++ b/scripts/mocks.mockgen.source.txt @@ -4,6 +4,6 @@ snow/networking/sender/external_sender.go==snow/networking/sender/mock_external_ vms/avm/block/executor/manager.go==vms/avm/block/executor/mock_manager.go vms/avm/txs/tx.go==vms/avm/txs/mock_unsigned_tx.go vms/platformvm/block/executor/manager.go==vms/platformvm/block/executor/mock_manager.go -vms/platformvm/txs/staker_tx.go=ValidatorTx,DelegatorTx,StakerTx,PermissionlessStaker=vms/platformvm/txs/mock_staker_tx.go vms/platformvm/txs/unsigned_tx.go==vms/platformvm/txs/mock_unsigned_tx.go +vms/platformvm/signer/signer.go==vms/platformvm/signer/mock_signer.go x/merkledb/db.go=ChangeProofer,RangeProofer,Clearer,Prefetcher=x/merkledb/mock_db.go diff --git a/vms/platformvm/signer/mock_signer.go b/vms/platformvm/signer/mock_signer.go new file mode 100644 index 000000000000..04c5100e9488 --- /dev/null +++ b/vms/platformvm/signer/mock_signer.go @@ -0,0 +1,68 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: vms/platformvm/signer/signer.go +// +// Generated by this command: +// +// mockgen -source=vms/platformvm/signer/signer.go -destination=vms/platformvm/signer/mock_signer.go -package=signer -exclude_interfaces= +// + +// Package signer is a generated GoMock package. +package signer + +import ( + reflect "reflect" + + bls "github.com/ava-labs/avalanchego/utils/crypto/bls" + gomock "go.uber.org/mock/gomock" +) + +// MockSigner is a mock of Signer interface. +type MockSigner struct { + ctrl *gomock.Controller + recorder *MockSignerMockRecorder +} + +// MockSignerMockRecorder is the mock recorder for MockSigner. +type MockSignerMockRecorder struct { + mock *MockSigner +} + +// NewMockSigner creates a new mock instance. +func NewMockSigner(ctrl *gomock.Controller) *MockSigner { + mock := &MockSigner{ctrl: ctrl} + mock.recorder = &MockSignerMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockSigner) EXPECT() *MockSignerMockRecorder { + return m.recorder +} + +// Key mocks base method. +func (m *MockSigner) Key() *bls.PublicKey { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Key") + ret0, _ := ret[0].(*bls.PublicKey) + return ret0 +} + +// Key indicates an expected call of Key. +func (mr *MockSignerMockRecorder) Key() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Key", reflect.TypeOf((*MockSigner)(nil).Key)) +} + +// Verify mocks base method. +func (m *MockSigner) Verify() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Verify") + ret0, _ := ret[0].(error) + return ret0 +} + +// Verify indicates an expected call of Verify. +func (mr *MockSignerMockRecorder) Verify() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockSigner)(nil).Verify)) +} diff --git a/vms/platformvm/state/staker_test.go b/vms/platformvm/state/staker_test.go index d1ac10f981b5..579d61cc841d 100644 --- a/vms/platformvm/state/staker_test.go +++ b/vms/platformvm/state/staker_test.go @@ -13,6 +13,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) @@ -133,43 +134,34 @@ func TestStakerLess(t *testing.T) { func TestNewCurrentStaker(t *testing.T) { require := require.New(t) - ctrl := gomock.NewController(t) + stakerTx := generateStakerTx(require) txID := ids.GenerateTestID() - nodeID := ids.GenerateTestNodeID() - sk, err := bls.NewSecretKey() - require.NoError(err) - publicKey := bls.PublicFromSecretKey(sk) - subnetID := ids.GenerateTestID() - weight := uint64(12345) - startTime := time.Now() - endTime := startTime.Add(time.Hour) - potentialReward := uint64(54321) - currentPriority := txs.SubnetPermissionedValidatorCurrentPriority - - stakerTx := txs.NewMockStaker(ctrl) - stakerTx.EXPECT().EndTime().Return(endTime) - stakerTx.EXPECT().NodeID().Return(nodeID) - stakerTx.EXPECT().PublicKey().Return(publicKey, true, nil) - stakerTx.EXPECT().SubnetID().Return(subnetID) - stakerTx.EXPECT().Weight().Return(weight) - stakerTx.EXPECT().CurrentPriority().Return(currentPriority) + startTime := stakerTx.StartTime().Add(2 * time.Hour) + potentialReward := uint64(12345) staker, err := NewCurrentStaker(txID, stakerTx, startTime, potentialReward) - require.NotNil(staker) require.NoError(err) - require.Equal(txID, staker.TxID) - require.Equal(nodeID, staker.NodeID) - require.Equal(publicKey, staker.PublicKey) - require.Equal(subnetID, staker.SubnetID) - require.Equal(weight, staker.Weight) - require.Equal(startTime, staker.StartTime) - require.Equal(endTime, staker.EndTime) - require.Equal(potentialReward, staker.PotentialReward) - require.Equal(endTime, staker.NextTime) - require.Equal(currentPriority, staker.Priority) - - stakerTx.EXPECT().PublicKey().Return(nil, false, errCustom) + publicKey, isNil, err := stakerTx.PublicKey() + require.NoError(err) + require.True(isNil) + require.Equal(&Staker{ + TxID: txID, + NodeID: stakerTx.NodeID(), + PublicKey: publicKey, + SubnetID: stakerTx.SubnetID(), + Weight: stakerTx.Weight(), + StartTime: startTime, + EndTime: stakerTx.EndTime(), + PotentialReward: potentialReward, + NextTime: stakerTx.EndTime(), + Priority: stakerTx.CurrentPriority(), + }, staker) + + ctrl := gomock.NewController(t) + signer := signer.NewMockSigner(ctrl) + signer.EXPECT().Verify().Return(errCustom) + stakerTx.Signer = signer _, err = NewCurrentStaker(txID, stakerTx, startTime, potentialReward) require.ErrorIs(err, errCustom) @@ -177,44 +169,54 @@ func TestNewCurrentStaker(t *testing.T) { func TestNewPendingStaker(t *testing.T) { require := require.New(t) - ctrl := gomock.NewController(t) + + stakerTx := generateStakerTx(require) txID := ids.GenerateTestID() + staker, err := NewPendingStaker(txID, stakerTx) + require.NoError(err) + publicKey, isNil, err := stakerTx.PublicKey() + require.NoError(err) + require.True(isNil) + require.Equal(&Staker{ + TxID: txID, + NodeID: stakerTx.NodeID(), + PublicKey: publicKey, + SubnetID: stakerTx.SubnetID(), + Weight: stakerTx.Weight(), + StartTime: stakerTx.StartTime(), + EndTime: stakerTx.EndTime(), + NextTime: stakerTx.StartTime(), + Priority: stakerTx.PendingPriority(), + }, staker) + + ctrl := gomock.NewController(t) + signer := signer.NewMockSigner(ctrl) + signer.EXPECT().Verify().Return(errCustom) + stakerTx.Signer = signer + + _, err = NewPendingStaker(txID, stakerTx) + require.ErrorIs(err, errCustom) +} + +func generateStakerTx(require *require.Assertions) *txs.AddPermissionlessValidatorTx { nodeID := ids.GenerateTestNodeID() sk, err := bls.NewSecretKey() require.NoError(err) - publicKey := bls.PublicFromSecretKey(sk) + pop := signer.NewProofOfPossession(sk) subnetID := ids.GenerateTestID() weight := uint64(12345) - startTime := time.Now() - endTime := time.Now() - pendingPriority := txs.SubnetPermissionedValidatorPendingPriority - - stakerTx := txs.NewMockScheduledStaker(ctrl) - stakerTx.EXPECT().NodeID().Return(nodeID) - stakerTx.EXPECT().PublicKey().Return(publicKey, true, nil) - stakerTx.EXPECT().SubnetID().Return(subnetID) - stakerTx.EXPECT().Weight().Return(weight) - stakerTx.EXPECT().StartTime().Return(startTime) - stakerTx.EXPECT().EndTime().Return(endTime) - stakerTx.EXPECT().PendingPriority().Return(pendingPriority) - - staker, err := NewPendingStaker(txID, stakerTx) - require.NotNil(staker) - require.NoError(err) - require.Equal(txID, staker.TxID) - require.Equal(nodeID, staker.NodeID) - require.Equal(publicKey, staker.PublicKey) - require.Equal(subnetID, staker.SubnetID) - require.Equal(weight, staker.Weight) - require.Equal(startTime, staker.StartTime) - require.Equal(endTime, staker.EndTime) - require.Zero(staker.PotentialReward) - require.Equal(startTime, staker.NextTime) - require.Equal(pendingPriority, staker.Priority) - - stakerTx.EXPECT().PublicKey().Return(nil, false, errCustom) + startTime := time.Now().Truncate(time.Second) + endTime := startTime.Add(time.Hour) - _, err = NewPendingStaker(txID, stakerTx) - require.ErrorIs(err, errCustom) + return &txs.AddPermissionlessValidatorTx{ + Validator: txs.Validator{ + NodeID: nodeID, + Start: uint64(startTime.Unix()), + End: uint64(endTime.Unix()), + Wght: weight, + }, + Signer: pop, + Subnet: subnetID, + } } diff --git a/vms/platformvm/txs/mock_staker_tx.go b/vms/platformvm/txs/mock_staker_tx.go deleted file mode 100644 index 2e01b15b3813..000000000000 --- a/vms/platformvm/txs/mock_staker_tx.go +++ /dev/null @@ -1,265 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: vms/platformvm/txs/staker_tx.go -// -// Generated by this command: -// -// mockgen -source=vms/platformvm/txs/staker_tx.go -destination=vms/platformvm/txs/mock_staker_tx.go -package=txs -exclude_interfaces=ValidatorTx,DelegatorTx,StakerTx,PermissionlessStaker -// - -// Package txs is a generated GoMock package. -package txs - -import ( - reflect "reflect" - time "time" - - ids "github.com/ava-labs/avalanchego/ids" - bls "github.com/ava-labs/avalanchego/utils/crypto/bls" - gomock "go.uber.org/mock/gomock" -) - -// MockStaker is a mock of Staker interface. -type MockStaker struct { - ctrl *gomock.Controller - recorder *MockStakerMockRecorder -} - -// MockStakerMockRecorder is the mock recorder for MockStaker. -type MockStakerMockRecorder struct { - mock *MockStaker -} - -// NewMockStaker creates a new mock instance. -func NewMockStaker(ctrl *gomock.Controller) *MockStaker { - mock := &MockStaker{ctrl: ctrl} - mock.recorder = &MockStakerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockStaker) EXPECT() *MockStakerMockRecorder { - return m.recorder -} - -// CurrentPriority mocks base method. -func (m *MockStaker) CurrentPriority() Priority { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CurrentPriority") - ret0, _ := ret[0].(Priority) - return ret0 -} - -// CurrentPriority indicates an expected call of CurrentPriority. -func (mr *MockStakerMockRecorder) CurrentPriority() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CurrentPriority", reflect.TypeOf((*MockStaker)(nil).CurrentPriority)) -} - -// EndTime mocks base method. -func (m *MockStaker) EndTime() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "EndTime") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// EndTime indicates an expected call of EndTime. -func (mr *MockStakerMockRecorder) EndTime() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EndTime", reflect.TypeOf((*MockStaker)(nil).EndTime)) -} - -// NodeID mocks base method. -func (m *MockStaker) NodeID() ids.NodeID { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NodeID") - ret0, _ := ret[0].(ids.NodeID) - return ret0 -} - -// NodeID indicates an expected call of NodeID. -func (mr *MockStakerMockRecorder) NodeID() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NodeID", reflect.TypeOf((*MockStaker)(nil).NodeID)) -} - -// PublicKey mocks base method. -func (m *MockStaker) PublicKey() (*bls.PublicKey, bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PublicKey") - ret0, _ := ret[0].(*bls.PublicKey) - ret1, _ := ret[1].(bool) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// PublicKey indicates an expected call of PublicKey. -func (mr *MockStakerMockRecorder) PublicKey() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PublicKey", reflect.TypeOf((*MockStaker)(nil).PublicKey)) -} - -// SubnetID mocks base method. -func (m *MockStaker) SubnetID() ids.ID { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SubnetID") - ret0, _ := ret[0].(ids.ID) - return ret0 -} - -// SubnetID indicates an expected call of SubnetID. -func (mr *MockStakerMockRecorder) SubnetID() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubnetID", reflect.TypeOf((*MockStaker)(nil).SubnetID)) -} - -// Weight mocks base method. -func (m *MockStaker) Weight() uint64 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Weight") - ret0, _ := ret[0].(uint64) - return ret0 -} - -// Weight indicates an expected call of Weight. -func (mr *MockStakerMockRecorder) Weight() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Weight", reflect.TypeOf((*MockStaker)(nil).Weight)) -} - -// MockScheduledStaker is a mock of ScheduledStaker interface. -type MockScheduledStaker struct { - ctrl *gomock.Controller - recorder *MockScheduledStakerMockRecorder -} - -// MockScheduledStakerMockRecorder is the mock recorder for MockScheduledStaker. -type MockScheduledStakerMockRecorder struct { - mock *MockScheduledStaker -} - -// NewMockScheduledStaker creates a new mock instance. -func NewMockScheduledStaker(ctrl *gomock.Controller) *MockScheduledStaker { - mock := &MockScheduledStaker{ctrl: ctrl} - mock.recorder = &MockScheduledStakerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockScheduledStaker) EXPECT() *MockScheduledStakerMockRecorder { - return m.recorder -} - -// CurrentPriority mocks base method. -func (m *MockScheduledStaker) CurrentPriority() Priority { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CurrentPriority") - ret0, _ := ret[0].(Priority) - return ret0 -} - -// CurrentPriority indicates an expected call of CurrentPriority. -func (mr *MockScheduledStakerMockRecorder) CurrentPriority() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CurrentPriority", reflect.TypeOf((*MockScheduledStaker)(nil).CurrentPriority)) -} - -// EndTime mocks base method. -func (m *MockScheduledStaker) EndTime() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "EndTime") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// EndTime indicates an expected call of EndTime. -func (mr *MockScheduledStakerMockRecorder) EndTime() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EndTime", reflect.TypeOf((*MockScheduledStaker)(nil).EndTime)) -} - -// NodeID mocks base method. -func (m *MockScheduledStaker) NodeID() ids.NodeID { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "NodeID") - ret0, _ := ret[0].(ids.NodeID) - return ret0 -} - -// NodeID indicates an expected call of NodeID. -func (mr *MockScheduledStakerMockRecorder) NodeID() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NodeID", reflect.TypeOf((*MockScheduledStaker)(nil).NodeID)) -} - -// PendingPriority mocks base method. -func (m *MockScheduledStaker) PendingPriority() Priority { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PendingPriority") - ret0, _ := ret[0].(Priority) - return ret0 -} - -// PendingPriority indicates an expected call of PendingPriority. -func (mr *MockScheduledStakerMockRecorder) PendingPriority() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PendingPriority", reflect.TypeOf((*MockScheduledStaker)(nil).PendingPriority)) -} - -// PublicKey mocks base method. -func (m *MockScheduledStaker) PublicKey() (*bls.PublicKey, bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PublicKey") - ret0, _ := ret[0].(*bls.PublicKey) - ret1, _ := ret[1].(bool) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// PublicKey indicates an expected call of PublicKey. -func (mr *MockScheduledStakerMockRecorder) PublicKey() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PublicKey", reflect.TypeOf((*MockScheduledStaker)(nil).PublicKey)) -} - -// StartTime mocks base method. -func (m *MockScheduledStaker) StartTime() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "StartTime") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// StartTime indicates an expected call of StartTime. -func (mr *MockScheduledStakerMockRecorder) StartTime() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StartTime", reflect.TypeOf((*MockScheduledStaker)(nil).StartTime)) -} - -// SubnetID mocks base method. -func (m *MockScheduledStaker) SubnetID() ids.ID { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SubnetID") - ret0, _ := ret[0].(ids.ID) - return ret0 -} - -// SubnetID indicates an expected call of SubnetID. -func (mr *MockScheduledStakerMockRecorder) SubnetID() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubnetID", reflect.TypeOf((*MockScheduledStaker)(nil).SubnetID)) -} - -// Weight mocks base method. -func (m *MockScheduledStaker) Weight() uint64 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Weight") - ret0, _ := ret[0].(uint64) - return ret0 -} - -// Weight indicates an expected call of Weight. -func (mr *MockScheduledStakerMockRecorder) Weight() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Weight", reflect.TypeOf((*MockScheduledStaker)(nil).Weight)) -} From ef3b7b5aed9878a6a7f0b48d6448a4124f985608 Mon Sep 17 00:00:00 2001 From: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> Date: Thu, 22 Aug 2024 13:42:48 -0400 Subject: [PATCH 39/69] Move most mocks to sub-dirs (#3323) --- api/admin/service_test.go | 12 +- api/info/service_test.go | 6 +- .../{mock_server.go => servermock/server.go} | 70 +- .../shared_memory.go} | 47 +- .../{mock_manager.go => codecmock/manager.go} | 53 +- database/corruptabledb/db_test.go | 5 +- .../{mock_batch.go => databasemock/batch.go} | 73 +- .../iterator.go} | 58 +- database/dbtest/dbtest.go | 7 +- indexer/indexer_test.go | 12 +- .../outbound_message.go} | 55 +- .../messagemock/outbound_message_builder.go | 405 +++++ message/mock_outbound_message_builder.go | 404 ----- network/p2p/validators_test.go | 5 +- .../inbound_resource_throttler_test.go | 11 +- .../throttling/outbound_msg_throttler_test.go | 9 +- node/beacon_manager_test.go | 4 +- scripts/lint.sh | 2 +- scripts/mock.gen.sh | 15 +- scripts/mocks.mockgen.source.txt | 24 +- scripts/mocks.mockgen.txt | 88 +- .../mock_block.go => snowmanmock/block.go} | 76 +- .../linearizable_vm.go} | 148 +- snow/engine/common/commonmock/sender.go | 279 ++++ snow/engine/common/mock_sender.go | 278 ---- .../build_block_with_context_chain_vm.go | 57 + .../chain_vm.go} | 136 +- .../block/blockmock/state_syncable_vm.go | 116 ++ .../block/blockmock/with_verify_context.go | 70 + .../block/mock_build_block_with_context_vm.go | 56 - .../snowman/block/mock_state_syncable_vm.go | 115 -- .../snowman/block/mock_with_verify_context.go | 69 - snow/engine/snowman/getter/getter_test.go | 8 +- snow/networking/handler/handler_test.go | 3 +- .../handler.go} | 109 +- snow/networking/handler/message_queue_test.go | 4 +- snow/networking/router/chain_router_test.go | 5 +- .../{mock_router.go => routermock/router.go} | 89 +- .../networking/sender/mock_external_sender.go | 58 - snow/networking/sender/sender_test.go | 80 +- .../sender/sendermock/external_sender.go | 58 + .../manager.go} | 82 +- snow/networking/tracker/mock_targeter.go | 54 - .../tracker/resource_tracker_test.go | 3 +- snow/networking/tracker/targeter_test.go | 5 +- .../tracker/trackermock/targeter.go | 54 + .../tracker.go} | 46 +- snow/uptime/locked_calculator_test.go | 3 +- .../calculator.go} | 46 +- .../gvalidators/validator_state_test.go | 5 +- snow/validators/mock_subnet_connector.go | 55 - .../state.go} | 55 +- .../validatorsmock/subnet_connector.go | 55 + utils/crypto/keychain/keychain_test.go | 53 +- .../ledger.go} | 64 +- utils/filesystem/filesystemmock/reader.go | 55 + utils/filesystem/mock_io.go | 55 - utils/hashing/consistent/ring_test.go | 6 +- utils/hashing/hashingmock/hasher.go | 53 + utils/hashing/mock_hasher.go | 53 - .../{mock_user.go => resourcemock/user.go} | 46 +- vms/avm/block/builder/builder_test.go | 69 +- vms/avm/block/executor/block_test.go | 126 +- .../manager.go} | 82 +- vms/avm/block/executor/manager_test.go | 23 +- vms/avm/block/mock_block.go | 20 +- .../metrics.go} | 70 +- vms/avm/network/network_test.go | 40 +- vms/avm/service_test.go | 46 +- vms/avm/state/mock_state.go | 711 --------- vms/avm/state/statemock/chain.go | 204 +++ vms/avm/state/statemock/diff.go | 217 +++ vms/avm/state/statemock/state.go | 333 ++++ .../txs/executor/semantic_verifier_test.go | 55 +- .../mempool.go} | 82 +- .../{mock_unsigned_tx.go => txsmock/tx.go} | 71 +- .../transferable_in.go} | 52 +- .../avax/avaxmock/transferable_out.go | 95 ++ vms/components/avax/mock_transferable_out.go | 95 -- vms/components/verify/mock_verifiable.go | 53 - vms/components/verify/subnet_test.go | 10 +- .../verify/verifymock/verifiable.go | 53 + vms/mock_manager.go | 224 --- vms/platformvm/block/builder/builder_test.go | 15 +- .../block/executor/acceptor_test.go | 48 +- vms/platformvm/block/executor/backend_test.go | 3 +- vms/platformvm/block/executor/block_test.go | 22 +- .../manager.go} | 82 +- .../block/executor/proposal_block_test.go | 5 +- .../block/executor/rejector_test.go | 4 +- .../block/executor/standard_block_test.go | 5 +- .../block/executor/verifier_test.go | 66 +- vms/platformvm/block/mock_block.go | 28 +- vms/platformvm/fx/fxmock/fx.go | 124 ++ vms/platformvm/fx/fxmock/owner.go | 83 + vms/platformvm/fx/mock_fx.go | 191 --- vms/platformvm/network/gossip_test.go | 11 +- vms/platformvm/network/network_test.go | 26 +- vms/platformvm/service_test.go | 13 +- .../{mock_signer.go => signermock/signer.go} | 40 +- .../stakeable/stakeable_lock_test.go | 9 +- vms/platformvm/state/diff_test.go | 17 +- vms/platformvm/state/mock_staker_iterator.go | 4 +- vms/platformvm/state/mock_state.go | 1390 +++-------------- vms/platformvm/state/staker_test.go | 5 +- vms/platformvm/state/state_test.go | 6 +- vms/platformvm/state/statemock/chain.go | 526 +++++++ vms/platformvm/state/statemock/diff.go | 540 +++++++ .../add_permissionless_delegator_tx_test.go | 21 +- .../add_permissionless_validator_tx_test.go | 23 +- .../executor/staker_tx_verification_test.go | 45 +- .../txs/executor/standard_tx_executor_test.go | 61 +- .../mempool.go} | 82 +- .../txs/remove_subnet_validator_tx_test.go | 6 +- .../txs/transfer_subnet_ownership_tx_test.go | 10 +- .../txs/transform_subnet_tx_test.go | 6 +- .../unsigned_tx.go} | 71 +- vms/platformvm/utxo/mock_verifier.go | 71 - vms/platformvm/utxo/utxomock/verifier.go | 71 + vms/platformvm/warp/signature_test.go | 33 +- vms/platformvm/warp/validator_test.go | 9 +- vms/proposervm/block_test.go | 28 +- vms/proposervm/mock_post_fork_block.go | 28 +- vms/proposervm/pre_fork_block_test.go | 13 +- vms/proposervm/proposer/mock_windower.go | 102 -- .../proposer/proposermock/windower.go | 102 ++ vms/proposervm/scheduler/mock_scheduler.go | 76 - .../scheduler/schedulermock/scheduler.go | 76 + .../{mock_state.go => statemock/state.go} | 100 +- vms/proposervm/vm_test.go | 54 +- vms/registry/mock_vm_getter.go | 57 - vms/registry/mock_vm_registry.go | 57 - vms/registry/registrymock/vm_getter.go | 57 + vms/registry/registrymock/vm_registry.go | 57 + vms/registry/vm_getter_test.go | 12 +- vms/registry/vm_registry_test.go | 26 +- vms/rpcchainvm/batched_vm_test.go | 9 +- vms/rpcchainvm/state_syncable_vm_test.go | 89 +- vms/rpcchainvm/vm_test.go | 3 +- vms/rpcchainvm/with_context_vm_test.go | 45 +- vms/vmsmock/factory.go | 55 + vms/vmsmock/manager.go | 186 +++ x/merkledb/mock_db.go | 2 +- x/sync/client_test.go | 13 +- x/sync/mock_client.go | 20 +- x/sync/network_server_test.go | 10 +- .../network_client.go} | 64 +- 147 files changed, 6038 insertions(+), 5833 deletions(-) rename api/server/{mock_server.go => servermock/server.go} (56%) rename chains/atomic/{mock_shared_memory.go => atomicmock/shared_memory.go} (50%) rename codec/{mock_manager.go => codecmock/manager.go} (52%) rename database/{mock_batch.go => databasemock/batch.go} (55%) rename database/{mock_iterator.go => databasemock/iterator.go} (54%) rename message/{mock_message.go => messagemock/outbound_message.go} (50%) create mode 100644 message/messagemock/outbound_message_builder.go delete mode 100644 message/mock_outbound_message_builder.go rename snow/consensus/snowman/{snowmantest/mock_block.go => snowmanmock/block.go} (58%) rename snow/engine/avalanche/vertex/{mock_vm.go => vertexmock/linearizable_vm.go} (54%) create mode 100644 snow/engine/common/commonmock/sender.go delete mode 100644 snow/engine/common/mock_sender.go create mode 100644 snow/engine/snowman/block/blockmock/build_block_with_context_chain_vm.go rename snow/engine/snowman/block/{mock_chain_vm.go => blockmock/chain_vm.go} (56%) create mode 100644 snow/engine/snowman/block/blockmock/state_syncable_vm.go create mode 100644 snow/engine/snowman/block/blockmock/with_verify_context.go delete mode 100644 snow/engine/snowman/block/mock_build_block_with_context_vm.go delete mode 100644 snow/engine/snowman/block/mock_state_syncable_vm.go delete mode 100644 snow/engine/snowman/block/mock_with_verify_context.go rename snow/networking/handler/{mock_handler.go => handlermock/handler.go} (55%) rename snow/networking/router/{mock_router.go => routermock/router.go} (51%) delete mode 100644 snow/networking/sender/mock_external_sender.go create mode 100644 snow/networking/sender/sendermock/external_sender.go rename snow/networking/timeout/{mock_manager.go => timeoutmock/manager.go} (53%) delete mode 100644 snow/networking/tracker/mock_targeter.go create mode 100644 snow/networking/tracker/trackermock/targeter.go rename snow/networking/tracker/{mock_resource_tracker.go => trackermock/tracker.go} (50%) rename snow/uptime/{mock_calculator.go => uptimemock/calculator.go} (50%) delete mode 100644 snow/validators/mock_subnet_connector.go rename snow/validators/{mock_state.go => validatorsmock/state.go} (51%) create mode 100644 snow/validators/validatorsmock/subnet_connector.go rename utils/crypto/keychain/{mock_ledger.go => keychainmock/ledger.go} (56%) create mode 100644 utils/filesystem/filesystemmock/reader.go delete mode 100644 utils/filesystem/mock_io.go create mode 100644 utils/hashing/hashingmock/hasher.go delete mode 100644 utils/hashing/mock_hasher.go rename utils/resource/{mock_user.go => resourcemock/user.go} (53%) rename vms/avm/block/executor/{mock_manager.go => executormock/manager.go} (59%) rename vms/avm/metrics/{mock_metrics.go => metricsmock/metrics.go} (55%) delete mode 100644 vms/avm/state/mock_state.go create mode 100644 vms/avm/state/statemock/chain.go create mode 100644 vms/avm/state/statemock/diff.go create mode 100644 vms/avm/state/statemock/state.go rename vms/avm/txs/mempool/{mock_mempool.go => mempoolmock/mempool.go} (57%) rename vms/avm/txs/{mock_unsigned_tx.go => txsmock/tx.go} (55%) rename vms/components/avax/{mock_transferable_in.go => avaxmock/transferable_in.go} (50%) create mode 100644 vms/components/avax/avaxmock/transferable_out.go delete mode 100644 vms/components/avax/mock_transferable_out.go delete mode 100644 vms/components/verify/mock_verifiable.go create mode 100644 vms/components/verify/verifymock/verifiable.go delete mode 100644 vms/mock_manager.go rename vms/platformvm/block/executor/{mock_manager.go => executormock/manager.go} (59%) create mode 100644 vms/platformvm/fx/fxmock/fx.go create mode 100644 vms/platformvm/fx/fxmock/owner.go delete mode 100644 vms/platformvm/fx/mock_fx.go rename vms/platformvm/signer/{mock_signer.go => signermock/signer.go} (52%) create mode 100644 vms/platformvm/state/statemock/chain.go create mode 100644 vms/platformvm/state/statemock/diff.go rename vms/platformvm/txs/mempool/{mock_mempool.go => mempoolmock/mempool.go} (56%) rename vms/platformvm/txs/{mock_unsigned_tx.go => txsmock/unsigned_tx.go} (56%) delete mode 100644 vms/platformvm/utxo/mock_verifier.go create mode 100644 vms/platformvm/utxo/utxomock/verifier.go delete mode 100644 vms/proposervm/proposer/mock_windower.go create mode 100644 vms/proposervm/proposer/proposermock/windower.go delete mode 100644 vms/proposervm/scheduler/mock_scheduler.go create mode 100644 vms/proposervm/scheduler/schedulermock/scheduler.go rename vms/proposervm/state/{mock_state.go => statemock/state.go} (59%) delete mode 100644 vms/registry/mock_vm_getter.go delete mode 100644 vms/registry/mock_vm_registry.go create mode 100644 vms/registry/registrymock/vm_getter.go create mode 100644 vms/registry/registrymock/vm_registry.go create mode 100644 vms/vmsmock/factory.go create mode 100644 vms/vmsmock/manager.go rename x/sync/{mock_network_client.go => syncmock/network_client.go} (50%) diff --git a/api/admin/service_test.go b/api/admin/service_test.go index 936e7107dbdb..476f09153927 100644 --- a/api/admin/service_test.go +++ b/api/admin/service_test.go @@ -14,8 +14,8 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/formatting" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/vms" - "github.com/ava-labs/avalanchego/vms/registry" + "github.com/ava-labs/avalanchego/vms/registry/registrymock" + "github.com/ava-labs/avalanchego/vms/vmsmock" rpcdbpb "github.com/ava-labs/avalanchego/proto/pb/rpcdb" ) @@ -23,15 +23,15 @@ import ( type loadVMsTest struct { admin *Admin ctrl *gomock.Controller - mockVMManager *vms.MockManager - mockVMRegistry *registry.MockVMRegistry + mockVMManager *vmsmock.Manager + mockVMRegistry *registrymock.VMRegistry } func initLoadVMsTest(t *testing.T) *loadVMsTest { ctrl := gomock.NewController(t) - mockVMRegistry := registry.NewMockVMRegistry(ctrl) - mockVMManager := vms.NewMockManager(ctrl) + mockVMRegistry := registrymock.NewVMRegistry(ctrl) + mockVMManager := vmsmock.NewManager(ctrl) return &loadVMsTest{ admin: &Admin{Config: Config{ diff --git a/api/info/service_test.go b/api/info/service_test.go index 95b7767ab5db..70bf9bfb49bc 100644 --- a/api/info/service_test.go +++ b/api/info/service_test.go @@ -12,7 +12,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/vms" + "github.com/ava-labs/avalanchego/vms/vmsmock" ) var errTest = errors.New("non-nil error") @@ -20,12 +20,12 @@ var errTest = errors.New("non-nil error") type getVMsTest struct { info *Info ctrl *gomock.Controller - mockVMManager *vms.MockManager + mockVMManager *vmsmock.Manager } func initGetVMsTest(t *testing.T) *getVMsTest { ctrl := gomock.NewController(t) - mockVMManager := vms.NewMockManager(ctrl) + mockVMManager := vmsmock.NewManager(ctrl) return &getVMsTest{ info: &Info{ Parameters: Parameters{ diff --git a/api/server/mock_server.go b/api/server/servermock/server.go similarity index 56% rename from api/server/mock_server.go rename to api/server/servermock/server.go index 769df9baa26f..f17939f2fb4f 100644 --- a/api/server/mock_server.go +++ b/api/server/servermock/server.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=server -destination=api/server/mock_server.go github.com/ava-labs/avalanchego/api/server Server +// mockgen -package=servermock -destination=api/server/servermock/server.go -mock_names=Server=Server github.com/ava-labs/avalanchego/api/server Server // -// Package server is a generated GoMock package. -package server +// Package servermock is a generated GoMock package. +package servermock import ( http "net/http" @@ -18,31 +18,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockServer is a mock of Server interface. -type MockServer struct { +// Server is a mock of Server interface. +type Server struct { ctrl *gomock.Controller - recorder *MockServerMockRecorder + recorder *ServerMockRecorder } -// MockServerMockRecorder is the mock recorder for MockServer. -type MockServerMockRecorder struct { - mock *MockServer +// ServerMockRecorder is the mock recorder for Server. +type ServerMockRecorder struct { + mock *Server } -// NewMockServer creates a new mock instance. -func NewMockServer(ctrl *gomock.Controller) *MockServer { - mock := &MockServer{ctrl: ctrl} - mock.recorder = &MockServerMockRecorder{mock} +// NewServer creates a new mock instance. +func NewServer(ctrl *gomock.Controller) *Server { + mock := &Server{ctrl: ctrl} + mock.recorder = &ServerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockServer) EXPECT() *MockServerMockRecorder { +func (m *Server) EXPECT() *ServerMockRecorder { return m.recorder } // AddAliases mocks base method. -func (m *MockServer) AddAliases(arg0 string, arg1 ...string) error { +func (m *Server) AddAliases(arg0 string, arg1 ...string) error { m.ctrl.T.Helper() varargs := []any{arg0} for _, a := range arg1 { @@ -54,14 +54,14 @@ func (m *MockServer) AddAliases(arg0 string, arg1 ...string) error { } // AddAliases indicates an expected call of AddAliases. -func (mr *MockServerMockRecorder) AddAliases(arg0 any, arg1 ...any) *gomock.Call { +func (mr *ServerMockRecorder) AddAliases(arg0 any, arg1 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{arg0}, arg1...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddAliases", reflect.TypeOf((*MockServer)(nil).AddAliases), varargs...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddAliases", reflect.TypeOf((*Server)(nil).AddAliases), varargs...) } // AddAliasesWithReadLock mocks base method. -func (m *MockServer) AddAliasesWithReadLock(arg0 string, arg1 ...string) error { +func (m *Server) AddAliasesWithReadLock(arg0 string, arg1 ...string) error { m.ctrl.T.Helper() varargs := []any{arg0} for _, a := range arg1 { @@ -73,14 +73,14 @@ func (m *MockServer) AddAliasesWithReadLock(arg0 string, arg1 ...string) error { } // AddAliasesWithReadLock indicates an expected call of AddAliasesWithReadLock. -func (mr *MockServerMockRecorder) AddAliasesWithReadLock(arg0 any, arg1 ...any) *gomock.Call { +func (mr *ServerMockRecorder) AddAliasesWithReadLock(arg0 any, arg1 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{arg0}, arg1...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddAliasesWithReadLock", reflect.TypeOf((*MockServer)(nil).AddAliasesWithReadLock), varargs...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddAliasesWithReadLock", reflect.TypeOf((*Server)(nil).AddAliasesWithReadLock), varargs...) } // AddRoute mocks base method. -func (m *MockServer) AddRoute(arg0 http.Handler, arg1, arg2 string) error { +func (m *Server) AddRoute(arg0 http.Handler, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddRoute", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -88,13 +88,13 @@ func (m *MockServer) AddRoute(arg0 http.Handler, arg1, arg2 string) error { } // AddRoute indicates an expected call of AddRoute. -func (mr *MockServerMockRecorder) AddRoute(arg0, arg1, arg2 any) *gomock.Call { +func (mr *ServerMockRecorder) AddRoute(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRoute", reflect.TypeOf((*MockServer)(nil).AddRoute), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRoute", reflect.TypeOf((*Server)(nil).AddRoute), arg0, arg1, arg2) } // AddRouteWithReadLock mocks base method. -func (m *MockServer) AddRouteWithReadLock(arg0 http.Handler, arg1, arg2 string) error { +func (m *Server) AddRouteWithReadLock(arg0 http.Handler, arg1, arg2 string) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AddRouteWithReadLock", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -102,13 +102,13 @@ func (m *MockServer) AddRouteWithReadLock(arg0 http.Handler, arg1, arg2 string) } // AddRouteWithReadLock indicates an expected call of AddRouteWithReadLock. -func (mr *MockServerMockRecorder) AddRouteWithReadLock(arg0, arg1, arg2 any) *gomock.Call { +func (mr *ServerMockRecorder) AddRouteWithReadLock(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRouteWithReadLock", reflect.TypeOf((*MockServer)(nil).AddRouteWithReadLock), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRouteWithReadLock", reflect.TypeOf((*Server)(nil).AddRouteWithReadLock), arg0, arg1, arg2) } // Dispatch mocks base method. -func (m *MockServer) Dispatch() error { +func (m *Server) Dispatch() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Dispatch") ret0, _ := ret[0].(error) @@ -116,25 +116,25 @@ func (m *MockServer) Dispatch() error { } // Dispatch indicates an expected call of Dispatch. -func (mr *MockServerMockRecorder) Dispatch() *gomock.Call { +func (mr *ServerMockRecorder) Dispatch() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dispatch", reflect.TypeOf((*MockServer)(nil).Dispatch)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dispatch", reflect.TypeOf((*Server)(nil).Dispatch)) } // RegisterChain mocks base method. -func (m *MockServer) RegisterChain(arg0 string, arg1 *snow.ConsensusContext, arg2 common.VM) { +func (m *Server) RegisterChain(arg0 string, arg1 *snow.ConsensusContext, arg2 common.VM) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterChain", arg0, arg1, arg2) } // RegisterChain indicates an expected call of RegisterChain. -func (mr *MockServerMockRecorder) RegisterChain(arg0, arg1, arg2 any) *gomock.Call { +func (mr *ServerMockRecorder) RegisterChain(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterChain", reflect.TypeOf((*MockServer)(nil).RegisterChain), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterChain", reflect.TypeOf((*Server)(nil).RegisterChain), arg0, arg1, arg2) } // Shutdown mocks base method. -func (m *MockServer) Shutdown() error { +func (m *Server) Shutdown() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Shutdown") ret0, _ := ret[0].(error) @@ -142,7 +142,7 @@ func (m *MockServer) Shutdown() error { } // Shutdown indicates an expected call of Shutdown. -func (mr *MockServerMockRecorder) Shutdown() *gomock.Call { +func (mr *ServerMockRecorder) Shutdown() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*MockServer)(nil).Shutdown)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*Server)(nil).Shutdown)) } diff --git a/chains/atomic/mock_shared_memory.go b/chains/atomic/atomicmock/shared_memory.go similarity index 50% rename from chains/atomic/mock_shared_memory.go rename to chains/atomic/atomicmock/shared_memory.go index 0e63179314da..fb93096f22b6 100644 --- a/chains/atomic/mock_shared_memory.go +++ b/chains/atomic/atomicmock/shared_memory.go @@ -3,45 +3,46 @@ // // Generated by this command: // -// mockgen -package=atomic -destination=chains/atomic/mock_shared_memory.go github.com/ava-labs/avalanchego/chains/atomic SharedMemory +// mockgen -package=atomicmock -destination=chains/atomic/atomicmock/shared_memory.go -mock_names=SharedMemory=SharedMemory github.com/ava-labs/avalanchego/chains/atomic SharedMemory // -// Package atomic is a generated GoMock package. -package atomic +// Package atomicmock is a generated GoMock package. +package atomicmock import ( reflect "reflect" + atomic "github.com/ava-labs/avalanchego/chains/atomic" database "github.com/ava-labs/avalanchego/database" ids "github.com/ava-labs/avalanchego/ids" gomock "go.uber.org/mock/gomock" ) -// MockSharedMemory is a mock of SharedMemory interface. -type MockSharedMemory struct { +// SharedMemory is a mock of SharedMemory interface. +type SharedMemory struct { ctrl *gomock.Controller - recorder *MockSharedMemoryMockRecorder + recorder *SharedMemoryMockRecorder } -// MockSharedMemoryMockRecorder is the mock recorder for MockSharedMemory. -type MockSharedMemoryMockRecorder struct { - mock *MockSharedMemory +// SharedMemoryMockRecorder is the mock recorder for SharedMemory. +type SharedMemoryMockRecorder struct { + mock *SharedMemory } -// NewMockSharedMemory creates a new mock instance. -func NewMockSharedMemory(ctrl *gomock.Controller) *MockSharedMemory { - mock := &MockSharedMemory{ctrl: ctrl} - mock.recorder = &MockSharedMemoryMockRecorder{mock} +// NewSharedMemory creates a new mock instance. +func NewSharedMemory(ctrl *gomock.Controller) *SharedMemory { + mock := &SharedMemory{ctrl: ctrl} + mock.recorder = &SharedMemoryMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSharedMemory) EXPECT() *MockSharedMemoryMockRecorder { +func (m *SharedMemory) EXPECT() *SharedMemoryMockRecorder { return m.recorder } // Apply mocks base method. -func (m *MockSharedMemory) Apply(arg0 map[ids.ID]*Requests, arg1 ...database.Batch) error { +func (m *SharedMemory) Apply(arg0 map[ids.ID]*atomic.Requests, arg1 ...database.Batch) error { m.ctrl.T.Helper() varargs := []any{arg0} for _, a := range arg1 { @@ -53,14 +54,14 @@ func (m *MockSharedMemory) Apply(arg0 map[ids.ID]*Requests, arg1 ...database.Bat } // Apply indicates an expected call of Apply. -func (mr *MockSharedMemoryMockRecorder) Apply(arg0 any, arg1 ...any) *gomock.Call { +func (mr *SharedMemoryMockRecorder) Apply(arg0 any, arg1 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() varargs := append([]any{arg0}, arg1...) - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockSharedMemory)(nil).Apply), varargs...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*SharedMemory)(nil).Apply), varargs...) } // Get mocks base method. -func (m *MockSharedMemory) Get(arg0 ids.ID, arg1 [][]byte) ([][]byte, error) { +func (m *SharedMemory) Get(arg0 ids.ID, arg1 [][]byte) ([][]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", arg0, arg1) ret0, _ := ret[0].([][]byte) @@ -69,13 +70,13 @@ func (m *MockSharedMemory) Get(arg0 ids.ID, arg1 [][]byte) ([][]byte, error) { } // Get indicates an expected call of Get. -func (mr *MockSharedMemoryMockRecorder) Get(arg0, arg1 any) *gomock.Call { +func (mr *SharedMemoryMockRecorder) Get(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockSharedMemory)(nil).Get), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*SharedMemory)(nil).Get), arg0, arg1) } // Indexed mocks base method. -func (m *MockSharedMemory) Indexed(arg0 ids.ID, arg1 [][]byte, arg2, arg3 []byte, arg4 int) ([][]byte, []byte, []byte, error) { +func (m *SharedMemory) Indexed(arg0 ids.ID, arg1 [][]byte, arg2, arg3 []byte, arg4 int) ([][]byte, []byte, []byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Indexed", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].([][]byte) @@ -86,7 +87,7 @@ func (m *MockSharedMemory) Indexed(arg0 ids.ID, arg1 [][]byte, arg2, arg3 []byte } // Indexed indicates an expected call of Indexed. -func (mr *MockSharedMemoryMockRecorder) Indexed(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { +func (mr *SharedMemoryMockRecorder) Indexed(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Indexed", reflect.TypeOf((*MockSharedMemory)(nil).Indexed), arg0, arg1, arg2, arg3, arg4) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Indexed", reflect.TypeOf((*SharedMemory)(nil).Indexed), arg0, arg1, arg2, arg3, arg4) } diff --git a/codec/mock_manager.go b/codec/codecmock/manager.go similarity index 52% rename from codec/mock_manager.go rename to codec/codecmock/manager.go index 36bbae57e96f..ec7c7c6ed229 100644 --- a/codec/mock_manager.go +++ b/codec/codecmock/manager.go @@ -3,43 +3,44 @@ // // Generated by this command: // -// mockgen -package=codec -destination=codec/mock_manager.go github.com/ava-labs/avalanchego/codec Manager +// mockgen -package=codecmock -destination=codec/codecmock/manager.go -mock_names=Manager=Manager github.com/ava-labs/avalanchego/codec Manager // -// Package codec is a generated GoMock package. -package codec +// Package codecmock is a generated GoMock package. +package codecmock import ( reflect "reflect" + codec "github.com/ava-labs/avalanchego/codec" gomock "go.uber.org/mock/gomock" ) -// MockManager is a mock of Manager interface. -type MockManager struct { +// Manager is a mock of Manager interface. +type Manager struct { ctrl *gomock.Controller - recorder *MockManagerMockRecorder + recorder *ManagerMockRecorder } -// MockManagerMockRecorder is the mock recorder for MockManager. -type MockManagerMockRecorder struct { - mock *MockManager +// ManagerMockRecorder is the mock recorder for Manager. +type ManagerMockRecorder struct { + mock *Manager } -// NewMockManager creates a new mock instance. -func NewMockManager(ctrl *gomock.Controller) *MockManager { - mock := &MockManager{ctrl: ctrl} - mock.recorder = &MockManagerMockRecorder{mock} +// NewManager creates a new mock instance. +func NewManager(ctrl *gomock.Controller) *Manager { + mock := &Manager{ctrl: ctrl} + mock.recorder = &ManagerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockManager) EXPECT() *MockManagerMockRecorder { +func (m *Manager) EXPECT() *ManagerMockRecorder { return m.recorder } // Marshal mocks base method. -func (m *MockManager) Marshal(arg0 uint16, arg1 any) ([]byte, error) { +func (m *Manager) Marshal(arg0 uint16, arg1 any) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Marshal", arg0, arg1) ret0, _ := ret[0].([]byte) @@ -48,13 +49,13 @@ func (m *MockManager) Marshal(arg0 uint16, arg1 any) ([]byte, error) { } // Marshal indicates an expected call of Marshal. -func (mr *MockManagerMockRecorder) Marshal(arg0, arg1 any) *gomock.Call { +func (mr *ManagerMockRecorder) Marshal(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Marshal", reflect.TypeOf((*MockManager)(nil).Marshal), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Marshal", reflect.TypeOf((*Manager)(nil).Marshal), arg0, arg1) } // RegisterCodec mocks base method. -func (m *MockManager) RegisterCodec(arg0 uint16, arg1 Codec) error { +func (m *Manager) RegisterCodec(arg0 uint16, arg1 codec.Codec) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RegisterCodec", arg0, arg1) ret0, _ := ret[0].(error) @@ -62,13 +63,13 @@ func (m *MockManager) RegisterCodec(arg0 uint16, arg1 Codec) error { } // RegisterCodec indicates an expected call of RegisterCodec. -func (mr *MockManagerMockRecorder) RegisterCodec(arg0, arg1 any) *gomock.Call { +func (mr *ManagerMockRecorder) RegisterCodec(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterCodec", reflect.TypeOf((*MockManager)(nil).RegisterCodec), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterCodec", reflect.TypeOf((*Manager)(nil).RegisterCodec), arg0, arg1) } // Size mocks base method. -func (m *MockManager) Size(arg0 uint16, arg1 any) (int, error) { +func (m *Manager) Size(arg0 uint16, arg1 any) (int, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Size", arg0, arg1) ret0, _ := ret[0].(int) @@ -77,13 +78,13 @@ func (m *MockManager) Size(arg0 uint16, arg1 any) (int, error) { } // Size indicates an expected call of Size. -func (mr *MockManagerMockRecorder) Size(arg0, arg1 any) *gomock.Call { +func (mr *ManagerMockRecorder) Size(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Size", reflect.TypeOf((*MockManager)(nil).Size), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Size", reflect.TypeOf((*Manager)(nil).Size), arg0, arg1) } // Unmarshal mocks base method. -func (m *MockManager) Unmarshal(arg0 []byte, arg1 any) (uint16, error) { +func (m *Manager) Unmarshal(arg0 []byte, arg1 any) (uint16, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Unmarshal", arg0, arg1) ret0, _ := ret[0].(uint16) @@ -92,7 +93,7 @@ func (m *MockManager) Unmarshal(arg0 []byte, arg1 any) (uint16, error) { } // Unmarshal indicates an expected call of Unmarshal. -func (mr *MockManagerMockRecorder) Unmarshal(arg0, arg1 any) *gomock.Call { +func (mr *ManagerMockRecorder) Unmarshal(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unmarshal", reflect.TypeOf((*MockManager)(nil).Unmarshal), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unmarshal", reflect.TypeOf((*Manager)(nil).Unmarshal), arg0, arg1) } diff --git a/database/corruptabledb/db_test.go b/database/corruptabledb/db_test.go index 4a9c74d171c0..ec9e4f1680a2 100644 --- a/database/corruptabledb/db_test.go +++ b/database/corruptabledb/db_test.go @@ -12,6 +12,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/databasemock" "github.com/ava-labs/avalanchego/database/dbtest" "github.com/ava-labs/avalanchego/database/memdb" ) @@ -111,7 +112,7 @@ func TestIterator(t *testing.T) { databaseErrBefore: nil, expectedErr: errIter, modifyIter: func(ctrl *gomock.Controller, iter *iterator) { - mockInnerIter := database.NewMockIterator(ctrl) + mockInnerIter := databasemock.NewIterator(ctrl) mockInnerIter.EXPECT().Next().Return(false) mockInnerIter.EXPECT().Error().Return(errIter) iter.Iterator = mockInnerIter @@ -135,7 +136,7 @@ func TestIterator(t *testing.T) { databaseErrBefore: nil, expectedErr: errIter, modifyIter: func(ctrl *gomock.Controller, iter *iterator) { - mockInnerIter := database.NewMockIterator(ctrl) + mockInnerIter := databasemock.NewIterator(ctrl) mockInnerIter.EXPECT().Error().Return(errIter) iter.Iterator = mockInnerIter }, diff --git a/database/mock_batch.go b/database/databasemock/batch.go similarity index 55% rename from database/mock_batch.go rename to database/databasemock/batch.go index e3762514954f..515a0c0c659c 100644 --- a/database/mock_batch.go +++ b/database/databasemock/batch.go @@ -3,43 +3,44 @@ // // Generated by this command: // -// mockgen -package=database -destination=database/mock_batch.go github.com/ava-labs/avalanchego/database Batch +// mockgen -package=databasemock -destination=database/databasemock/batch.go -mock_names=Batch=Batch github.com/ava-labs/avalanchego/database Batch // -// Package database is a generated GoMock package. -package database +// Package databasemock is a generated GoMock package. +package databasemock import ( reflect "reflect" + database "github.com/ava-labs/avalanchego/database" gomock "go.uber.org/mock/gomock" ) -// MockBatch is a mock of Batch interface. -type MockBatch struct { +// Batch is a mock of Batch interface. +type Batch struct { ctrl *gomock.Controller - recorder *MockBatchMockRecorder + recorder *BatchMockRecorder } -// MockBatchMockRecorder is the mock recorder for MockBatch. -type MockBatchMockRecorder struct { - mock *MockBatch +// BatchMockRecorder is the mock recorder for Batch. +type BatchMockRecorder struct { + mock *Batch } -// NewMockBatch creates a new mock instance. -func NewMockBatch(ctrl *gomock.Controller) *MockBatch { - mock := &MockBatch{ctrl: ctrl} - mock.recorder = &MockBatchMockRecorder{mock} +// NewBatch creates a new mock instance. +func NewBatch(ctrl *gomock.Controller) *Batch { + mock := &Batch{ctrl: ctrl} + mock.recorder = &BatchMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBatch) EXPECT() *MockBatchMockRecorder { +func (m *Batch) EXPECT() *BatchMockRecorder { return m.recorder } // Delete mocks base method. -func (m *MockBatch) Delete(arg0 []byte) error { +func (m *Batch) Delete(arg0 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Delete", arg0) ret0, _ := ret[0].(error) @@ -47,27 +48,27 @@ func (m *MockBatch) Delete(arg0 []byte) error { } // Delete indicates an expected call of Delete. -func (mr *MockBatchMockRecorder) Delete(arg0 any) *gomock.Call { +func (mr *BatchMockRecorder) Delete(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockBatch)(nil).Delete), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*Batch)(nil).Delete), arg0) } // Inner mocks base method. -func (m *MockBatch) Inner() Batch { +func (m *Batch) Inner() database.Batch { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Inner") - ret0, _ := ret[0].(Batch) + ret0, _ := ret[0].(database.Batch) return ret0 } // Inner indicates an expected call of Inner. -func (mr *MockBatchMockRecorder) Inner() *gomock.Call { +func (mr *BatchMockRecorder) Inner() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Inner", reflect.TypeOf((*MockBatch)(nil).Inner)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Inner", reflect.TypeOf((*Batch)(nil).Inner)) } // Put mocks base method. -func (m *MockBatch) Put(arg0, arg1 []byte) error { +func (m *Batch) Put(arg0, arg1 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Put", arg0, arg1) ret0, _ := ret[0].(error) @@ -75,13 +76,13 @@ func (m *MockBatch) Put(arg0, arg1 []byte) error { } // Put indicates an expected call of Put. -func (mr *MockBatchMockRecorder) Put(arg0, arg1 any) *gomock.Call { +func (mr *BatchMockRecorder) Put(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockBatch)(nil).Put), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*Batch)(nil).Put), arg0, arg1) } // Replay mocks base method. -func (m *MockBatch) Replay(arg0 KeyValueWriterDeleter) error { +func (m *Batch) Replay(arg0 database.KeyValueWriterDeleter) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Replay", arg0) ret0, _ := ret[0].(error) @@ -89,25 +90,25 @@ func (m *MockBatch) Replay(arg0 KeyValueWriterDeleter) error { } // Replay indicates an expected call of Replay. -func (mr *MockBatchMockRecorder) Replay(arg0 any) *gomock.Call { +func (mr *BatchMockRecorder) Replay(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Replay", reflect.TypeOf((*MockBatch)(nil).Replay), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Replay", reflect.TypeOf((*Batch)(nil).Replay), arg0) } // Reset mocks base method. -func (m *MockBatch) Reset() { +func (m *Batch) Reset() { m.ctrl.T.Helper() m.ctrl.Call(m, "Reset") } // Reset indicates an expected call of Reset. -func (mr *MockBatchMockRecorder) Reset() *gomock.Call { +func (mr *BatchMockRecorder) Reset() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reset", reflect.TypeOf((*MockBatch)(nil).Reset)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reset", reflect.TypeOf((*Batch)(nil).Reset)) } // Size mocks base method. -func (m *MockBatch) Size() int { +func (m *Batch) Size() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Size") ret0, _ := ret[0].(int) @@ -115,13 +116,13 @@ func (m *MockBatch) Size() int { } // Size indicates an expected call of Size. -func (mr *MockBatchMockRecorder) Size() *gomock.Call { +func (mr *BatchMockRecorder) Size() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Size", reflect.TypeOf((*MockBatch)(nil).Size)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Size", reflect.TypeOf((*Batch)(nil).Size)) } // Write mocks base method. -func (m *MockBatch) Write() error { +func (m *Batch) Write() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Write") ret0, _ := ret[0].(error) @@ -129,7 +130,7 @@ func (m *MockBatch) Write() error { } // Write indicates an expected call of Write. -func (mr *MockBatchMockRecorder) Write() *gomock.Call { +func (mr *BatchMockRecorder) Write() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*MockBatch)(nil).Write)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Write", reflect.TypeOf((*Batch)(nil).Write)) } diff --git a/database/mock_iterator.go b/database/databasemock/iterator.go similarity index 54% rename from database/mock_iterator.go rename to database/databasemock/iterator.go index 77856c92ea5e..2308ab65864b 100644 --- a/database/mock_iterator.go +++ b/database/databasemock/iterator.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=database -destination=database/mock_iterator.go github.com/ava-labs/avalanchego/database Iterator +// mockgen -package=databasemock -destination=database/databasemock/iterator.go -mock_names=Iterator=Iterator github.com/ava-labs/avalanchego/database Iterator // -// Package database is a generated GoMock package. -package database +// Package databasemock is a generated GoMock package. +package databasemock import ( reflect "reflect" @@ -15,31 +15,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockIterator is a mock of Iterator interface. -type MockIterator struct { +// Iterator is a mock of Iterator interface. +type Iterator struct { ctrl *gomock.Controller - recorder *MockIteratorMockRecorder + recorder *IteratorMockRecorder } -// MockIteratorMockRecorder is the mock recorder for MockIterator. -type MockIteratorMockRecorder struct { - mock *MockIterator +// IteratorMockRecorder is the mock recorder for Iterator. +type IteratorMockRecorder struct { + mock *Iterator } -// NewMockIterator creates a new mock instance. -func NewMockIterator(ctrl *gomock.Controller) *MockIterator { - mock := &MockIterator{ctrl: ctrl} - mock.recorder = &MockIteratorMockRecorder{mock} +// NewIterator creates a new mock instance. +func NewIterator(ctrl *gomock.Controller) *Iterator { + mock := &Iterator{ctrl: ctrl} + mock.recorder = &IteratorMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockIterator) EXPECT() *MockIteratorMockRecorder { +func (m *Iterator) EXPECT() *IteratorMockRecorder { return m.recorder } // Error mocks base method. -func (m *MockIterator) Error() error { +func (m *Iterator) Error() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Error") ret0, _ := ret[0].(error) @@ -47,13 +47,13 @@ func (m *MockIterator) Error() error { } // Error indicates an expected call of Error. -func (mr *MockIteratorMockRecorder) Error() *gomock.Call { +func (mr *IteratorMockRecorder) Error() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*MockIterator)(nil).Error)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Error", reflect.TypeOf((*Iterator)(nil).Error)) } // Key mocks base method. -func (m *MockIterator) Key() []byte { +func (m *Iterator) Key() []byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Key") ret0, _ := ret[0].([]byte) @@ -61,13 +61,13 @@ func (m *MockIterator) Key() []byte { } // Key indicates an expected call of Key. -func (mr *MockIteratorMockRecorder) Key() *gomock.Call { +func (mr *IteratorMockRecorder) Key() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Key", reflect.TypeOf((*MockIterator)(nil).Key)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Key", reflect.TypeOf((*Iterator)(nil).Key)) } // Next mocks base method. -func (m *MockIterator) Next() bool { +func (m *Iterator) Next() bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Next") ret0, _ := ret[0].(bool) @@ -75,25 +75,25 @@ func (m *MockIterator) Next() bool { } // Next indicates an expected call of Next. -func (mr *MockIteratorMockRecorder) Next() *gomock.Call { +func (mr *IteratorMockRecorder) Next() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Next", reflect.TypeOf((*MockIterator)(nil).Next)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Next", reflect.TypeOf((*Iterator)(nil).Next)) } // Release mocks base method. -func (m *MockIterator) Release() { +func (m *Iterator) Release() { m.ctrl.T.Helper() m.ctrl.Call(m, "Release") } // Release indicates an expected call of Release. -func (mr *MockIteratorMockRecorder) Release() *gomock.Call { +func (mr *IteratorMockRecorder) Release() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Release", reflect.TypeOf((*MockIterator)(nil).Release)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Release", reflect.TypeOf((*Iterator)(nil).Release)) } // Value mocks base method. -func (m *MockIterator) Value() []byte { +func (m *Iterator) Value() []byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Value") ret0, _ := ret[0].([]byte) @@ -101,7 +101,7 @@ func (m *MockIterator) Value() []byte { } // Value indicates an expected call of Value. -func (mr *MockIteratorMockRecorder) Value() *gomock.Call { +func (mr *IteratorMockRecorder) Value() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Value", reflect.TypeOf((*MockIterator)(nil).Value)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Value", reflect.TypeOf((*Iterator)(nil).Value)) } diff --git a/database/dbtest/dbtest.go b/database/dbtest/dbtest.go index b12e921634fe..dc203db09d1d 100644 --- a/database/dbtest/dbtest.go +++ b/database/dbtest/dbtest.go @@ -17,6 +17,7 @@ import ( "golang.org/x/sync/errgroup" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/database/databasemock" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/units" ) @@ -466,7 +467,7 @@ func TestBatchReplay(t *testing.T, db database.Database) { require.NoError(batch.Put(key1, value2)) for i := 0; i < 2; i++ { - mockBatch := database.NewMockBatch(ctrl) + mockBatch := databasemock.NewBatch(ctrl) gomock.InOrder( mockBatch.EXPECT().Put(key1, value1).Times(1), mockBatch.EXPECT().Put(key2, value2).Times(1), @@ -497,13 +498,13 @@ func TestBatchReplayPropagateError(t *testing.T, db database.Database) { require.NoError(batch.Put(key1, value1)) require.NoError(batch.Put(key2, value2)) - mockBatch := database.NewMockBatch(ctrl) + mockBatch := databasemock.NewBatch(ctrl) gomock.InOrder( mockBatch.EXPECT().Put(key1, value1).Return(database.ErrClosed).Times(1), ) require.Equal(database.ErrClosed, batch.Replay(mockBatch)) - mockBatch = database.NewMockBatch(ctrl) + mockBatch = databasemock.NewBatch(ctrl) gomock.InOrder( mockBatch.EXPECT().Put(key1, value1).Return(io.ErrClosedPipe).Times(1), ) diff --git a/indexer/indexer_test.go b/indexer/indexer_test.go index c8eb6c8e0eaf..6958d8851a86 100644 --- a/indexer/indexer_test.go +++ b/indexer/indexer_test.go @@ -18,8 +18,8 @@ import ( "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex" - "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex/vertexmock" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/logging" @@ -162,7 +162,7 @@ func TestIndexer(t *testing.T) { require.False(previouslyIndexed) // Register this chain, creating a new index - chainVM := block.NewMockChainVM(ctrl) + chainVM := blockmock.NewChainVM(ctrl) idxr.RegisterChain("chain1", chain1Ctx, chainVM) isIncomplete, err = idxr.isIncomplete(chain1Ctx.ChainID) require.NoError(err) @@ -265,7 +265,7 @@ func TestIndexer(t *testing.T) { previouslyIndexed, err = idxr.previouslyIndexed(chain2Ctx.ChainID) require.NoError(err) require.False(previouslyIndexed) - dagVM := vertex.NewMockLinearizableVM(ctrl) + dagVM := vertexmock.NewLinearizableVM(ctrl) idxr.RegisterChain("chain2", chain2Ctx, dagVM) require.NoError(err) require.Equal(4, server.timesCalled) // block index for chain, block index for dag, vtx index, tx index @@ -425,7 +425,7 @@ func TestIncompleteIndex(t *testing.T) { previouslyIndexed, err := idxr.previouslyIndexed(chain1Ctx.ChainID) require.NoError(err) require.False(previouslyIndexed) - chainVM := block.NewMockChainVM(ctrl) + chainVM := blockmock.NewChainVM(ctrl) idxr.RegisterChain("chain1", chain1Ctx, chainVM) isIncomplete, err = idxr.isIncomplete(chain1Ctx.ChainID) require.NoError(err) @@ -506,7 +506,7 @@ func TestIgnoreNonDefaultChains(t *testing.T) { }) // RegisterChain should return without adding an index for this chain - chainVM := block.NewMockChainVM(ctrl) + chainVM := blockmock.NewChainVM(ctrl) idxr.RegisterChain("chain1", chain1Ctx, chainVM) require.Empty(idxr.blockIndices) } diff --git a/message/mock_message.go b/message/messagemock/outbound_message.go similarity index 50% rename from message/mock_message.go rename to message/messagemock/outbound_message.go index ea6b9a67afcf..f7aadd4a21e2 100644 --- a/message/mock_message.go +++ b/message/messagemock/outbound_message.go @@ -3,43 +3,44 @@ // // Generated by this command: // -// mockgen -package=message -destination=message/mock_message.go github.com/ava-labs/avalanchego/message OutboundMessage +// mockgen -package=messagemock -destination=message/messagemock/outbound_message.go -mock_names=OutboundMessage=OutboundMessage github.com/ava-labs/avalanchego/message OutboundMessage // -// Package message is a generated GoMock package. -package message +// Package messagemock is a generated GoMock package. +package messagemock import ( reflect "reflect" + message "github.com/ava-labs/avalanchego/message" gomock "go.uber.org/mock/gomock" ) -// MockOutboundMessage is a mock of OutboundMessage interface. -type MockOutboundMessage struct { +// OutboundMessage is a mock of OutboundMessage interface. +type OutboundMessage struct { ctrl *gomock.Controller - recorder *MockOutboundMessageMockRecorder + recorder *OutboundMessageMockRecorder } -// MockOutboundMessageMockRecorder is the mock recorder for MockOutboundMessage. -type MockOutboundMessageMockRecorder struct { - mock *MockOutboundMessage +// OutboundMessageMockRecorder is the mock recorder for OutboundMessage. +type OutboundMessageMockRecorder struct { + mock *OutboundMessage } -// NewMockOutboundMessage creates a new mock instance. -func NewMockOutboundMessage(ctrl *gomock.Controller) *MockOutboundMessage { - mock := &MockOutboundMessage{ctrl: ctrl} - mock.recorder = &MockOutboundMessageMockRecorder{mock} +// NewOutboundMessage creates a new mock instance. +func NewOutboundMessage(ctrl *gomock.Controller) *OutboundMessage { + mock := &OutboundMessage{ctrl: ctrl} + mock.recorder = &OutboundMessageMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOutboundMessage) EXPECT() *MockOutboundMessageMockRecorder { +func (m *OutboundMessage) EXPECT() *OutboundMessageMockRecorder { return m.recorder } // BypassThrottling mocks base method. -func (m *MockOutboundMessage) BypassThrottling() bool { +func (m *OutboundMessage) BypassThrottling() bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BypassThrottling") ret0, _ := ret[0].(bool) @@ -47,13 +48,13 @@ func (m *MockOutboundMessage) BypassThrottling() bool { } // BypassThrottling indicates an expected call of BypassThrottling. -func (mr *MockOutboundMessageMockRecorder) BypassThrottling() *gomock.Call { +func (mr *OutboundMessageMockRecorder) BypassThrottling() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BypassThrottling", reflect.TypeOf((*MockOutboundMessage)(nil).BypassThrottling)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BypassThrottling", reflect.TypeOf((*OutboundMessage)(nil).BypassThrottling)) } // Bytes mocks base method. -func (m *MockOutboundMessage) Bytes() []byte { +func (m *OutboundMessage) Bytes() []byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bytes") ret0, _ := ret[0].([]byte) @@ -61,13 +62,13 @@ func (m *MockOutboundMessage) Bytes() []byte { } // Bytes indicates an expected call of Bytes. -func (mr *MockOutboundMessageMockRecorder) Bytes() *gomock.Call { +func (mr *OutboundMessageMockRecorder) Bytes() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*MockOutboundMessage)(nil).Bytes)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*OutboundMessage)(nil).Bytes)) } // BytesSavedCompression mocks base method. -func (m *MockOutboundMessage) BytesSavedCompression() int { +func (m *OutboundMessage) BytesSavedCompression() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BytesSavedCompression") ret0, _ := ret[0].(int) @@ -75,21 +76,21 @@ func (m *MockOutboundMessage) BytesSavedCompression() int { } // BytesSavedCompression indicates an expected call of BytesSavedCompression. -func (mr *MockOutboundMessageMockRecorder) BytesSavedCompression() *gomock.Call { +func (mr *OutboundMessageMockRecorder) BytesSavedCompression() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesSavedCompression", reflect.TypeOf((*MockOutboundMessage)(nil).BytesSavedCompression)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BytesSavedCompression", reflect.TypeOf((*OutboundMessage)(nil).BytesSavedCompression)) } // Op mocks base method. -func (m *MockOutboundMessage) Op() Op { +func (m *OutboundMessage) Op() message.Op { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Op") - ret0, _ := ret[0].(Op) + ret0, _ := ret[0].(message.Op) return ret0 } // Op indicates an expected call of Op. -func (mr *MockOutboundMessageMockRecorder) Op() *gomock.Call { +func (mr *OutboundMessageMockRecorder) Op() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Op", reflect.TypeOf((*MockOutboundMessage)(nil).Op)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Op", reflect.TypeOf((*OutboundMessage)(nil).Op)) } diff --git a/message/messagemock/outbound_message_builder.go b/message/messagemock/outbound_message_builder.go new file mode 100644 index 000000000000..b9261ca33010 --- /dev/null +++ b/message/messagemock/outbound_message_builder.go @@ -0,0 +1,405 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/message (interfaces: OutboundMsgBuilder) +// +// Generated by this command: +// +// mockgen -package=messagemock -destination=message/messagemock/outbound_message_builder.go -mock_names=OutboundMsgBuilder=OutboundMsgBuilder github.com/ava-labs/avalanchego/message OutboundMsgBuilder +// + +// Package messagemock is a generated GoMock package. +package messagemock + +import ( + netip "net/netip" + reflect "reflect" + time "time" + + ids "github.com/ava-labs/avalanchego/ids" + message "github.com/ava-labs/avalanchego/message" + p2p "github.com/ava-labs/avalanchego/proto/pb/p2p" + ips "github.com/ava-labs/avalanchego/utils/ips" + gomock "go.uber.org/mock/gomock" +) + +// OutboundMsgBuilder is a mock of OutboundMsgBuilder interface. +type OutboundMsgBuilder struct { + ctrl *gomock.Controller + recorder *OutboundMsgBuilderMockRecorder +} + +// OutboundMsgBuilderMockRecorder is the mock recorder for OutboundMsgBuilder. +type OutboundMsgBuilderMockRecorder struct { + mock *OutboundMsgBuilder +} + +// NewOutboundMsgBuilder creates a new mock instance. +func NewOutboundMsgBuilder(ctrl *gomock.Controller) *OutboundMsgBuilder { + mock := &OutboundMsgBuilder{ctrl: ctrl} + mock.recorder = &OutboundMsgBuilderMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *OutboundMsgBuilder) EXPECT() *OutboundMsgBuilderMockRecorder { + return m.recorder +} + +// Accepted mocks base method. +func (m *OutboundMsgBuilder) Accepted(arg0 ids.ID, arg1 uint32, arg2 []ids.ID) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Accepted", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Accepted indicates an expected call of Accepted. +func (mr *OutboundMsgBuilderMockRecorder) Accepted(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Accepted", reflect.TypeOf((*OutboundMsgBuilder)(nil).Accepted), arg0, arg1, arg2) +} + +// AcceptedFrontier mocks base method. +func (m *OutboundMsgBuilder) AcceptedFrontier(arg0 ids.ID, arg1 uint32, arg2 ids.ID) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AcceptedFrontier", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AcceptedFrontier indicates an expected call of AcceptedFrontier. +func (mr *OutboundMsgBuilderMockRecorder) AcceptedFrontier(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcceptedFrontier", reflect.TypeOf((*OutboundMsgBuilder)(nil).AcceptedFrontier), arg0, arg1, arg2) +} + +// AcceptedStateSummary mocks base method. +func (m *OutboundMsgBuilder) AcceptedStateSummary(arg0 ids.ID, arg1 uint32, arg2 []ids.ID) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AcceptedStateSummary", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AcceptedStateSummary indicates an expected call of AcceptedStateSummary. +func (mr *OutboundMsgBuilderMockRecorder) AcceptedStateSummary(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcceptedStateSummary", reflect.TypeOf((*OutboundMsgBuilder)(nil).AcceptedStateSummary), arg0, arg1, arg2) +} + +// Ancestors mocks base method. +func (m *OutboundMsgBuilder) Ancestors(arg0 ids.ID, arg1 uint32, arg2 [][]byte) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Ancestors", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Ancestors indicates an expected call of Ancestors. +func (mr *OutboundMsgBuilderMockRecorder) Ancestors(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ancestors", reflect.TypeOf((*OutboundMsgBuilder)(nil).Ancestors), arg0, arg1, arg2) +} + +// AppError mocks base method. +func (m *OutboundMsgBuilder) AppError(arg0 ids.ID, arg1 uint32, arg2 int32, arg3 string) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AppError", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AppError indicates an expected call of AppError. +func (mr *OutboundMsgBuilderMockRecorder) AppError(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppError", reflect.TypeOf((*OutboundMsgBuilder)(nil).AppError), arg0, arg1, arg2, arg3) +} + +// AppGossip mocks base method. +func (m *OutboundMsgBuilder) AppGossip(arg0 ids.ID, arg1 []byte) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AppGossip", arg0, arg1) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AppGossip indicates an expected call of AppGossip. +func (mr *OutboundMsgBuilderMockRecorder) AppGossip(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppGossip", reflect.TypeOf((*OutboundMsgBuilder)(nil).AppGossip), arg0, arg1) +} + +// AppRequest mocks base method. +func (m *OutboundMsgBuilder) AppRequest(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 []byte) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AppRequest", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AppRequest indicates an expected call of AppRequest. +func (mr *OutboundMsgBuilderMockRecorder) AppRequest(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequest", reflect.TypeOf((*OutboundMsgBuilder)(nil).AppRequest), arg0, arg1, arg2, arg3) +} + +// AppResponse mocks base method. +func (m *OutboundMsgBuilder) AppResponse(arg0 ids.ID, arg1 uint32, arg2 []byte) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AppResponse", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// AppResponse indicates an expected call of AppResponse. +func (mr *OutboundMsgBuilderMockRecorder) AppResponse(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppResponse", reflect.TypeOf((*OutboundMsgBuilder)(nil).AppResponse), arg0, arg1, arg2) +} + +// Chits mocks base method. +func (m *OutboundMsgBuilder) Chits(arg0 ids.ID, arg1 uint32, arg2, arg3, arg4 ids.ID) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Chits", arg0, arg1, arg2, arg3, arg4) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Chits indicates an expected call of Chits. +func (mr *OutboundMsgBuilderMockRecorder) Chits(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Chits", reflect.TypeOf((*OutboundMsgBuilder)(nil).Chits), arg0, arg1, arg2, arg3, arg4) +} + +// Get mocks base method. +func (m *OutboundMsgBuilder) Get(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 ids.ID) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *OutboundMsgBuilderMockRecorder) Get(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*OutboundMsgBuilder)(nil).Get), arg0, arg1, arg2, arg3) +} + +// GetAccepted mocks base method. +func (m *OutboundMsgBuilder) GetAccepted(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 []ids.ID) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAccepted", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAccepted indicates an expected call of GetAccepted. +func (mr *OutboundMsgBuilderMockRecorder) GetAccepted(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccepted", reflect.TypeOf((*OutboundMsgBuilder)(nil).GetAccepted), arg0, arg1, arg2, arg3) +} + +// GetAcceptedFrontier mocks base method. +func (m *OutboundMsgBuilder) GetAcceptedFrontier(arg0 ids.ID, arg1 uint32, arg2 time.Duration) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAcceptedFrontier", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAcceptedFrontier indicates an expected call of GetAcceptedFrontier. +func (mr *OutboundMsgBuilderMockRecorder) GetAcceptedFrontier(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAcceptedFrontier", reflect.TypeOf((*OutboundMsgBuilder)(nil).GetAcceptedFrontier), arg0, arg1, arg2) +} + +// GetAcceptedStateSummary mocks base method. +func (m *OutboundMsgBuilder) GetAcceptedStateSummary(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 []uint64) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAcceptedStateSummary", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAcceptedStateSummary indicates an expected call of GetAcceptedStateSummary. +func (mr *OutboundMsgBuilderMockRecorder) GetAcceptedStateSummary(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAcceptedStateSummary", reflect.TypeOf((*OutboundMsgBuilder)(nil).GetAcceptedStateSummary), arg0, arg1, arg2, arg3) +} + +// GetAncestors mocks base method. +func (m *OutboundMsgBuilder) GetAncestors(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 ids.ID, arg4 p2p.EngineType) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAncestors", arg0, arg1, arg2, arg3, arg4) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAncestors indicates an expected call of GetAncestors. +func (mr *OutboundMsgBuilderMockRecorder) GetAncestors(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAncestors", reflect.TypeOf((*OutboundMsgBuilder)(nil).GetAncestors), arg0, arg1, arg2, arg3, arg4) +} + +// GetPeerList mocks base method. +func (m *OutboundMsgBuilder) GetPeerList(arg0, arg1 []byte, arg2 bool) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPeerList", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPeerList indicates an expected call of GetPeerList. +func (mr *OutboundMsgBuilderMockRecorder) GetPeerList(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPeerList", reflect.TypeOf((*OutboundMsgBuilder)(nil).GetPeerList), arg0, arg1, arg2) +} + +// GetStateSummaryFrontier mocks base method. +func (m *OutboundMsgBuilder) GetStateSummaryFrontier(arg0 ids.ID, arg1 uint32, arg2 time.Duration) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetStateSummaryFrontier", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetStateSummaryFrontier indicates an expected call of GetStateSummaryFrontier. +func (mr *OutboundMsgBuilderMockRecorder) GetStateSummaryFrontier(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStateSummaryFrontier", reflect.TypeOf((*OutboundMsgBuilder)(nil).GetStateSummaryFrontier), arg0, arg1, arg2) +} + +// Handshake mocks base method. +func (m *OutboundMsgBuilder) Handshake(arg0 uint32, arg1 uint64, arg2 netip.AddrPort, arg3 string, arg4, arg5, arg6 uint32, arg7 uint64, arg8, arg9 []byte, arg10 []ids.ID, arg11, arg12 []uint32, arg13, arg14 []byte, arg15 bool) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Handshake", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Handshake indicates an expected call of Handshake. +func (mr *OutboundMsgBuilderMockRecorder) Handshake(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Handshake", reflect.TypeOf((*OutboundMsgBuilder)(nil).Handshake), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) +} + +// PeerList mocks base method. +func (m *OutboundMsgBuilder) PeerList(arg0 []*ips.ClaimedIPPort, arg1 bool) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PeerList", arg0, arg1) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PeerList indicates an expected call of PeerList. +func (mr *OutboundMsgBuilderMockRecorder) PeerList(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PeerList", reflect.TypeOf((*OutboundMsgBuilder)(nil).PeerList), arg0, arg1) +} + +// Ping mocks base method. +func (m *OutboundMsgBuilder) Ping(arg0 uint32, arg1 []*p2p.SubnetUptime) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Ping", arg0, arg1) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Ping indicates an expected call of Ping. +func (mr *OutboundMsgBuilderMockRecorder) Ping(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ping", reflect.TypeOf((*OutboundMsgBuilder)(nil).Ping), arg0, arg1) +} + +// Pong mocks base method. +func (m *OutboundMsgBuilder) Pong() (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Pong") + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Pong indicates an expected call of Pong. +func (mr *OutboundMsgBuilderMockRecorder) Pong() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Pong", reflect.TypeOf((*OutboundMsgBuilder)(nil).Pong)) +} + +// PullQuery mocks base method. +func (m *OutboundMsgBuilder) PullQuery(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 ids.ID, arg4 uint64) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PullQuery", arg0, arg1, arg2, arg3, arg4) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PullQuery indicates an expected call of PullQuery. +func (mr *OutboundMsgBuilderMockRecorder) PullQuery(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PullQuery", reflect.TypeOf((*OutboundMsgBuilder)(nil).PullQuery), arg0, arg1, arg2, arg3, arg4) +} + +// PushQuery mocks base method. +func (m *OutboundMsgBuilder) PushQuery(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 []byte, arg4 uint64) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PushQuery", arg0, arg1, arg2, arg3, arg4) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PushQuery indicates an expected call of PushQuery. +func (mr *OutboundMsgBuilderMockRecorder) PushQuery(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PushQuery", reflect.TypeOf((*OutboundMsgBuilder)(nil).PushQuery), arg0, arg1, arg2, arg3, arg4) +} + +// Put mocks base method. +func (m *OutboundMsgBuilder) Put(arg0 ids.ID, arg1 uint32, arg2 []byte) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Put", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Put indicates an expected call of Put. +func (mr *OutboundMsgBuilderMockRecorder) Put(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*OutboundMsgBuilder)(nil).Put), arg0, arg1, arg2) +} + +// StateSummaryFrontier mocks base method. +func (m *OutboundMsgBuilder) StateSummaryFrontier(arg0 ids.ID, arg1 uint32, arg2 []byte) (message.OutboundMessage, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StateSummaryFrontier", arg0, arg1, arg2) + ret0, _ := ret[0].(message.OutboundMessage) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StateSummaryFrontier indicates an expected call of StateSummaryFrontier. +func (mr *OutboundMsgBuilderMockRecorder) StateSummaryFrontier(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateSummaryFrontier", reflect.TypeOf((*OutboundMsgBuilder)(nil).StateSummaryFrontier), arg0, arg1, arg2) +} diff --git a/message/mock_outbound_message_builder.go b/message/mock_outbound_message_builder.go deleted file mode 100644 index 1422230961e4..000000000000 --- a/message/mock_outbound_message_builder.go +++ /dev/null @@ -1,404 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/message (interfaces: OutboundMsgBuilder) -// -// Generated by this command: -// -// mockgen -package=message -destination=message/mock_outbound_message_builder.go github.com/ava-labs/avalanchego/message OutboundMsgBuilder -// - -// Package message is a generated GoMock package. -package message - -import ( - netip "net/netip" - reflect "reflect" - time "time" - - ids "github.com/ava-labs/avalanchego/ids" - p2p "github.com/ava-labs/avalanchego/proto/pb/p2p" - ips "github.com/ava-labs/avalanchego/utils/ips" - gomock "go.uber.org/mock/gomock" -) - -// MockOutboundMsgBuilder is a mock of OutboundMsgBuilder interface. -type MockOutboundMsgBuilder struct { - ctrl *gomock.Controller - recorder *MockOutboundMsgBuilderMockRecorder -} - -// MockOutboundMsgBuilderMockRecorder is the mock recorder for MockOutboundMsgBuilder. -type MockOutboundMsgBuilderMockRecorder struct { - mock *MockOutboundMsgBuilder -} - -// NewMockOutboundMsgBuilder creates a new mock instance. -func NewMockOutboundMsgBuilder(ctrl *gomock.Controller) *MockOutboundMsgBuilder { - mock := &MockOutboundMsgBuilder{ctrl: ctrl} - mock.recorder = &MockOutboundMsgBuilderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOutboundMsgBuilder) EXPECT() *MockOutboundMsgBuilderMockRecorder { - return m.recorder -} - -// Accepted mocks base method. -func (m *MockOutboundMsgBuilder) Accepted(arg0 ids.ID, arg1 uint32, arg2 []ids.ID) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Accepted", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Accepted indicates an expected call of Accepted. -func (mr *MockOutboundMsgBuilderMockRecorder) Accepted(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Accepted", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Accepted), arg0, arg1, arg2) -} - -// AcceptedFrontier mocks base method. -func (m *MockOutboundMsgBuilder) AcceptedFrontier(arg0 ids.ID, arg1 uint32, arg2 ids.ID) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AcceptedFrontier", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AcceptedFrontier indicates an expected call of AcceptedFrontier. -func (mr *MockOutboundMsgBuilderMockRecorder) AcceptedFrontier(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcceptedFrontier", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).AcceptedFrontier), arg0, arg1, arg2) -} - -// AcceptedStateSummary mocks base method. -func (m *MockOutboundMsgBuilder) AcceptedStateSummary(arg0 ids.ID, arg1 uint32, arg2 []ids.ID) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AcceptedStateSummary", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AcceptedStateSummary indicates an expected call of AcceptedStateSummary. -func (mr *MockOutboundMsgBuilderMockRecorder) AcceptedStateSummary(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AcceptedStateSummary", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).AcceptedStateSummary), arg0, arg1, arg2) -} - -// Ancestors mocks base method. -func (m *MockOutboundMsgBuilder) Ancestors(arg0 ids.ID, arg1 uint32, arg2 [][]byte) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Ancestors", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Ancestors indicates an expected call of Ancestors. -func (mr *MockOutboundMsgBuilderMockRecorder) Ancestors(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ancestors", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Ancestors), arg0, arg1, arg2) -} - -// AppError mocks base method. -func (m *MockOutboundMsgBuilder) AppError(arg0 ids.ID, arg1 uint32, arg2 int32, arg3 string) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AppError", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AppError indicates an expected call of AppError. -func (mr *MockOutboundMsgBuilderMockRecorder) AppError(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppError", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).AppError), arg0, arg1, arg2, arg3) -} - -// AppGossip mocks base method. -func (m *MockOutboundMsgBuilder) AppGossip(arg0 ids.ID, arg1 []byte) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AppGossip", arg0, arg1) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AppGossip indicates an expected call of AppGossip. -func (mr *MockOutboundMsgBuilderMockRecorder) AppGossip(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppGossip", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).AppGossip), arg0, arg1) -} - -// AppRequest mocks base method. -func (m *MockOutboundMsgBuilder) AppRequest(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 []byte) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AppRequest", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AppRequest indicates an expected call of AppRequest. -func (mr *MockOutboundMsgBuilderMockRecorder) AppRequest(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequest", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).AppRequest), arg0, arg1, arg2, arg3) -} - -// AppResponse mocks base method. -func (m *MockOutboundMsgBuilder) AppResponse(arg0 ids.ID, arg1 uint32, arg2 []byte) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "AppResponse", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// AppResponse indicates an expected call of AppResponse. -func (mr *MockOutboundMsgBuilderMockRecorder) AppResponse(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppResponse", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).AppResponse), arg0, arg1, arg2) -} - -// Chits mocks base method. -func (m *MockOutboundMsgBuilder) Chits(arg0 ids.ID, arg1 uint32, arg2, arg3, arg4 ids.ID) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Chits", arg0, arg1, arg2, arg3, arg4) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Chits indicates an expected call of Chits. -func (mr *MockOutboundMsgBuilderMockRecorder) Chits(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Chits", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Chits), arg0, arg1, arg2, arg3, arg4) -} - -// Get mocks base method. -func (m *MockOutboundMsgBuilder) Get(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 ids.ID) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Get indicates an expected call of Get. -func (mr *MockOutboundMsgBuilderMockRecorder) Get(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Get), arg0, arg1, arg2, arg3) -} - -// GetAccepted mocks base method. -func (m *MockOutboundMsgBuilder) GetAccepted(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 []ids.ID) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAccepted", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAccepted indicates an expected call of GetAccepted. -func (mr *MockOutboundMsgBuilderMockRecorder) GetAccepted(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAccepted", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).GetAccepted), arg0, arg1, arg2, arg3) -} - -// GetAcceptedFrontier mocks base method. -func (m *MockOutboundMsgBuilder) GetAcceptedFrontier(arg0 ids.ID, arg1 uint32, arg2 time.Duration) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAcceptedFrontier", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAcceptedFrontier indicates an expected call of GetAcceptedFrontier. -func (mr *MockOutboundMsgBuilderMockRecorder) GetAcceptedFrontier(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAcceptedFrontier", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).GetAcceptedFrontier), arg0, arg1, arg2) -} - -// GetAcceptedStateSummary mocks base method. -func (m *MockOutboundMsgBuilder) GetAcceptedStateSummary(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 []uint64) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAcceptedStateSummary", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAcceptedStateSummary indicates an expected call of GetAcceptedStateSummary. -func (mr *MockOutboundMsgBuilderMockRecorder) GetAcceptedStateSummary(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAcceptedStateSummary", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).GetAcceptedStateSummary), arg0, arg1, arg2, arg3) -} - -// GetAncestors mocks base method. -func (m *MockOutboundMsgBuilder) GetAncestors(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 ids.ID, arg4 p2p.EngineType) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAncestors", arg0, arg1, arg2, arg3, arg4) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAncestors indicates an expected call of GetAncestors. -func (mr *MockOutboundMsgBuilderMockRecorder) GetAncestors(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAncestors", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).GetAncestors), arg0, arg1, arg2, arg3, arg4) -} - -// GetPeerList mocks base method. -func (m *MockOutboundMsgBuilder) GetPeerList(arg0, arg1 []byte, arg2 bool) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPeerList", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPeerList indicates an expected call of GetPeerList. -func (mr *MockOutboundMsgBuilderMockRecorder) GetPeerList(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPeerList", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).GetPeerList), arg0, arg1, arg2) -} - -// GetStateSummaryFrontier mocks base method. -func (m *MockOutboundMsgBuilder) GetStateSummaryFrontier(arg0 ids.ID, arg1 uint32, arg2 time.Duration) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStateSummaryFrontier", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStateSummaryFrontier indicates an expected call of GetStateSummaryFrontier. -func (mr *MockOutboundMsgBuilderMockRecorder) GetStateSummaryFrontier(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStateSummaryFrontier", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).GetStateSummaryFrontier), arg0, arg1, arg2) -} - -// Handshake mocks base method. -func (m *MockOutboundMsgBuilder) Handshake(arg0 uint32, arg1 uint64, arg2 netip.AddrPort, arg3 string, arg4, arg5, arg6 uint32, arg7 uint64, arg8, arg9 []byte, arg10 []ids.ID, arg11, arg12 []uint32, arg13, arg14 []byte, arg15 bool) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Handshake", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Handshake indicates an expected call of Handshake. -func (mr *MockOutboundMsgBuilderMockRecorder) Handshake(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Handshake", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Handshake), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) -} - -// PeerList mocks base method. -func (m *MockOutboundMsgBuilder) PeerList(arg0 []*ips.ClaimedIPPort, arg1 bool) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PeerList", arg0, arg1) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PeerList indicates an expected call of PeerList. -func (mr *MockOutboundMsgBuilderMockRecorder) PeerList(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PeerList", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).PeerList), arg0, arg1) -} - -// Ping mocks base method. -func (m *MockOutboundMsgBuilder) Ping(arg0 uint32, arg1 []*p2p.SubnetUptime) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Ping", arg0, arg1) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Ping indicates an expected call of Ping. -func (mr *MockOutboundMsgBuilderMockRecorder) Ping(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Ping", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Ping), arg0, arg1) -} - -// Pong mocks base method. -func (m *MockOutboundMsgBuilder) Pong() (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Pong") - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Pong indicates an expected call of Pong. -func (mr *MockOutboundMsgBuilderMockRecorder) Pong() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Pong", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Pong)) -} - -// PullQuery mocks base method. -func (m *MockOutboundMsgBuilder) PullQuery(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 ids.ID, arg4 uint64) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PullQuery", arg0, arg1, arg2, arg3, arg4) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PullQuery indicates an expected call of PullQuery. -func (mr *MockOutboundMsgBuilderMockRecorder) PullQuery(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PullQuery", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).PullQuery), arg0, arg1, arg2, arg3, arg4) -} - -// PushQuery mocks base method. -func (m *MockOutboundMsgBuilder) PushQuery(arg0 ids.ID, arg1 uint32, arg2 time.Duration, arg3 []byte, arg4 uint64) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PushQuery", arg0, arg1, arg2, arg3, arg4) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PushQuery indicates an expected call of PushQuery. -func (mr *MockOutboundMsgBuilderMockRecorder) PushQuery(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PushQuery", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).PushQuery), arg0, arg1, arg2, arg3, arg4) -} - -// Put mocks base method. -func (m *MockOutboundMsgBuilder) Put(arg0 ids.ID, arg1 uint32, arg2 []byte) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Put", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Put indicates an expected call of Put. -func (mr *MockOutboundMsgBuilderMockRecorder) Put(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Put", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).Put), arg0, arg1, arg2) -} - -// StateSummaryFrontier mocks base method. -func (m *MockOutboundMsgBuilder) StateSummaryFrontier(arg0 ids.ID, arg1 uint32, arg2 []byte) (OutboundMessage, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "StateSummaryFrontier", arg0, arg1, arg2) - ret0, _ := ret[0].(OutboundMessage) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// StateSummaryFrontier indicates an expected call of StateSummaryFrontier. -func (mr *MockOutboundMsgBuilderMockRecorder) StateSummaryFrontier(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateSummaryFrontier", reflect.TypeOf((*MockOutboundMsgBuilder)(nil).StateSummaryFrontier), arg0, arg1, arg2) -} diff --git a/network/p2p/validators_test.go b/network/p2p/validators_test.go index 16cdd92e18a3..a3753d0e180e 100644 --- a/network/p2p/validators_test.go +++ b/network/p2p/validators_test.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" "github.com/ava-labs/avalanchego/utils/logging" ) @@ -169,7 +170,7 @@ func TestValidatorsSample(t *testing.T) { require := require.New(t) subnetID := ids.GenerateTestID() ctrl := gomock.NewController(t) - mockValidators := validators.NewMockState(ctrl) + mockValidators := validatorsmock.NewState(ctrl) calls := make([]any, 0) for _, call := range tt.calls { @@ -310,7 +311,7 @@ func TestValidatorsTop(t *testing.T) { } subnetID := ids.GenerateTestID() - mockValidators := validators.NewMockState(ctrl) + mockValidators := validatorsmock.NewState(ctrl) mockValidators.EXPECT().GetCurrentHeight(gomock.Any()).Return(uint64(1), nil) mockValidators.EXPECT().GetValidatorSet(gomock.Any(), uint64(1), subnetID).Return(validatorSet, nil) diff --git a/network/throttling/inbound_resource_throttler_test.go b/network/throttling/inbound_resource_throttler_test.go index 93ec28119614..c9f9b00dc3f4 100644 --- a/network/throttling/inbound_resource_throttler_test.go +++ b/network/throttling/inbound_resource_throttler_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/networking/tracker" + "github.com/ava-labs/avalanchego/snow/networking/tracker/trackermock" "github.com/ava-labs/avalanchego/utils/math/meter" "github.com/ava-labs/avalanchego/utils/resource" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -33,7 +34,7 @@ func TestNewSystemThrottler(t *testing.T) { Clock: clock, MaxRecheckDelay: time.Second, } - targeter := tracker.NewMockTargeter(ctrl) + targeter := trackermock.NewTargeter(ctrl) throttlerIntf, err := NewSystemThrottler("", reg, config, cpuTracker, targeter) require.NoError(err) require.IsType(&systemThrottler{}, throttlerIntf) @@ -49,13 +50,13 @@ func TestSystemThrottler(t *testing.T) { require := require.New(t) // Setup - mockTracker := tracker.NewMockTracker(ctrl) + mockTracker := trackermock.NewTracker(ctrl) maxRecheckDelay := 100 * time.Millisecond config := SystemThrottlerConfig{ MaxRecheckDelay: maxRecheckDelay, } vdrID, nonVdrID := ids.GenerateTestNodeID(), ids.GenerateTestNodeID() - targeter := tracker.NewMockTargeter(ctrl) + targeter := trackermock.NewTargeter(ctrl) throttler, err := NewSystemThrottler("", prometheus.NewRegistry(), config, mockTracker, targeter) require.NoError(err) @@ -131,13 +132,13 @@ func TestSystemThrottlerContextCancel(t *testing.T) { ctrl := gomock.NewController(t) // Setup - mockTracker := tracker.NewMockTracker(ctrl) + mockTracker := trackermock.NewTracker(ctrl) maxRecheckDelay := 10 * time.Second config := SystemThrottlerConfig{ MaxRecheckDelay: maxRecheckDelay, } vdrID := ids.GenerateTestNodeID() - targeter := tracker.NewMockTargeter(ctrl) + targeter := trackermock.NewTargeter(ctrl) throttler, err := NewSystemThrottler("", prometheus.NewRegistry(), config, mockTracker, targeter) require.NoError(err) diff --git a/network/throttling/outbound_msg_throttler_test.go b/network/throttling/outbound_msg_throttler_test.go index ab883b8fa4e4..105b8be6b3f3 100644 --- a/network/throttling/outbound_msg_throttler_test.go +++ b/network/throttling/outbound_msg_throttler_test.go @@ -12,6 +12,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/message" + "github.com/ava-labs/avalanchego/message/messagemock" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" @@ -226,7 +227,7 @@ func TestBypassThrottling(t *testing.T) { require.NoError(err) throttler := throttlerIntf.(*outboundMsgThrottler) nonVdrNodeID1 := ids.GenerateTestNodeID() - msg := message.NewMockOutboundMessage(ctrl) + msg := messagemock.NewOutboundMessage(ctrl) msg.EXPECT().BypassThrottling().Return(true).AnyTimes() msg.EXPECT().Op().Return(message.AppGossipOp).AnyTimes() msg.EXPECT().Bytes().Return(make([]byte, config.NodeMaxAtLargeBytes)).AnyTimes() @@ -234,7 +235,7 @@ func TestBypassThrottling(t *testing.T) { require.True(acquired) // Acquiring more should not fail - msg = message.NewMockOutboundMessage(ctrl) + msg = messagemock.NewOutboundMessage(ctrl) msg.EXPECT().BypassThrottling().Return(true).AnyTimes() msg.EXPECT().Op().Return(message.AppGossipOp).AnyTimes() msg.EXPECT().Bytes().Return(make([]byte, 1)).AnyTimes() @@ -247,7 +248,7 @@ func TestBypassThrottling(t *testing.T) { require.True(acquired) // Validator should only be able to take [MaxAtLargeBytes] - msg = message.NewMockOutboundMessage(ctrl) + msg = messagemock.NewOutboundMessage(ctrl) msg.EXPECT().BypassThrottling().Return(true).AnyTimes() msg.EXPECT().Op().Return(message.AppGossipOp).AnyTimes() msg.EXPECT().Bytes().Return(make([]byte, config.NodeMaxAtLargeBytes+1)).AnyTimes() @@ -259,7 +260,7 @@ func TestBypassThrottling(t *testing.T) { } func testMsgWithSize(ctrl *gomock.Controller, size uint64) message.OutboundMessage { - msg := message.NewMockOutboundMessage(ctrl) + msg := messagemock.NewOutboundMessage(ctrl) msg.EXPECT().BypassThrottling().Return(false).AnyTimes() msg.EXPECT().Op().Return(message.AppGossipOp).AnyTimes() msg.EXPECT().Bytes().Return(make([]byte, size)).AnyTimes() diff --git a/node/beacon_manager_test.go b/node/beacon_manager_test.go index c4d0097563a7..57c3323476ad 100644 --- a/node/beacon_manager_test.go +++ b/node/beacon_manager_test.go @@ -11,7 +11,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/snow/networking/router" + "github.com/ava-labs/avalanchego/snow/networking/router/routermock" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/version" @@ -36,7 +36,7 @@ func TestBeaconManager_DataRace(t *testing.T) { wg := &sync.WaitGroup{} ctrl := gomock.NewController(t) - mockRouter := router.NewMockRouter(ctrl) + mockRouter := routermock.NewRouter(ctrl) b := beaconManager{ Router: mockRouter, diff --git a/scripts/lint.sh b/scripts/lint.sh index c35a87dd7910..41eedec65e92 100755 --- a/scripts/lint.sh +++ b/scripts/lint.sh @@ -43,7 +43,7 @@ _addlicense_flags=${ADDLICENSE_FLAGS:-"--verify --debug"} function test_license_header { go install -v github.com/palantir/go-license@v1.25.0 local files=() - while IFS= read -r line; do files+=("$line"); done < <(find . -type f -name '*.go' ! -name '*.pb.go' ! -name 'mock_*.go') + while IFS= read -r line; do files+=("$line"); done < <(find . -type f -name '*.go' ! -name '*.pb.go' ! -name 'mock_*.go' ! -path './**/*mock/*.go') # shellcheck disable=SC2086 go-license \ diff --git a/scripts/mock.gen.sh b/scripts/mock.gen.sh index ead92957b852..3a25f8ee4f6c 100755 --- a/scripts/mock.gen.sh +++ b/scripts/mock.gen.sh @@ -14,7 +14,7 @@ source ./scripts/constants.sh outputted_files=() -# tuples of (source interface import path, comma-separated interface names, output file path) +# tuples of (source import path, comma-separated interface names, output file path) input="scripts/mocks.mockgen.txt" while IFS= read -r line do @@ -22,15 +22,15 @@ do package_name="$(basename "$(dirname "$output_path")")" echo "Generating ${output_path}..." outputted_files+=("${output_path}") - mockgen -package="${package_name}" -destination="${output_path}" "${src_import_path}" "${interface_name}" + mockgen -package="${package_name}" -destination="${output_path}" -mock_names="${interface_name}=${interface_name}" "${src_import_path}" "${interface_name}" done < "$input" -# tuples of (source import path, comma-separated interface names to exclude, output file path) +# tuples of (source import path, comma-separated interface names to exclude, interface name, output file path) input="scripts/mocks.mockgen.source.txt" while IFS= read -r line do - IFS='=' read -r source_path exclude_interfaces output_path <<< "${line}" + IFS='=' read -r source_path exclude_interfaces interface_name output_path <<< "${line}" package_name=$(basename "$(dirname "$output_path")") outputted_files+=("${output_path}") echo "Generating ${output_path}..." @@ -39,7 +39,8 @@ do -source="${source_path}" \ -destination="${output_path}" \ -package="${package_name}" \ - -exclude_interfaces="${exclude_interfaces}" + -exclude_interfaces="${exclude_interfaces}" \ + -mock_names="${interface_name}=${interface_name}" done < "$input" @@ -47,8 +48,8 @@ mapfile -t all_generated_files < <(grep -Rl 'Code generated by MockGen. DO NOT E # Exclude certain files outputted_files+=('scripts/mock.gen.sh') # This file -outputted_files+=('vms/components/avax/mock_transferable_out.go') # Embedded verify.IsState -outputted_files+=('vms/platformvm/fx/mock_fx.go') # Embedded verify.IsNotState +outputted_files+=('vms/components/avax/avaxmock/transferable_out.go') # Embedded verify.IsState +outputted_files+=('vms/platformvm/fx/fxmock/owner.go') # Embedded verify.IsNotState mapfile -t diff_files < <(echo "${all_generated_files[@]}" "${outputted_files[@]}" | tr ' ' '\n' | sort | uniq -u) diff --git a/scripts/mocks.mockgen.source.txt b/scripts/mocks.mockgen.source.txt index 167c77ce5cc8..465e8ea5d888 100644 --- a/scripts/mocks.mockgen.source.txt +++ b/scripts/mocks.mockgen.source.txt @@ -1,9 +1,15 @@ -snow/engine/common/sender.go=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,Gossiper=snow/engine/common/mock_sender.go -snow/networking/router/router.go=InternalHandler=snow/networking/router/mock_router.go -snow/networking/sender/external_sender.go==snow/networking/sender/mock_external_sender.go -vms/avm/block/executor/manager.go==vms/avm/block/executor/mock_manager.go -vms/avm/txs/tx.go==vms/avm/txs/mock_unsigned_tx.go -vms/platformvm/block/executor/manager.go==vms/platformvm/block/executor/mock_manager.go -vms/platformvm/txs/unsigned_tx.go==vms/platformvm/txs/mock_unsigned_tx.go -vms/platformvm/signer/signer.go==vms/platformvm/signer/mock_signer.go -x/merkledb/db.go=ChangeProofer,RangeProofer,Clearer,Prefetcher=x/merkledb/mock_db.go +snow/engine/common/sender.go=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,Gossiper=Sender=snow/engine/common/commonmock/sender.go +snow/networking/router/router.go=InternalHandler=Router=snow/networking/router/routermock/router.go +snow/networking/sender/external_sender.go==ExternalSender=snow/networking/sender/sendermock/external_sender.go +vms/avm/block/block.go==MockBlock=vms/avm/block/mock_block.go +vms/avm/block/executor/manager.go==Manager=vms/avm/block/executor/executormock/manager.go +vms/avm/txs/tx.go==UnsignedTx=vms/avm/txs/txsmock/tx.go +vms/platformvm/block/block.go=BanffBlock=MockBlock=vms/platformvm/block/mock_block.go +vms/platformvm/block/executor/manager.go==Manager=vms/platformvm/block/executor/executormock/manager.go +vms/platformvm/signer/signer.go==Signer=vms/platformvm/signer/signermock/signer.go +vms/platformvm/state/staker.go==MockStakerIterator=vms/platformvm/state/mock_staker_iterator.go +vms/platformvm/state/state.go=Chain=MockState=vms/platformvm/state/mock_state.go +vms/platformvm/txs/unsigned_tx.go==UnsignedTx=vms/platformvm/txs/txsmock/unsigned_tx.go +vms/proposervm/block.go=Block=MockPostForkBlock=vms/proposervm/mock_post_fork_block.go +x/merkledb/db.go=ChangeProofer,RangeProofer,Clearer,Prefetcher=MockMerkleDB=x/merkledb/mock_db.go +x/sync/client.go==MockClient=x/sync/mock_client.go diff --git a/scripts/mocks.mockgen.txt b/scripts/mocks.mockgen.txt index 688eee77a57b..7763fa06e6e3 100644 --- a/scripts/mocks.mockgen.txt +++ b/scripts/mocks.mockgen.txt @@ -1,44 +1,44 @@ -github.com/ava-labs/avalanchego/api/server=Server=api/server/mock_server.go -github.com/ava-labs/avalanchego/chains/atomic=SharedMemory=chains/atomic/mock_shared_memory.go -github.com/ava-labs/avalanchego/codec=Manager=codec/mock_manager.go -github.com/ava-labs/avalanchego/database=Batch=database/mock_batch.go -github.com/ava-labs/avalanchego/database=Iterator=database/mock_iterator.go -github.com/ava-labs/avalanchego/message=OutboundMessage=message/mock_message.go -github.com/ava-labs/avalanchego/message=OutboundMsgBuilder=message/mock_outbound_message_builder.go -github.com/ava-labs/avalanchego/snow/consensus/snowman=Block=snow/consensus/snowman/snowmantest/mock_block.go -github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex=LinearizableVM=snow/engine/avalanche/vertex/mock_vm.go -github.com/ava-labs/avalanchego/snow/engine/snowman/block=BuildBlockWithContextChainVM=snow/engine/snowman/block/mock_build_block_with_context_vm.go -github.com/ava-labs/avalanchego/snow/engine/snowman/block=ChainVM=snow/engine/snowman/block/mock_chain_vm.go -github.com/ava-labs/avalanchego/snow/engine/snowman/block=StateSyncableVM=snow/engine/snowman/block/mock_state_syncable_vm.go -github.com/ava-labs/avalanchego/snow/engine/snowman/block=WithVerifyContext=snow/engine/snowman/block/mock_with_verify_context.go -github.com/ava-labs/avalanchego/snow/networking/handler=Handler=snow/networking/handler/mock_handler.go -github.com/ava-labs/avalanchego/snow/networking/timeout=Manager=snow/networking/timeout/mock_manager.go -github.com/ava-labs/avalanchego/snow/networking/tracker=Targeter=snow/networking/tracker/mock_targeter.go -github.com/ava-labs/avalanchego/snow/networking/tracker=Tracker=snow/networking/tracker/mock_resource_tracker.go -github.com/ava-labs/avalanchego/snow/uptime=Calculator=snow/uptime/mock_calculator.go -github.com/ava-labs/avalanchego/snow/validators=State=snow/validators/mock_state.go -github.com/ava-labs/avalanchego/snow/validators=SubnetConnector=snow/validators/mock_subnet_connector.go -github.com/ava-labs/avalanchego/utils/crypto/keychain=Ledger=utils/crypto/keychain/mock_ledger.go -github.com/ava-labs/avalanchego/utils/filesystem=Reader=utils/filesystem/mock_io.go -github.com/ava-labs/avalanchego/utils/hashing=Hasher=utils/hashing/mock_hasher.go -github.com/ava-labs/avalanchego/utils/resource=User=utils/resource/mock_user.go -github.com/ava-labs/avalanchego/vms/avm/block=Block=vms/avm/block/mock_block.go -github.com/ava-labs/avalanchego/vms/avm/metrics=Metrics=vms/avm/metrics/mock_metrics.go -github.com/ava-labs/avalanchego/vms/avm/state=Chain,State,Diff=vms/avm/state/mock_state.go -github.com/ava-labs/avalanchego/vms/avm/txs/mempool=Mempool=vms/avm/txs/mempool/mock_mempool.go -github.com/ava-labs/avalanchego/vms/components/avax=TransferableIn=vms/components/avax/mock_transferable_in.go -github.com/ava-labs/avalanchego/vms/components/verify=Verifiable=vms/components/verify/mock_verifiable.go -github.com/ava-labs/avalanchego/vms/platformvm/block=Block=vms/platformvm/block/mock_block.go -github.com/ava-labs/avalanchego/vms/platformvm/state=Chain,Diff,State=vms/platformvm/state/mock_state.go -github.com/ava-labs/avalanchego/vms/platformvm/state=StakerIterator=vms/platformvm/state/mock_staker_iterator.go -github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool=Mempool=vms/platformvm/txs/mempool/mock_mempool.go -github.com/ava-labs/avalanchego/vms/platformvm/utxo=Verifier=vms/platformvm/utxo/mock_verifier.go -github.com/ava-labs/avalanchego/vms/proposervm/proposer=Windower=vms/proposervm/proposer/mock_windower.go -github.com/ava-labs/avalanchego/vms/proposervm/scheduler=Scheduler=vms/proposervm/scheduler/mock_scheduler.go -github.com/ava-labs/avalanchego/vms/proposervm/state=State=vms/proposervm/state/mock_state.go -github.com/ava-labs/avalanchego/vms/proposervm=PostForkBlock=vms/proposervm/mock_post_fork_block.go -github.com/ava-labs/avalanchego/vms/registry=VMGetter=vms/registry/mock_vm_getter.go -github.com/ava-labs/avalanchego/vms/registry=VMRegistry=vms/registry/mock_vm_registry.go -github.com/ava-labs/avalanchego/vms=Factory,Manager=vms/mock_manager.go -github.com/ava-labs/avalanchego/x/sync=Client=x/sync/mock_client.go -github.com/ava-labs/avalanchego/x/sync=NetworkClient=x/sync/mock_network_client.go +github.com/ava-labs/avalanchego/api/server=Server=api/server/servermock/server.go +github.com/ava-labs/avalanchego/chains/atomic=SharedMemory=chains/atomic/atomicmock/shared_memory.go +github.com/ava-labs/avalanchego/codec=Manager=codec/codecmock/manager.go +github.com/ava-labs/avalanchego/database=Batch=database/databasemock/batch.go +github.com/ava-labs/avalanchego/database=Iterator=database/databasemock/iterator.go +github.com/ava-labs/avalanchego/message=OutboundMessage=message/messagemock/outbound_message.go +github.com/ava-labs/avalanchego/message=OutboundMsgBuilder=message/messagemock/outbound_message_builder.go +github.com/ava-labs/avalanchego/snow/consensus/snowman=Block=snow/consensus/snowman/snowmanmock/block.go +github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex=LinearizableVM=snow/engine/avalanche/vertex/vertexmock/linearizable_vm.go +github.com/ava-labs/avalanchego/snow/engine/snowman/block=BuildBlockWithContextChainVM=snow/engine/snowman/block/blockmock/build_block_with_context_chain_vm.go +github.com/ava-labs/avalanchego/snow/engine/snowman/block=ChainVM=snow/engine/snowman/block/blockmock/chain_vm.go +github.com/ava-labs/avalanchego/snow/engine/snowman/block=StateSyncableVM=snow/engine/snowman/block/blockmock/state_syncable_vm.go +github.com/ava-labs/avalanchego/snow/engine/snowman/block=WithVerifyContext=snow/engine/snowman/block/blockmock/with_verify_context.go +github.com/ava-labs/avalanchego/snow/networking/handler=Handler=snow/networking/handler/handlermock/handler.go +github.com/ava-labs/avalanchego/snow/networking/timeout=Manager=snow/networking/timeout/timeoutmock/manager.go +github.com/ava-labs/avalanchego/snow/networking/tracker=Targeter=snow/networking/tracker/trackermock/targeter.go +github.com/ava-labs/avalanchego/snow/networking/tracker=Tracker=snow/networking/tracker/trackermock/tracker.go +github.com/ava-labs/avalanchego/snow/uptime=Calculator=snow/uptime/uptimemock/calculator.go +github.com/ava-labs/avalanchego/snow/validators=State=snow/validators/validatorsmock/state.go +github.com/ava-labs/avalanchego/snow/validators=SubnetConnector=snow/validators/validatorsmock/subnet_connector.go +github.com/ava-labs/avalanchego/utils/crypto/keychain=Ledger=utils/crypto/keychain/keychainmock/ledger.go +github.com/ava-labs/avalanchego/utils/filesystem=Reader=utils/filesystem/filesystemmock/reader.go +github.com/ava-labs/avalanchego/utils/hashing=Hasher=utils/hashing/hashingmock/hasher.go +github.com/ava-labs/avalanchego/utils/resource=User=utils/resource/resourcemock/user.go +github.com/ava-labs/avalanchego/vms/avm/metrics=Metrics=vms/avm/metrics/metricsmock/metrics.go +github.com/ava-labs/avalanchego/vms/avm/state=Chain=vms/avm/state/statemock/chain.go +github.com/ava-labs/avalanchego/vms/avm/state=Diff=vms/avm/state/statemock/diff.go +github.com/ava-labs/avalanchego/vms/avm/state=State=vms/avm/state/statemock/state.go +github.com/ava-labs/avalanchego/vms/avm/txs/mempool=Mempool=vms/avm/txs/mempool/mempoolmock/mempool.go +github.com/ava-labs/avalanchego/vms/components/avax=TransferableIn=vms/components/avax/avaxmock/transferable_in.go +github.com/ava-labs/avalanchego/vms/components/verify=Verifiable=vms/components/verify/verifymock/verifiable.go +github.com/ava-labs/avalanchego/vms/platformvm/fx=Fx=vms/platformvm/fx/fxmock/fx.go +github.com/ava-labs/avalanchego/vms/platformvm/state=Chain=vms/platformvm/state/statemock/chain.go +github.com/ava-labs/avalanchego/vms/platformvm/state=Diff=vms/platformvm/state/statemock/diff.go +github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool=Mempool=vms/platformvm/txs/mempool/mempoolmock/mempool.go +github.com/ava-labs/avalanchego/vms/platformvm/utxo=Verifier=vms/platformvm/utxo/utxomock/verifier.go +github.com/ava-labs/avalanchego/vms/proposervm/proposer=Windower=vms/proposervm/proposer/proposermock/windower.go +github.com/ava-labs/avalanchego/vms/proposervm/scheduler=Scheduler=vms/proposervm/scheduler/schedulermock/scheduler.go +github.com/ava-labs/avalanchego/vms/proposervm/state=State=vms/proposervm/state/statemock/state.go +github.com/ava-labs/avalanchego/vms/registry=VMGetter=vms/registry/registrymock/vm_getter.go +github.com/ava-labs/avalanchego/vms/registry=VMRegistry=vms/registry/registrymock/vm_registry.go +github.com/ava-labs/avalanchego/vms=Factory=vms/vmsmock/factory.go +github.com/ava-labs/avalanchego/vms=Manager=vms/vmsmock/manager.go +github.com/ava-labs/avalanchego/x/sync=NetworkClient=x/sync/syncmock/network_client.go diff --git a/snow/consensus/snowman/snowmantest/mock_block.go b/snow/consensus/snowman/snowmanmock/block.go similarity index 58% rename from snow/consensus/snowman/snowmantest/mock_block.go rename to snow/consensus/snowman/snowmanmock/block.go index 233e979e3a86..e3f179229c77 100644 --- a/snow/consensus/snowman/snowmantest/mock_block.go +++ b/snow/consensus/snowman/snowmanmock/block.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=snowmantest -destination=snow/consensus/snowman/snowmantest/mock_block.go github.com/ava-labs/avalanchego/snow/consensus/snowman Block +// mockgen -package=snowmanmock -destination=snow/consensus/snowman/snowmanmock/block.go -mock_names=Block=Block github.com/ava-labs/avalanchego/snow/consensus/snowman Block // -// Package snowmantest is a generated GoMock package. -package snowmantest +// Package snowmanmock is a generated GoMock package. +package snowmanmock import ( context "context" @@ -18,31 +18,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockBlock is a mock of Block interface. -type MockBlock struct { +// Block is a mock of Block interface. +type Block struct { ctrl *gomock.Controller - recorder *MockBlockMockRecorder + recorder *BlockMockRecorder } -// MockBlockMockRecorder is the mock recorder for MockBlock. -type MockBlockMockRecorder struct { - mock *MockBlock +// BlockMockRecorder is the mock recorder for Block. +type BlockMockRecorder struct { + mock *Block } -// NewMockBlock creates a new mock instance. -func NewMockBlock(ctrl *gomock.Controller) *MockBlock { - mock := &MockBlock{ctrl: ctrl} - mock.recorder = &MockBlockMockRecorder{mock} +// NewBlock creates a new mock instance. +func NewBlock(ctrl *gomock.Controller) *Block { + mock := &Block{ctrl: ctrl} + mock.recorder = &BlockMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBlock) EXPECT() *MockBlockMockRecorder { +func (m *Block) EXPECT() *BlockMockRecorder { return m.recorder } // Accept mocks base method. -func (m *MockBlock) Accept(arg0 context.Context) error { +func (m *Block) Accept(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Accept", arg0) ret0, _ := ret[0].(error) @@ -50,13 +50,13 @@ func (m *MockBlock) Accept(arg0 context.Context) error { } // Accept indicates an expected call of Accept. -func (mr *MockBlockMockRecorder) Accept(arg0 any) *gomock.Call { +func (mr *BlockMockRecorder) Accept(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Accept", reflect.TypeOf((*MockBlock)(nil).Accept), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Accept", reflect.TypeOf((*Block)(nil).Accept), arg0) } // Bytes mocks base method. -func (m *MockBlock) Bytes() []byte { +func (m *Block) Bytes() []byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bytes") ret0, _ := ret[0].([]byte) @@ -64,13 +64,13 @@ func (m *MockBlock) Bytes() []byte { } // Bytes indicates an expected call of Bytes. -func (mr *MockBlockMockRecorder) Bytes() *gomock.Call { +func (mr *BlockMockRecorder) Bytes() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*MockBlock)(nil).Bytes)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*Block)(nil).Bytes)) } // Height mocks base method. -func (m *MockBlock) Height() uint64 { +func (m *Block) Height() uint64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Height") ret0, _ := ret[0].(uint64) @@ -78,13 +78,13 @@ func (m *MockBlock) Height() uint64 { } // Height indicates an expected call of Height. -func (mr *MockBlockMockRecorder) Height() *gomock.Call { +func (mr *BlockMockRecorder) Height() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Height", reflect.TypeOf((*MockBlock)(nil).Height)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Height", reflect.TypeOf((*Block)(nil).Height)) } // ID mocks base method. -func (m *MockBlock) ID() ids.ID { +func (m *Block) ID() ids.ID { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ID") ret0, _ := ret[0].(ids.ID) @@ -92,13 +92,13 @@ func (m *MockBlock) ID() ids.ID { } // ID indicates an expected call of ID. -func (mr *MockBlockMockRecorder) ID() *gomock.Call { +func (mr *BlockMockRecorder) ID() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ID", reflect.TypeOf((*MockBlock)(nil).ID)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ID", reflect.TypeOf((*Block)(nil).ID)) } // Parent mocks base method. -func (m *MockBlock) Parent() ids.ID { +func (m *Block) Parent() ids.ID { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Parent") ret0, _ := ret[0].(ids.ID) @@ -106,13 +106,13 @@ func (m *MockBlock) Parent() ids.ID { } // Parent indicates an expected call of Parent. -func (mr *MockBlockMockRecorder) Parent() *gomock.Call { +func (mr *BlockMockRecorder) Parent() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Parent", reflect.TypeOf((*MockBlock)(nil).Parent)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Parent", reflect.TypeOf((*Block)(nil).Parent)) } // Reject mocks base method. -func (m *MockBlock) Reject(arg0 context.Context) error { +func (m *Block) Reject(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Reject", arg0) ret0, _ := ret[0].(error) @@ -120,13 +120,13 @@ func (m *MockBlock) Reject(arg0 context.Context) error { } // Reject indicates an expected call of Reject. -func (mr *MockBlockMockRecorder) Reject(arg0 any) *gomock.Call { +func (mr *BlockMockRecorder) Reject(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reject", reflect.TypeOf((*MockBlock)(nil).Reject), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reject", reflect.TypeOf((*Block)(nil).Reject), arg0) } // Timestamp mocks base method. -func (m *MockBlock) Timestamp() time.Time { +func (m *Block) Timestamp() time.Time { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Timestamp") ret0, _ := ret[0].(time.Time) @@ -134,13 +134,13 @@ func (m *MockBlock) Timestamp() time.Time { } // Timestamp indicates an expected call of Timestamp. -func (mr *MockBlockMockRecorder) Timestamp() *gomock.Call { +func (mr *BlockMockRecorder) Timestamp() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Timestamp", reflect.TypeOf((*MockBlock)(nil).Timestamp)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Timestamp", reflect.TypeOf((*Block)(nil).Timestamp)) } // Verify mocks base method. -func (m *MockBlock) Verify(arg0 context.Context) error { +func (m *Block) Verify(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Verify", arg0) ret0, _ := ret[0].(error) @@ -148,7 +148,7 @@ func (m *MockBlock) Verify(arg0 context.Context) error { } // Verify indicates an expected call of Verify. -func (mr *MockBlockMockRecorder) Verify(arg0 any) *gomock.Call { +func (mr *BlockMockRecorder) Verify(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockBlock)(nil).Verify), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*Block)(nil).Verify), arg0) } diff --git a/snow/engine/avalanche/vertex/mock_vm.go b/snow/engine/avalanche/vertex/vertexmock/linearizable_vm.go similarity index 54% rename from snow/engine/avalanche/vertex/mock_vm.go rename to snow/engine/avalanche/vertex/vertexmock/linearizable_vm.go index 9687aa884e7c..491d25617944 100644 --- a/snow/engine/avalanche/vertex/mock_vm.go +++ b/snow/engine/avalanche/vertex/vertexmock/linearizable_vm.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=vertex -destination=snow/engine/avalanche/vertex/mock_vm.go github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex LinearizableVM +// mockgen -package=vertexmock -destination=snow/engine/avalanche/vertex/vertexmock/linearizable_vm.go -mock_names=LinearizableVM=LinearizableVM github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex LinearizableVM // -// Package vertex is a generated GoMock package. -package vertex +// Package vertexmock is a generated GoMock package. +package vertexmock import ( context "context" @@ -25,31 +25,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockLinearizableVM is a mock of LinearizableVM interface. -type MockLinearizableVM struct { +// LinearizableVM is a mock of LinearizableVM interface. +type LinearizableVM struct { ctrl *gomock.Controller - recorder *MockLinearizableVMMockRecorder + recorder *LinearizableVMMockRecorder } -// MockLinearizableVMMockRecorder is the mock recorder for MockLinearizableVM. -type MockLinearizableVMMockRecorder struct { - mock *MockLinearizableVM +// LinearizableVMMockRecorder is the mock recorder for LinearizableVM. +type LinearizableVMMockRecorder struct { + mock *LinearizableVM } -// NewMockLinearizableVM creates a new mock instance. -func NewMockLinearizableVM(ctrl *gomock.Controller) *MockLinearizableVM { - mock := &MockLinearizableVM{ctrl: ctrl} - mock.recorder = &MockLinearizableVMMockRecorder{mock} +// NewLinearizableVM creates a new mock instance. +func NewLinearizableVM(ctrl *gomock.Controller) *LinearizableVM { + mock := &LinearizableVM{ctrl: ctrl} + mock.recorder = &LinearizableVMMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockLinearizableVM) EXPECT() *MockLinearizableVMMockRecorder { +func (m *LinearizableVM) EXPECT() *LinearizableVMMockRecorder { return m.recorder } // AppGossip mocks base method. -func (m *MockLinearizableVM) AppGossip(arg0 context.Context, arg1 ids.NodeID, arg2 []byte) error { +func (m *LinearizableVM) AppGossip(arg0 context.Context, arg1 ids.NodeID, arg2 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppGossip", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -57,13 +57,13 @@ func (m *MockLinearizableVM) AppGossip(arg0 context.Context, arg1 ids.NodeID, ar } // AppGossip indicates an expected call of AppGossip. -func (mr *MockLinearizableVMMockRecorder) AppGossip(arg0, arg1, arg2 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) AppGossip(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppGossip", reflect.TypeOf((*MockLinearizableVM)(nil).AppGossip), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppGossip", reflect.TypeOf((*LinearizableVM)(nil).AppGossip), arg0, arg1, arg2) } // AppRequest mocks base method. -func (m *MockLinearizableVM) AppRequest(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 time.Time, arg4 []byte) error { +func (m *LinearizableVM) AppRequest(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 time.Time, arg4 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppRequest", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(error) @@ -71,13 +71,13 @@ func (m *MockLinearizableVM) AppRequest(arg0 context.Context, arg1 ids.NodeID, a } // AppRequest indicates an expected call of AppRequest. -func (mr *MockLinearizableVMMockRecorder) AppRequest(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) AppRequest(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequest", reflect.TypeOf((*MockLinearizableVM)(nil).AppRequest), arg0, arg1, arg2, arg3, arg4) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequest", reflect.TypeOf((*LinearizableVM)(nil).AppRequest), arg0, arg1, arg2, arg3, arg4) } // AppRequestFailed mocks base method. -func (m *MockLinearizableVM) AppRequestFailed(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 *common.AppError) error { +func (m *LinearizableVM) AppRequestFailed(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 *common.AppError) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppRequestFailed", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) @@ -85,13 +85,13 @@ func (m *MockLinearizableVM) AppRequestFailed(arg0 context.Context, arg1 ids.Nod } // AppRequestFailed indicates an expected call of AppRequestFailed. -func (mr *MockLinearizableVMMockRecorder) AppRequestFailed(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) AppRequestFailed(arg0, arg1, arg2, arg3 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequestFailed", reflect.TypeOf((*MockLinearizableVM)(nil).AppRequestFailed), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequestFailed", reflect.TypeOf((*LinearizableVM)(nil).AppRequestFailed), arg0, arg1, arg2, arg3) } // AppResponse mocks base method. -func (m *MockLinearizableVM) AppResponse(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 []byte) error { +func (m *LinearizableVM) AppResponse(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppResponse", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) @@ -99,13 +99,13 @@ func (m *MockLinearizableVM) AppResponse(arg0 context.Context, arg1 ids.NodeID, } // AppResponse indicates an expected call of AppResponse. -func (mr *MockLinearizableVMMockRecorder) AppResponse(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) AppResponse(arg0, arg1, arg2, arg3 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppResponse", reflect.TypeOf((*MockLinearizableVM)(nil).AppResponse), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppResponse", reflect.TypeOf((*LinearizableVM)(nil).AppResponse), arg0, arg1, arg2, arg3) } // BuildBlock mocks base method. -func (m *MockLinearizableVM) BuildBlock(arg0 context.Context) (snowman.Block, error) { +func (m *LinearizableVM) BuildBlock(arg0 context.Context) (snowman.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BuildBlock", arg0) ret0, _ := ret[0].(snowman.Block) @@ -114,13 +114,13 @@ func (m *MockLinearizableVM) BuildBlock(arg0 context.Context) (snowman.Block, er } // BuildBlock indicates an expected call of BuildBlock. -func (mr *MockLinearizableVMMockRecorder) BuildBlock(arg0 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) BuildBlock(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildBlock", reflect.TypeOf((*MockLinearizableVM)(nil).BuildBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildBlock", reflect.TypeOf((*LinearizableVM)(nil).BuildBlock), arg0) } // Connected mocks base method. -func (m *MockLinearizableVM) Connected(arg0 context.Context, arg1 ids.NodeID, arg2 *version.Application) error { +func (m *LinearizableVM) Connected(arg0 context.Context, arg1 ids.NodeID, arg2 *version.Application) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Connected", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -128,13 +128,13 @@ func (m *MockLinearizableVM) Connected(arg0 context.Context, arg1 ids.NodeID, ar } // Connected indicates an expected call of Connected. -func (mr *MockLinearizableVMMockRecorder) Connected(arg0, arg1, arg2 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) Connected(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connected", reflect.TypeOf((*MockLinearizableVM)(nil).Connected), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connected", reflect.TypeOf((*LinearizableVM)(nil).Connected), arg0, arg1, arg2) } // CreateHandlers mocks base method. -func (m *MockLinearizableVM) CreateHandlers(arg0 context.Context) (map[string]http.Handler, error) { +func (m *LinearizableVM) CreateHandlers(arg0 context.Context) (map[string]http.Handler, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateHandlers", arg0) ret0, _ := ret[0].(map[string]http.Handler) @@ -143,13 +143,13 @@ func (m *MockLinearizableVM) CreateHandlers(arg0 context.Context) (map[string]ht } // CreateHandlers indicates an expected call of CreateHandlers. -func (mr *MockLinearizableVMMockRecorder) CreateHandlers(arg0 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) CreateHandlers(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateHandlers", reflect.TypeOf((*MockLinearizableVM)(nil).CreateHandlers), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateHandlers", reflect.TypeOf((*LinearizableVM)(nil).CreateHandlers), arg0) } // Disconnected mocks base method. -func (m *MockLinearizableVM) Disconnected(arg0 context.Context, arg1 ids.NodeID) error { +func (m *LinearizableVM) Disconnected(arg0 context.Context, arg1 ids.NodeID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Disconnected", arg0, arg1) ret0, _ := ret[0].(error) @@ -157,13 +157,13 @@ func (m *MockLinearizableVM) Disconnected(arg0 context.Context, arg1 ids.NodeID) } // Disconnected indicates an expected call of Disconnected. -func (mr *MockLinearizableVMMockRecorder) Disconnected(arg0, arg1 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) Disconnected(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnected", reflect.TypeOf((*MockLinearizableVM)(nil).Disconnected), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnected", reflect.TypeOf((*LinearizableVM)(nil).Disconnected), arg0, arg1) } // GetBlock mocks base method. -func (m *MockLinearizableVM) GetBlock(arg0 context.Context, arg1 ids.ID) (snowman.Block, error) { +func (m *LinearizableVM) GetBlock(arg0 context.Context, arg1 ids.ID) (snowman.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBlock", arg0, arg1) ret0, _ := ret[0].(snowman.Block) @@ -172,13 +172,13 @@ func (m *MockLinearizableVM) GetBlock(arg0 context.Context, arg1 ids.ID) (snowma } // GetBlock indicates an expected call of GetBlock. -func (mr *MockLinearizableVMMockRecorder) GetBlock(arg0, arg1 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) GetBlock(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*MockLinearizableVM)(nil).GetBlock), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*LinearizableVM)(nil).GetBlock), arg0, arg1) } // GetBlockIDAtHeight mocks base method. -func (m *MockLinearizableVM) GetBlockIDAtHeight(arg0 context.Context, arg1 uint64) (ids.ID, error) { +func (m *LinearizableVM) GetBlockIDAtHeight(arg0 context.Context, arg1 uint64) (ids.ID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0, arg1) ret0, _ := ret[0].(ids.ID) @@ -187,13 +187,13 @@ func (m *MockLinearizableVM) GetBlockIDAtHeight(arg0 context.Context, arg1 uint6 } // GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. -func (mr *MockLinearizableVMMockRecorder) GetBlockIDAtHeight(arg0, arg1 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) GetBlockIDAtHeight(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*MockLinearizableVM)(nil).GetBlockIDAtHeight), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*LinearizableVM)(nil).GetBlockIDAtHeight), arg0, arg1) } // HealthCheck mocks base method. -func (m *MockLinearizableVM) HealthCheck(arg0 context.Context) (any, error) { +func (m *LinearizableVM) HealthCheck(arg0 context.Context) (any, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HealthCheck", arg0) ret0, _ := ret[0].(any) @@ -202,13 +202,13 @@ func (m *MockLinearizableVM) HealthCheck(arg0 context.Context) (any, error) { } // HealthCheck indicates an expected call of HealthCheck. -func (mr *MockLinearizableVMMockRecorder) HealthCheck(arg0 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) HealthCheck(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*MockLinearizableVM)(nil).HealthCheck), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*LinearizableVM)(nil).HealthCheck), arg0) } // Initialize mocks base method. -func (m *MockLinearizableVM) Initialize(arg0 context.Context, arg1 *snow.Context, arg2 database.Database, arg3, arg4, arg5 []byte, arg6 chan<- common.Message, arg7 []*common.Fx, arg8 common.AppSender) error { +func (m *LinearizableVM) Initialize(arg0 context.Context, arg1 *snow.Context, arg2 database.Database, arg3, arg4, arg5 []byte, arg6 chan<- common.Message, arg7 []*common.Fx, arg8 common.AppSender) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Initialize", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) ret0, _ := ret[0].(error) @@ -216,13 +216,13 @@ func (m *MockLinearizableVM) Initialize(arg0 context.Context, arg1 *snow.Context } // Initialize indicates an expected call of Initialize. -func (mr *MockLinearizableVMMockRecorder) Initialize(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) Initialize(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*MockLinearizableVM)(nil).Initialize), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*LinearizableVM)(nil).Initialize), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) } // LastAccepted mocks base method. -func (m *MockLinearizableVM) LastAccepted(arg0 context.Context) (ids.ID, error) { +func (m *LinearizableVM) LastAccepted(arg0 context.Context) (ids.ID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LastAccepted", arg0) ret0, _ := ret[0].(ids.ID) @@ -231,13 +231,13 @@ func (m *MockLinearizableVM) LastAccepted(arg0 context.Context) (ids.ID, error) } // LastAccepted indicates an expected call of LastAccepted. -func (mr *MockLinearizableVMMockRecorder) LastAccepted(arg0 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) LastAccepted(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAccepted", reflect.TypeOf((*MockLinearizableVM)(nil).LastAccepted), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAccepted", reflect.TypeOf((*LinearizableVM)(nil).LastAccepted), arg0) } // Linearize mocks base method. -func (m *MockLinearizableVM) Linearize(arg0 context.Context, arg1 ids.ID) error { +func (m *LinearizableVM) Linearize(arg0 context.Context, arg1 ids.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Linearize", arg0, arg1) ret0, _ := ret[0].(error) @@ -245,13 +245,13 @@ func (m *MockLinearizableVM) Linearize(arg0 context.Context, arg1 ids.ID) error } // Linearize indicates an expected call of Linearize. -func (mr *MockLinearizableVMMockRecorder) Linearize(arg0, arg1 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) Linearize(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Linearize", reflect.TypeOf((*MockLinearizableVM)(nil).Linearize), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Linearize", reflect.TypeOf((*LinearizableVM)(nil).Linearize), arg0, arg1) } // ParseBlock mocks base method. -func (m *MockLinearizableVM) ParseBlock(arg0 context.Context, arg1 []byte) (snowman.Block, error) { +func (m *LinearizableVM) ParseBlock(arg0 context.Context, arg1 []byte) (snowman.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ParseBlock", arg0, arg1) ret0, _ := ret[0].(snowman.Block) @@ -260,13 +260,13 @@ func (m *MockLinearizableVM) ParseBlock(arg0 context.Context, arg1 []byte) (snow } // ParseBlock indicates an expected call of ParseBlock. -func (mr *MockLinearizableVMMockRecorder) ParseBlock(arg0, arg1 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) ParseBlock(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseBlock", reflect.TypeOf((*MockLinearizableVM)(nil).ParseBlock), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseBlock", reflect.TypeOf((*LinearizableVM)(nil).ParseBlock), arg0, arg1) } // ParseTx mocks base method. -func (m *MockLinearizableVM) ParseTx(arg0 context.Context, arg1 []byte) (snowstorm.Tx, error) { +func (m *LinearizableVM) ParseTx(arg0 context.Context, arg1 []byte) (snowstorm.Tx, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ParseTx", arg0, arg1) ret0, _ := ret[0].(snowstorm.Tx) @@ -275,13 +275,13 @@ func (m *MockLinearizableVM) ParseTx(arg0 context.Context, arg1 []byte) (snowsto } // ParseTx indicates an expected call of ParseTx. -func (mr *MockLinearizableVMMockRecorder) ParseTx(arg0, arg1 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) ParseTx(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseTx", reflect.TypeOf((*MockLinearizableVM)(nil).ParseTx), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseTx", reflect.TypeOf((*LinearizableVM)(nil).ParseTx), arg0, arg1) } // SetPreference mocks base method. -func (m *MockLinearizableVM) SetPreference(arg0 context.Context, arg1 ids.ID) error { +func (m *LinearizableVM) SetPreference(arg0 context.Context, arg1 ids.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetPreference", arg0, arg1) ret0, _ := ret[0].(error) @@ -289,13 +289,13 @@ func (m *MockLinearizableVM) SetPreference(arg0 context.Context, arg1 ids.ID) er } // SetPreference indicates an expected call of SetPreference. -func (mr *MockLinearizableVMMockRecorder) SetPreference(arg0, arg1 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) SetPreference(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPreference", reflect.TypeOf((*MockLinearizableVM)(nil).SetPreference), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPreference", reflect.TypeOf((*LinearizableVM)(nil).SetPreference), arg0, arg1) } // SetState mocks base method. -func (m *MockLinearizableVM) SetState(arg0 context.Context, arg1 snow.State) error { +func (m *LinearizableVM) SetState(arg0 context.Context, arg1 snow.State) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetState", arg0, arg1) ret0, _ := ret[0].(error) @@ -303,13 +303,13 @@ func (m *MockLinearizableVM) SetState(arg0 context.Context, arg1 snow.State) err } // SetState indicates an expected call of SetState. -func (mr *MockLinearizableVMMockRecorder) SetState(arg0, arg1 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) SetState(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetState", reflect.TypeOf((*MockLinearizableVM)(nil).SetState), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetState", reflect.TypeOf((*LinearizableVM)(nil).SetState), arg0, arg1) } // Shutdown mocks base method. -func (m *MockLinearizableVM) Shutdown(arg0 context.Context) error { +func (m *LinearizableVM) Shutdown(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Shutdown", arg0) ret0, _ := ret[0].(error) @@ -317,13 +317,13 @@ func (m *MockLinearizableVM) Shutdown(arg0 context.Context) error { } // Shutdown indicates an expected call of Shutdown. -func (mr *MockLinearizableVMMockRecorder) Shutdown(arg0 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) Shutdown(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*MockLinearizableVM)(nil).Shutdown), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*LinearizableVM)(nil).Shutdown), arg0) } // Version mocks base method. -func (m *MockLinearizableVM) Version(arg0 context.Context) (string, error) { +func (m *LinearizableVM) Version(arg0 context.Context) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Version", arg0) ret0, _ := ret[0].(string) @@ -332,7 +332,7 @@ func (m *MockLinearizableVM) Version(arg0 context.Context) (string, error) { } // Version indicates an expected call of Version. -func (mr *MockLinearizableVMMockRecorder) Version(arg0 any) *gomock.Call { +func (mr *LinearizableVMMockRecorder) Version(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Version", reflect.TypeOf((*MockLinearizableVM)(nil).Version), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Version", reflect.TypeOf((*LinearizableVM)(nil).Version), arg0) } diff --git a/snow/engine/common/commonmock/sender.go b/snow/engine/common/commonmock/sender.go new file mode 100644 index 000000000000..fa9a0070ede7 --- /dev/null +++ b/snow/engine/common/commonmock/sender.go @@ -0,0 +1,279 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: snow/engine/common/sender.go +// +// Generated by this command: +// +// mockgen -source=snow/engine/common/sender.go -destination=snow/engine/common/commonmock/sender.go -package=commonmock -exclude_interfaces=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,Gossiper -mock_names=Sender=Sender +// + +// Package commonmock is a generated GoMock package. +package commonmock + +import ( + context "context" + reflect "reflect" + + ids "github.com/ava-labs/avalanchego/ids" + common "github.com/ava-labs/avalanchego/snow/engine/common" + set "github.com/ava-labs/avalanchego/utils/set" + gomock "go.uber.org/mock/gomock" +) + +// Sender is a mock of Sender interface. +type Sender struct { + ctrl *gomock.Controller + recorder *SenderMockRecorder +} + +// SenderMockRecorder is the mock recorder for Sender. +type SenderMockRecorder struct { + mock *Sender +} + +// NewSender creates a new mock instance. +func NewSender(ctrl *gomock.Controller) *Sender { + mock := &Sender{ctrl: ctrl} + mock.recorder = &SenderMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Sender) EXPECT() *SenderMockRecorder { + return m.recorder +} + +// SendAccepted mocks base method. +func (m *Sender) SendAccepted(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerIDs []ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendAccepted", ctx, nodeID, requestID, containerIDs) +} + +// SendAccepted indicates an expected call of SendAccepted. +func (mr *SenderMockRecorder) SendAccepted(ctx, nodeID, requestID, containerIDs any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAccepted", reflect.TypeOf((*Sender)(nil).SendAccepted), ctx, nodeID, requestID, containerIDs) +} + +// SendAcceptedFrontier mocks base method. +func (m *Sender) SendAcceptedFrontier(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendAcceptedFrontier", ctx, nodeID, requestID, containerID) +} + +// SendAcceptedFrontier indicates an expected call of SendAcceptedFrontier. +func (mr *SenderMockRecorder) SendAcceptedFrontier(ctx, nodeID, requestID, containerID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAcceptedFrontier", reflect.TypeOf((*Sender)(nil).SendAcceptedFrontier), ctx, nodeID, requestID, containerID) +} + +// SendAcceptedStateSummary mocks base method. +func (m *Sender) SendAcceptedStateSummary(ctx context.Context, nodeID ids.NodeID, requestID uint32, summaryIDs []ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendAcceptedStateSummary", ctx, nodeID, requestID, summaryIDs) +} + +// SendAcceptedStateSummary indicates an expected call of SendAcceptedStateSummary. +func (mr *SenderMockRecorder) SendAcceptedStateSummary(ctx, nodeID, requestID, summaryIDs any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAcceptedStateSummary", reflect.TypeOf((*Sender)(nil).SendAcceptedStateSummary), ctx, nodeID, requestID, summaryIDs) +} + +// SendAncestors mocks base method. +func (m *Sender) SendAncestors(ctx context.Context, nodeID ids.NodeID, requestID uint32, containers [][]byte) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendAncestors", ctx, nodeID, requestID, containers) +} + +// SendAncestors indicates an expected call of SendAncestors. +func (mr *SenderMockRecorder) SendAncestors(ctx, nodeID, requestID, containers any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAncestors", reflect.TypeOf((*Sender)(nil).SendAncestors), ctx, nodeID, requestID, containers) +} + +// SendAppError mocks base method. +func (m *Sender) SendAppError(ctx context.Context, nodeID ids.NodeID, requestID uint32, errorCode int32, errorMessage string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendAppError", ctx, nodeID, requestID, errorCode, errorMessage) + ret0, _ := ret[0].(error) + return ret0 +} + +// SendAppError indicates an expected call of SendAppError. +func (mr *SenderMockRecorder) SendAppError(ctx, nodeID, requestID, errorCode, errorMessage any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppError", reflect.TypeOf((*Sender)(nil).SendAppError), ctx, nodeID, requestID, errorCode, errorMessage) +} + +// SendAppGossip mocks base method. +func (m *Sender) SendAppGossip(ctx context.Context, config common.SendConfig, appGossipBytes []byte) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendAppGossip", ctx, config, appGossipBytes) + ret0, _ := ret[0].(error) + return ret0 +} + +// SendAppGossip indicates an expected call of SendAppGossip. +func (mr *SenderMockRecorder) SendAppGossip(ctx, config, appGossipBytes any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppGossip", reflect.TypeOf((*Sender)(nil).SendAppGossip), ctx, config, appGossipBytes) +} + +// SendAppRequest mocks base method. +func (m *Sender) SendAppRequest(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, appRequestBytes []byte) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendAppRequest", ctx, nodeIDs, requestID, appRequestBytes) + ret0, _ := ret[0].(error) + return ret0 +} + +// SendAppRequest indicates an expected call of SendAppRequest. +func (mr *SenderMockRecorder) SendAppRequest(ctx, nodeIDs, requestID, appRequestBytes any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppRequest", reflect.TypeOf((*Sender)(nil).SendAppRequest), ctx, nodeIDs, requestID, appRequestBytes) +} + +// SendAppResponse mocks base method. +func (m *Sender) SendAppResponse(ctx context.Context, nodeID ids.NodeID, requestID uint32, appResponseBytes []byte) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SendAppResponse", ctx, nodeID, requestID, appResponseBytes) + ret0, _ := ret[0].(error) + return ret0 +} + +// SendAppResponse indicates an expected call of SendAppResponse. +func (mr *SenderMockRecorder) SendAppResponse(ctx, nodeID, requestID, appResponseBytes any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppResponse", reflect.TypeOf((*Sender)(nil).SendAppResponse), ctx, nodeID, requestID, appResponseBytes) +} + +// SendChits mocks base method. +func (m *Sender) SendChits(ctx context.Context, nodeID ids.NodeID, requestID uint32, preferredID, preferredIDAtHeight, acceptedID ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendChits", ctx, nodeID, requestID, preferredID, preferredIDAtHeight, acceptedID) +} + +// SendChits indicates an expected call of SendChits. +func (mr *SenderMockRecorder) SendChits(ctx, nodeID, requestID, preferredID, preferredIDAtHeight, acceptedID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendChits", reflect.TypeOf((*Sender)(nil).SendChits), ctx, nodeID, requestID, preferredID, preferredIDAtHeight, acceptedID) +} + +// SendGet mocks base method. +func (m *Sender) SendGet(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendGet", ctx, nodeID, requestID, containerID) +} + +// SendGet indicates an expected call of SendGet. +func (mr *SenderMockRecorder) SendGet(ctx, nodeID, requestID, containerID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGet", reflect.TypeOf((*Sender)(nil).SendGet), ctx, nodeID, requestID, containerID) +} + +// SendGetAccepted mocks base method. +func (m *Sender) SendGetAccepted(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, containerIDs []ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendGetAccepted", ctx, nodeIDs, requestID, containerIDs) +} + +// SendGetAccepted indicates an expected call of SendGetAccepted. +func (mr *SenderMockRecorder) SendGetAccepted(ctx, nodeIDs, requestID, containerIDs any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetAccepted", reflect.TypeOf((*Sender)(nil).SendGetAccepted), ctx, nodeIDs, requestID, containerIDs) +} + +// SendGetAcceptedFrontier mocks base method. +func (m *Sender) SendGetAcceptedFrontier(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendGetAcceptedFrontier", ctx, nodeIDs, requestID) +} + +// SendGetAcceptedFrontier indicates an expected call of SendGetAcceptedFrontier. +func (mr *SenderMockRecorder) SendGetAcceptedFrontier(ctx, nodeIDs, requestID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetAcceptedFrontier", reflect.TypeOf((*Sender)(nil).SendGetAcceptedFrontier), ctx, nodeIDs, requestID) +} + +// SendGetAcceptedStateSummary mocks base method. +func (m *Sender) SendGetAcceptedStateSummary(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, heights []uint64) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendGetAcceptedStateSummary", ctx, nodeIDs, requestID, heights) +} + +// SendGetAcceptedStateSummary indicates an expected call of SendGetAcceptedStateSummary. +func (mr *SenderMockRecorder) SendGetAcceptedStateSummary(ctx, nodeIDs, requestID, heights any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetAcceptedStateSummary", reflect.TypeOf((*Sender)(nil).SendGetAcceptedStateSummary), ctx, nodeIDs, requestID, heights) +} + +// SendGetAncestors mocks base method. +func (m *Sender) SendGetAncestors(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendGetAncestors", ctx, nodeID, requestID, containerID) +} + +// SendGetAncestors indicates an expected call of SendGetAncestors. +func (mr *SenderMockRecorder) SendGetAncestors(ctx, nodeID, requestID, containerID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetAncestors", reflect.TypeOf((*Sender)(nil).SendGetAncestors), ctx, nodeID, requestID, containerID) +} + +// SendGetStateSummaryFrontier mocks base method. +func (m *Sender) SendGetStateSummaryFrontier(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendGetStateSummaryFrontier", ctx, nodeIDs, requestID) +} + +// SendGetStateSummaryFrontier indicates an expected call of SendGetStateSummaryFrontier. +func (mr *SenderMockRecorder) SendGetStateSummaryFrontier(ctx, nodeIDs, requestID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetStateSummaryFrontier", reflect.TypeOf((*Sender)(nil).SendGetStateSummaryFrontier), ctx, nodeIDs, requestID) +} + +// SendPullQuery mocks base method. +func (m *Sender) SendPullQuery(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, containerID ids.ID, requestedHeight uint64) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendPullQuery", ctx, nodeIDs, requestID, containerID, requestedHeight) +} + +// SendPullQuery indicates an expected call of SendPullQuery. +func (mr *SenderMockRecorder) SendPullQuery(ctx, nodeIDs, requestID, containerID, requestedHeight any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPullQuery", reflect.TypeOf((*Sender)(nil).SendPullQuery), ctx, nodeIDs, requestID, containerID, requestedHeight) +} + +// SendPushQuery mocks base method. +func (m *Sender) SendPushQuery(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, container []byte, requestedHeight uint64) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendPushQuery", ctx, nodeIDs, requestID, container, requestedHeight) +} + +// SendPushQuery indicates an expected call of SendPushQuery. +func (mr *SenderMockRecorder) SendPushQuery(ctx, nodeIDs, requestID, container, requestedHeight any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPushQuery", reflect.TypeOf((*Sender)(nil).SendPushQuery), ctx, nodeIDs, requestID, container, requestedHeight) +} + +// SendPut mocks base method. +func (m *Sender) SendPut(ctx context.Context, nodeID ids.NodeID, requestID uint32, container []byte) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendPut", ctx, nodeID, requestID, container) +} + +// SendPut indicates an expected call of SendPut. +func (mr *SenderMockRecorder) SendPut(ctx, nodeID, requestID, container any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPut", reflect.TypeOf((*Sender)(nil).SendPut), ctx, nodeID, requestID, container) +} + +// SendStateSummaryFrontier mocks base method. +func (m *Sender) SendStateSummaryFrontier(ctx context.Context, nodeID ids.NodeID, requestID uint32, summary []byte) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SendStateSummaryFrontier", ctx, nodeID, requestID, summary) +} + +// SendStateSummaryFrontier indicates an expected call of SendStateSummaryFrontier. +func (mr *SenderMockRecorder) SendStateSummaryFrontier(ctx, nodeID, requestID, summary any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendStateSummaryFrontier", reflect.TypeOf((*Sender)(nil).SendStateSummaryFrontier), ctx, nodeID, requestID, summary) +} diff --git a/snow/engine/common/mock_sender.go b/snow/engine/common/mock_sender.go deleted file mode 100644 index 737adba95ade..000000000000 --- a/snow/engine/common/mock_sender.go +++ /dev/null @@ -1,278 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: snow/engine/common/sender.go -// -// Generated by this command: -// -// mockgen -source=snow/engine/common/sender.go -destination=snow/engine/common/mock_sender.go -package=common -exclude_interfaces=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,Gossiper -// - -// Package common is a generated GoMock package. -package common - -import ( - context "context" - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - set "github.com/ava-labs/avalanchego/utils/set" - gomock "go.uber.org/mock/gomock" -) - -// MockSender is a mock of Sender interface. -type MockSender struct { - ctrl *gomock.Controller - recorder *MockSenderMockRecorder -} - -// MockSenderMockRecorder is the mock recorder for MockSender. -type MockSenderMockRecorder struct { - mock *MockSender -} - -// NewMockSender creates a new mock instance. -func NewMockSender(ctrl *gomock.Controller) *MockSender { - mock := &MockSender{ctrl: ctrl} - mock.recorder = &MockSenderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSender) EXPECT() *MockSenderMockRecorder { - return m.recorder -} - -// SendAccepted mocks base method. -func (m *MockSender) SendAccepted(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerIDs []ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendAccepted", ctx, nodeID, requestID, containerIDs) -} - -// SendAccepted indicates an expected call of SendAccepted. -func (mr *MockSenderMockRecorder) SendAccepted(ctx, nodeID, requestID, containerIDs any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAccepted", reflect.TypeOf((*MockSender)(nil).SendAccepted), ctx, nodeID, requestID, containerIDs) -} - -// SendAcceptedFrontier mocks base method. -func (m *MockSender) SendAcceptedFrontier(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendAcceptedFrontier", ctx, nodeID, requestID, containerID) -} - -// SendAcceptedFrontier indicates an expected call of SendAcceptedFrontier. -func (mr *MockSenderMockRecorder) SendAcceptedFrontier(ctx, nodeID, requestID, containerID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAcceptedFrontier", reflect.TypeOf((*MockSender)(nil).SendAcceptedFrontier), ctx, nodeID, requestID, containerID) -} - -// SendAcceptedStateSummary mocks base method. -func (m *MockSender) SendAcceptedStateSummary(ctx context.Context, nodeID ids.NodeID, requestID uint32, summaryIDs []ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendAcceptedStateSummary", ctx, nodeID, requestID, summaryIDs) -} - -// SendAcceptedStateSummary indicates an expected call of SendAcceptedStateSummary. -func (mr *MockSenderMockRecorder) SendAcceptedStateSummary(ctx, nodeID, requestID, summaryIDs any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAcceptedStateSummary", reflect.TypeOf((*MockSender)(nil).SendAcceptedStateSummary), ctx, nodeID, requestID, summaryIDs) -} - -// SendAncestors mocks base method. -func (m *MockSender) SendAncestors(ctx context.Context, nodeID ids.NodeID, requestID uint32, containers [][]byte) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendAncestors", ctx, nodeID, requestID, containers) -} - -// SendAncestors indicates an expected call of SendAncestors. -func (mr *MockSenderMockRecorder) SendAncestors(ctx, nodeID, requestID, containers any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAncestors", reflect.TypeOf((*MockSender)(nil).SendAncestors), ctx, nodeID, requestID, containers) -} - -// SendAppError mocks base method. -func (m *MockSender) SendAppError(ctx context.Context, nodeID ids.NodeID, requestID uint32, errorCode int32, errorMessage string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendAppError", ctx, nodeID, requestID, errorCode, errorMessage) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendAppError indicates an expected call of SendAppError. -func (mr *MockSenderMockRecorder) SendAppError(ctx, nodeID, requestID, errorCode, errorMessage any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppError", reflect.TypeOf((*MockSender)(nil).SendAppError), ctx, nodeID, requestID, errorCode, errorMessage) -} - -// SendAppGossip mocks base method. -func (m *MockSender) SendAppGossip(ctx context.Context, config SendConfig, appGossipBytes []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendAppGossip", ctx, config, appGossipBytes) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendAppGossip indicates an expected call of SendAppGossip. -func (mr *MockSenderMockRecorder) SendAppGossip(ctx, config, appGossipBytes any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppGossip", reflect.TypeOf((*MockSender)(nil).SendAppGossip), ctx, config, appGossipBytes) -} - -// SendAppRequest mocks base method. -func (m *MockSender) SendAppRequest(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, appRequestBytes []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendAppRequest", ctx, nodeIDs, requestID, appRequestBytes) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendAppRequest indicates an expected call of SendAppRequest. -func (mr *MockSenderMockRecorder) SendAppRequest(ctx, nodeIDs, requestID, appRequestBytes any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppRequest", reflect.TypeOf((*MockSender)(nil).SendAppRequest), ctx, nodeIDs, requestID, appRequestBytes) -} - -// SendAppResponse mocks base method. -func (m *MockSender) SendAppResponse(ctx context.Context, nodeID ids.NodeID, requestID uint32, appResponseBytes []byte) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SendAppResponse", ctx, nodeID, requestID, appResponseBytes) - ret0, _ := ret[0].(error) - return ret0 -} - -// SendAppResponse indicates an expected call of SendAppResponse. -func (mr *MockSenderMockRecorder) SendAppResponse(ctx, nodeID, requestID, appResponseBytes any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendAppResponse", reflect.TypeOf((*MockSender)(nil).SendAppResponse), ctx, nodeID, requestID, appResponseBytes) -} - -// SendChits mocks base method. -func (m *MockSender) SendChits(ctx context.Context, nodeID ids.NodeID, requestID uint32, preferredID, preferredIDAtHeight, acceptedID ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendChits", ctx, nodeID, requestID, preferredID, preferredIDAtHeight, acceptedID) -} - -// SendChits indicates an expected call of SendChits. -func (mr *MockSenderMockRecorder) SendChits(ctx, nodeID, requestID, preferredID, preferredIDAtHeight, acceptedID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendChits", reflect.TypeOf((*MockSender)(nil).SendChits), ctx, nodeID, requestID, preferredID, preferredIDAtHeight, acceptedID) -} - -// SendGet mocks base method. -func (m *MockSender) SendGet(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendGet", ctx, nodeID, requestID, containerID) -} - -// SendGet indicates an expected call of SendGet. -func (mr *MockSenderMockRecorder) SendGet(ctx, nodeID, requestID, containerID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGet", reflect.TypeOf((*MockSender)(nil).SendGet), ctx, nodeID, requestID, containerID) -} - -// SendGetAccepted mocks base method. -func (m *MockSender) SendGetAccepted(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, containerIDs []ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendGetAccepted", ctx, nodeIDs, requestID, containerIDs) -} - -// SendGetAccepted indicates an expected call of SendGetAccepted. -func (mr *MockSenderMockRecorder) SendGetAccepted(ctx, nodeIDs, requestID, containerIDs any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetAccepted", reflect.TypeOf((*MockSender)(nil).SendGetAccepted), ctx, nodeIDs, requestID, containerIDs) -} - -// SendGetAcceptedFrontier mocks base method. -func (m *MockSender) SendGetAcceptedFrontier(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendGetAcceptedFrontier", ctx, nodeIDs, requestID) -} - -// SendGetAcceptedFrontier indicates an expected call of SendGetAcceptedFrontier. -func (mr *MockSenderMockRecorder) SendGetAcceptedFrontier(ctx, nodeIDs, requestID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetAcceptedFrontier", reflect.TypeOf((*MockSender)(nil).SendGetAcceptedFrontier), ctx, nodeIDs, requestID) -} - -// SendGetAcceptedStateSummary mocks base method. -func (m *MockSender) SendGetAcceptedStateSummary(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, heights []uint64) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendGetAcceptedStateSummary", ctx, nodeIDs, requestID, heights) -} - -// SendGetAcceptedStateSummary indicates an expected call of SendGetAcceptedStateSummary. -func (mr *MockSenderMockRecorder) SendGetAcceptedStateSummary(ctx, nodeIDs, requestID, heights any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetAcceptedStateSummary", reflect.TypeOf((*MockSender)(nil).SendGetAcceptedStateSummary), ctx, nodeIDs, requestID, heights) -} - -// SendGetAncestors mocks base method. -func (m *MockSender) SendGetAncestors(ctx context.Context, nodeID ids.NodeID, requestID uint32, containerID ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendGetAncestors", ctx, nodeID, requestID, containerID) -} - -// SendGetAncestors indicates an expected call of SendGetAncestors. -func (mr *MockSenderMockRecorder) SendGetAncestors(ctx, nodeID, requestID, containerID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetAncestors", reflect.TypeOf((*MockSender)(nil).SendGetAncestors), ctx, nodeID, requestID, containerID) -} - -// SendGetStateSummaryFrontier mocks base method. -func (m *MockSender) SendGetStateSummaryFrontier(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendGetStateSummaryFrontier", ctx, nodeIDs, requestID) -} - -// SendGetStateSummaryFrontier indicates an expected call of SendGetStateSummaryFrontier. -func (mr *MockSenderMockRecorder) SendGetStateSummaryFrontier(ctx, nodeIDs, requestID any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendGetStateSummaryFrontier", reflect.TypeOf((*MockSender)(nil).SendGetStateSummaryFrontier), ctx, nodeIDs, requestID) -} - -// SendPullQuery mocks base method. -func (m *MockSender) SendPullQuery(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, containerID ids.ID, requestedHeight uint64) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendPullQuery", ctx, nodeIDs, requestID, containerID, requestedHeight) -} - -// SendPullQuery indicates an expected call of SendPullQuery. -func (mr *MockSenderMockRecorder) SendPullQuery(ctx, nodeIDs, requestID, containerID, requestedHeight any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPullQuery", reflect.TypeOf((*MockSender)(nil).SendPullQuery), ctx, nodeIDs, requestID, containerID, requestedHeight) -} - -// SendPushQuery mocks base method. -func (m *MockSender) SendPushQuery(ctx context.Context, nodeIDs set.Set[ids.NodeID], requestID uint32, container []byte, requestedHeight uint64) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendPushQuery", ctx, nodeIDs, requestID, container, requestedHeight) -} - -// SendPushQuery indicates an expected call of SendPushQuery. -func (mr *MockSenderMockRecorder) SendPushQuery(ctx, nodeIDs, requestID, container, requestedHeight any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPushQuery", reflect.TypeOf((*MockSender)(nil).SendPushQuery), ctx, nodeIDs, requestID, container, requestedHeight) -} - -// SendPut mocks base method. -func (m *MockSender) SendPut(ctx context.Context, nodeID ids.NodeID, requestID uint32, container []byte) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendPut", ctx, nodeID, requestID, container) -} - -// SendPut indicates an expected call of SendPut. -func (mr *MockSenderMockRecorder) SendPut(ctx, nodeID, requestID, container any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendPut", reflect.TypeOf((*MockSender)(nil).SendPut), ctx, nodeID, requestID, container) -} - -// SendStateSummaryFrontier mocks base method. -func (m *MockSender) SendStateSummaryFrontier(ctx context.Context, nodeID ids.NodeID, requestID uint32, summary []byte) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SendStateSummaryFrontier", ctx, nodeID, requestID, summary) -} - -// SendStateSummaryFrontier indicates an expected call of SendStateSummaryFrontier. -func (mr *MockSenderMockRecorder) SendStateSummaryFrontier(ctx, nodeID, requestID, summary any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SendStateSummaryFrontier", reflect.TypeOf((*MockSender)(nil).SendStateSummaryFrontier), ctx, nodeID, requestID, summary) -} diff --git a/snow/engine/snowman/block/blockmock/build_block_with_context_chain_vm.go b/snow/engine/snowman/block/blockmock/build_block_with_context_chain_vm.go new file mode 100644 index 000000000000..5106fef25848 --- /dev/null +++ b/snow/engine/snowman/block/blockmock/build_block_with_context_chain_vm.go @@ -0,0 +1,57 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/snow/engine/snowman/block (interfaces: BuildBlockWithContextChainVM) +// +// Generated by this command: +// +// mockgen -package=blockmock -destination=snow/engine/snowman/block/blockmock/build_block_with_context_chain_vm.go -mock_names=BuildBlockWithContextChainVM=BuildBlockWithContextChainVM github.com/ava-labs/avalanchego/snow/engine/snowman/block BuildBlockWithContextChainVM +// + +// Package blockmock is a generated GoMock package. +package blockmock + +import ( + context "context" + reflect "reflect" + + snowman "github.com/ava-labs/avalanchego/snow/consensus/snowman" + block "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + gomock "go.uber.org/mock/gomock" +) + +// BuildBlockWithContextChainVM is a mock of BuildBlockWithContextChainVM interface. +type BuildBlockWithContextChainVM struct { + ctrl *gomock.Controller + recorder *BuildBlockWithContextChainVMMockRecorder +} + +// BuildBlockWithContextChainVMMockRecorder is the mock recorder for BuildBlockWithContextChainVM. +type BuildBlockWithContextChainVMMockRecorder struct { + mock *BuildBlockWithContextChainVM +} + +// NewBuildBlockWithContextChainVM creates a new mock instance. +func NewBuildBlockWithContextChainVM(ctrl *gomock.Controller) *BuildBlockWithContextChainVM { + mock := &BuildBlockWithContextChainVM{ctrl: ctrl} + mock.recorder = &BuildBlockWithContextChainVMMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *BuildBlockWithContextChainVM) EXPECT() *BuildBlockWithContextChainVMMockRecorder { + return m.recorder +} + +// BuildBlockWithContext mocks base method. +func (m *BuildBlockWithContextChainVM) BuildBlockWithContext(arg0 context.Context, arg1 *block.Context) (snowman.Block, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "BuildBlockWithContext", arg0, arg1) + ret0, _ := ret[0].(snowman.Block) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// BuildBlockWithContext indicates an expected call of BuildBlockWithContext. +func (mr *BuildBlockWithContextChainVMMockRecorder) BuildBlockWithContext(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildBlockWithContext", reflect.TypeOf((*BuildBlockWithContextChainVM)(nil).BuildBlockWithContext), arg0, arg1) +} diff --git a/snow/engine/snowman/block/mock_chain_vm.go b/snow/engine/snowman/block/blockmock/chain_vm.go similarity index 56% rename from snow/engine/snowman/block/mock_chain_vm.go rename to snow/engine/snowman/block/blockmock/chain_vm.go index 4e7d7d7387fd..5dc21630bb11 100644 --- a/snow/engine/snowman/block/mock_chain_vm.go +++ b/snow/engine/snowman/block/blockmock/chain_vm.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=block -destination=snow/engine/snowman/block/mock_chain_vm.go github.com/ava-labs/avalanchego/snow/engine/snowman/block ChainVM +// mockgen -package=blockmock -destination=snow/engine/snowman/block/blockmock/chain_vm.go -mock_names=ChainVM=ChainVM github.com/ava-labs/avalanchego/snow/engine/snowman/block ChainVM // -// Package block is a generated GoMock package. -package block +// Package blockmock is a generated GoMock package. +package blockmock import ( context "context" @@ -24,31 +24,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockChainVM is a mock of ChainVM interface. -type MockChainVM struct { +// ChainVM is a mock of ChainVM interface. +type ChainVM struct { ctrl *gomock.Controller - recorder *MockChainVMMockRecorder + recorder *ChainVMMockRecorder } -// MockChainVMMockRecorder is the mock recorder for MockChainVM. -type MockChainVMMockRecorder struct { - mock *MockChainVM +// ChainVMMockRecorder is the mock recorder for ChainVM. +type ChainVMMockRecorder struct { + mock *ChainVM } -// NewMockChainVM creates a new mock instance. -func NewMockChainVM(ctrl *gomock.Controller) *MockChainVM { - mock := &MockChainVM{ctrl: ctrl} - mock.recorder = &MockChainVMMockRecorder{mock} +// NewChainVM creates a new mock instance. +func NewChainVM(ctrl *gomock.Controller) *ChainVM { + mock := &ChainVM{ctrl: ctrl} + mock.recorder = &ChainVMMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockChainVM) EXPECT() *MockChainVMMockRecorder { +func (m *ChainVM) EXPECT() *ChainVMMockRecorder { return m.recorder } // AppGossip mocks base method. -func (m *MockChainVM) AppGossip(arg0 context.Context, arg1 ids.NodeID, arg2 []byte) error { +func (m *ChainVM) AppGossip(arg0 context.Context, arg1 ids.NodeID, arg2 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppGossip", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -56,13 +56,13 @@ func (m *MockChainVM) AppGossip(arg0 context.Context, arg1 ids.NodeID, arg2 []by } // AppGossip indicates an expected call of AppGossip. -func (mr *MockChainVMMockRecorder) AppGossip(arg0, arg1, arg2 any) *gomock.Call { +func (mr *ChainVMMockRecorder) AppGossip(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppGossip", reflect.TypeOf((*MockChainVM)(nil).AppGossip), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppGossip", reflect.TypeOf((*ChainVM)(nil).AppGossip), arg0, arg1, arg2) } // AppRequest mocks base method. -func (m *MockChainVM) AppRequest(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 time.Time, arg4 []byte) error { +func (m *ChainVM) AppRequest(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 time.Time, arg4 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppRequest", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(error) @@ -70,13 +70,13 @@ func (m *MockChainVM) AppRequest(arg0 context.Context, arg1 ids.NodeID, arg2 uin } // AppRequest indicates an expected call of AppRequest. -func (mr *MockChainVMMockRecorder) AppRequest(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { +func (mr *ChainVMMockRecorder) AppRequest(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequest", reflect.TypeOf((*MockChainVM)(nil).AppRequest), arg0, arg1, arg2, arg3, arg4) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequest", reflect.TypeOf((*ChainVM)(nil).AppRequest), arg0, arg1, arg2, arg3, arg4) } // AppRequestFailed mocks base method. -func (m *MockChainVM) AppRequestFailed(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 *common.AppError) error { +func (m *ChainVM) AppRequestFailed(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 *common.AppError) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppRequestFailed", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) @@ -84,13 +84,13 @@ func (m *MockChainVM) AppRequestFailed(arg0 context.Context, arg1 ids.NodeID, ar } // AppRequestFailed indicates an expected call of AppRequestFailed. -func (mr *MockChainVMMockRecorder) AppRequestFailed(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *ChainVMMockRecorder) AppRequestFailed(arg0, arg1, arg2, arg3 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequestFailed", reflect.TypeOf((*MockChainVM)(nil).AppRequestFailed), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequestFailed", reflect.TypeOf((*ChainVM)(nil).AppRequestFailed), arg0, arg1, arg2, arg3) } // AppResponse mocks base method. -func (m *MockChainVM) AppResponse(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 []byte) error { +func (m *ChainVM) AppResponse(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppResponse", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) @@ -98,13 +98,13 @@ func (m *MockChainVM) AppResponse(arg0 context.Context, arg1 ids.NodeID, arg2 ui } // AppResponse indicates an expected call of AppResponse. -func (mr *MockChainVMMockRecorder) AppResponse(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *ChainVMMockRecorder) AppResponse(arg0, arg1, arg2, arg3 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppResponse", reflect.TypeOf((*MockChainVM)(nil).AppResponse), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppResponse", reflect.TypeOf((*ChainVM)(nil).AppResponse), arg0, arg1, arg2, arg3) } // BuildBlock mocks base method. -func (m *MockChainVM) BuildBlock(arg0 context.Context) (snowman.Block, error) { +func (m *ChainVM) BuildBlock(arg0 context.Context) (snowman.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BuildBlock", arg0) ret0, _ := ret[0].(snowman.Block) @@ -113,13 +113,13 @@ func (m *MockChainVM) BuildBlock(arg0 context.Context) (snowman.Block, error) { } // BuildBlock indicates an expected call of BuildBlock. -func (mr *MockChainVMMockRecorder) BuildBlock(arg0 any) *gomock.Call { +func (mr *ChainVMMockRecorder) BuildBlock(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildBlock", reflect.TypeOf((*MockChainVM)(nil).BuildBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildBlock", reflect.TypeOf((*ChainVM)(nil).BuildBlock), arg0) } // Connected mocks base method. -func (m *MockChainVM) Connected(arg0 context.Context, arg1 ids.NodeID, arg2 *version.Application) error { +func (m *ChainVM) Connected(arg0 context.Context, arg1 ids.NodeID, arg2 *version.Application) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Connected", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -127,13 +127,13 @@ func (m *MockChainVM) Connected(arg0 context.Context, arg1 ids.NodeID, arg2 *ver } // Connected indicates an expected call of Connected. -func (mr *MockChainVMMockRecorder) Connected(arg0, arg1, arg2 any) *gomock.Call { +func (mr *ChainVMMockRecorder) Connected(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connected", reflect.TypeOf((*MockChainVM)(nil).Connected), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connected", reflect.TypeOf((*ChainVM)(nil).Connected), arg0, arg1, arg2) } // CreateHandlers mocks base method. -func (m *MockChainVM) CreateHandlers(arg0 context.Context) (map[string]http.Handler, error) { +func (m *ChainVM) CreateHandlers(arg0 context.Context) (map[string]http.Handler, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CreateHandlers", arg0) ret0, _ := ret[0].(map[string]http.Handler) @@ -142,13 +142,13 @@ func (m *MockChainVM) CreateHandlers(arg0 context.Context) (map[string]http.Hand } // CreateHandlers indicates an expected call of CreateHandlers. -func (mr *MockChainVMMockRecorder) CreateHandlers(arg0 any) *gomock.Call { +func (mr *ChainVMMockRecorder) CreateHandlers(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateHandlers", reflect.TypeOf((*MockChainVM)(nil).CreateHandlers), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateHandlers", reflect.TypeOf((*ChainVM)(nil).CreateHandlers), arg0) } // Disconnected mocks base method. -func (m *MockChainVM) Disconnected(arg0 context.Context, arg1 ids.NodeID) error { +func (m *ChainVM) Disconnected(arg0 context.Context, arg1 ids.NodeID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Disconnected", arg0, arg1) ret0, _ := ret[0].(error) @@ -156,13 +156,13 @@ func (m *MockChainVM) Disconnected(arg0 context.Context, arg1 ids.NodeID) error } // Disconnected indicates an expected call of Disconnected. -func (mr *MockChainVMMockRecorder) Disconnected(arg0, arg1 any) *gomock.Call { +func (mr *ChainVMMockRecorder) Disconnected(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnected", reflect.TypeOf((*MockChainVM)(nil).Disconnected), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnected", reflect.TypeOf((*ChainVM)(nil).Disconnected), arg0, arg1) } // GetBlock mocks base method. -func (m *MockChainVM) GetBlock(arg0 context.Context, arg1 ids.ID) (snowman.Block, error) { +func (m *ChainVM) GetBlock(arg0 context.Context, arg1 ids.ID) (snowman.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBlock", arg0, arg1) ret0, _ := ret[0].(snowman.Block) @@ -171,13 +171,13 @@ func (m *MockChainVM) GetBlock(arg0 context.Context, arg1 ids.ID) (snowman.Block } // GetBlock indicates an expected call of GetBlock. -func (mr *MockChainVMMockRecorder) GetBlock(arg0, arg1 any) *gomock.Call { +func (mr *ChainVMMockRecorder) GetBlock(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*MockChainVM)(nil).GetBlock), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*ChainVM)(nil).GetBlock), arg0, arg1) } // GetBlockIDAtHeight mocks base method. -func (m *MockChainVM) GetBlockIDAtHeight(arg0 context.Context, arg1 uint64) (ids.ID, error) { +func (m *ChainVM) GetBlockIDAtHeight(arg0 context.Context, arg1 uint64) (ids.ID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0, arg1) ret0, _ := ret[0].(ids.ID) @@ -186,13 +186,13 @@ func (m *MockChainVM) GetBlockIDAtHeight(arg0 context.Context, arg1 uint64) (ids } // GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. -func (mr *MockChainVMMockRecorder) GetBlockIDAtHeight(arg0, arg1 any) *gomock.Call { +func (mr *ChainVMMockRecorder) GetBlockIDAtHeight(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*MockChainVM)(nil).GetBlockIDAtHeight), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*ChainVM)(nil).GetBlockIDAtHeight), arg0, arg1) } // HealthCheck mocks base method. -func (m *MockChainVM) HealthCheck(arg0 context.Context) (any, error) { +func (m *ChainVM) HealthCheck(arg0 context.Context) (any, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HealthCheck", arg0) ret0, _ := ret[0].(any) @@ -201,13 +201,13 @@ func (m *MockChainVM) HealthCheck(arg0 context.Context) (any, error) { } // HealthCheck indicates an expected call of HealthCheck. -func (mr *MockChainVMMockRecorder) HealthCheck(arg0 any) *gomock.Call { +func (mr *ChainVMMockRecorder) HealthCheck(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*MockChainVM)(nil).HealthCheck), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*ChainVM)(nil).HealthCheck), arg0) } // Initialize mocks base method. -func (m *MockChainVM) Initialize(arg0 context.Context, arg1 *snow.Context, arg2 database.Database, arg3, arg4, arg5 []byte, arg6 chan<- common.Message, arg7 []*common.Fx, arg8 common.AppSender) error { +func (m *ChainVM) Initialize(arg0 context.Context, arg1 *snow.Context, arg2 database.Database, arg3, arg4, arg5 []byte, arg6 chan<- common.Message, arg7 []*common.Fx, arg8 common.AppSender) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Initialize", arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) ret0, _ := ret[0].(error) @@ -215,13 +215,13 @@ func (m *MockChainVM) Initialize(arg0 context.Context, arg1 *snow.Context, arg2 } // Initialize indicates an expected call of Initialize. -func (mr *MockChainVMMockRecorder) Initialize(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 any) *gomock.Call { +func (mr *ChainVMMockRecorder) Initialize(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*MockChainVM)(nil).Initialize), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*ChainVM)(nil).Initialize), arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) } // LastAccepted mocks base method. -func (m *MockChainVM) LastAccepted(arg0 context.Context) (ids.ID, error) { +func (m *ChainVM) LastAccepted(arg0 context.Context) (ids.ID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LastAccepted", arg0) ret0, _ := ret[0].(ids.ID) @@ -230,13 +230,13 @@ func (m *MockChainVM) LastAccepted(arg0 context.Context) (ids.ID, error) { } // LastAccepted indicates an expected call of LastAccepted. -func (mr *MockChainVMMockRecorder) LastAccepted(arg0 any) *gomock.Call { +func (mr *ChainVMMockRecorder) LastAccepted(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAccepted", reflect.TypeOf((*MockChainVM)(nil).LastAccepted), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAccepted", reflect.TypeOf((*ChainVM)(nil).LastAccepted), arg0) } // ParseBlock mocks base method. -func (m *MockChainVM) ParseBlock(arg0 context.Context, arg1 []byte) (snowman.Block, error) { +func (m *ChainVM) ParseBlock(arg0 context.Context, arg1 []byte) (snowman.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ParseBlock", arg0, arg1) ret0, _ := ret[0].(snowman.Block) @@ -245,13 +245,13 @@ func (m *MockChainVM) ParseBlock(arg0 context.Context, arg1 []byte) (snowman.Blo } // ParseBlock indicates an expected call of ParseBlock. -func (mr *MockChainVMMockRecorder) ParseBlock(arg0, arg1 any) *gomock.Call { +func (mr *ChainVMMockRecorder) ParseBlock(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseBlock", reflect.TypeOf((*MockChainVM)(nil).ParseBlock), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseBlock", reflect.TypeOf((*ChainVM)(nil).ParseBlock), arg0, arg1) } // SetPreference mocks base method. -func (m *MockChainVM) SetPreference(arg0 context.Context, arg1 ids.ID) error { +func (m *ChainVM) SetPreference(arg0 context.Context, arg1 ids.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetPreference", arg0, arg1) ret0, _ := ret[0].(error) @@ -259,13 +259,13 @@ func (m *MockChainVM) SetPreference(arg0 context.Context, arg1 ids.ID) error { } // SetPreference indicates an expected call of SetPreference. -func (mr *MockChainVMMockRecorder) SetPreference(arg0, arg1 any) *gomock.Call { +func (mr *ChainVMMockRecorder) SetPreference(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPreference", reflect.TypeOf((*MockChainVM)(nil).SetPreference), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPreference", reflect.TypeOf((*ChainVM)(nil).SetPreference), arg0, arg1) } // SetState mocks base method. -func (m *MockChainVM) SetState(arg0 context.Context, arg1 snow.State) error { +func (m *ChainVM) SetState(arg0 context.Context, arg1 snow.State) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetState", arg0, arg1) ret0, _ := ret[0].(error) @@ -273,13 +273,13 @@ func (m *MockChainVM) SetState(arg0 context.Context, arg1 snow.State) error { } // SetState indicates an expected call of SetState. -func (mr *MockChainVMMockRecorder) SetState(arg0, arg1 any) *gomock.Call { +func (mr *ChainVMMockRecorder) SetState(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetState", reflect.TypeOf((*MockChainVM)(nil).SetState), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetState", reflect.TypeOf((*ChainVM)(nil).SetState), arg0, arg1) } // Shutdown mocks base method. -func (m *MockChainVM) Shutdown(arg0 context.Context) error { +func (m *ChainVM) Shutdown(arg0 context.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Shutdown", arg0) ret0, _ := ret[0].(error) @@ -287,13 +287,13 @@ func (m *MockChainVM) Shutdown(arg0 context.Context) error { } // Shutdown indicates an expected call of Shutdown. -func (mr *MockChainVMMockRecorder) Shutdown(arg0 any) *gomock.Call { +func (mr *ChainVMMockRecorder) Shutdown(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*MockChainVM)(nil).Shutdown), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*ChainVM)(nil).Shutdown), arg0) } // Version mocks base method. -func (m *MockChainVM) Version(arg0 context.Context) (string, error) { +func (m *ChainVM) Version(arg0 context.Context) (string, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Version", arg0) ret0, _ := ret[0].(string) @@ -302,7 +302,7 @@ func (m *MockChainVM) Version(arg0 context.Context) (string, error) { } // Version indicates an expected call of Version. -func (mr *MockChainVMMockRecorder) Version(arg0 any) *gomock.Call { +func (mr *ChainVMMockRecorder) Version(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Version", reflect.TypeOf((*MockChainVM)(nil).Version), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Version", reflect.TypeOf((*ChainVM)(nil).Version), arg0) } diff --git a/snow/engine/snowman/block/blockmock/state_syncable_vm.go b/snow/engine/snowman/block/blockmock/state_syncable_vm.go new file mode 100644 index 000000000000..cd44c7c8c7fa --- /dev/null +++ b/snow/engine/snowman/block/blockmock/state_syncable_vm.go @@ -0,0 +1,116 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/snow/engine/snowman/block (interfaces: StateSyncableVM) +// +// Generated by this command: +// +// mockgen -package=blockmock -destination=snow/engine/snowman/block/blockmock/state_syncable_vm.go -mock_names=StateSyncableVM=StateSyncableVM github.com/ava-labs/avalanchego/snow/engine/snowman/block StateSyncableVM +// + +// Package blockmock is a generated GoMock package. +package blockmock + +import ( + context "context" + reflect "reflect" + + block "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + gomock "go.uber.org/mock/gomock" +) + +// StateSyncableVM is a mock of StateSyncableVM interface. +type StateSyncableVM struct { + ctrl *gomock.Controller + recorder *StateSyncableVMMockRecorder +} + +// StateSyncableVMMockRecorder is the mock recorder for StateSyncableVM. +type StateSyncableVMMockRecorder struct { + mock *StateSyncableVM +} + +// NewStateSyncableVM creates a new mock instance. +func NewStateSyncableVM(ctrl *gomock.Controller) *StateSyncableVM { + mock := &StateSyncableVM{ctrl: ctrl} + mock.recorder = &StateSyncableVMMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *StateSyncableVM) EXPECT() *StateSyncableVMMockRecorder { + return m.recorder +} + +// GetLastStateSummary mocks base method. +func (m *StateSyncableVM) GetLastStateSummary(arg0 context.Context) (block.StateSummary, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetLastStateSummary", arg0) + ret0, _ := ret[0].(block.StateSummary) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetLastStateSummary indicates an expected call of GetLastStateSummary. +func (mr *StateSyncableVMMockRecorder) GetLastStateSummary(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastStateSummary", reflect.TypeOf((*StateSyncableVM)(nil).GetLastStateSummary), arg0) +} + +// GetOngoingSyncStateSummary mocks base method. +func (m *StateSyncableVM) GetOngoingSyncStateSummary(arg0 context.Context) (block.StateSummary, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetOngoingSyncStateSummary", arg0) + ret0, _ := ret[0].(block.StateSummary) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetOngoingSyncStateSummary indicates an expected call of GetOngoingSyncStateSummary. +func (mr *StateSyncableVMMockRecorder) GetOngoingSyncStateSummary(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOngoingSyncStateSummary", reflect.TypeOf((*StateSyncableVM)(nil).GetOngoingSyncStateSummary), arg0) +} + +// GetStateSummary mocks base method. +func (m *StateSyncableVM) GetStateSummary(arg0 context.Context, arg1 uint64) (block.StateSummary, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetStateSummary", arg0, arg1) + ret0, _ := ret[0].(block.StateSummary) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetStateSummary indicates an expected call of GetStateSummary. +func (mr *StateSyncableVMMockRecorder) GetStateSummary(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStateSummary", reflect.TypeOf((*StateSyncableVM)(nil).GetStateSummary), arg0, arg1) +} + +// ParseStateSummary mocks base method. +func (m *StateSyncableVM) ParseStateSummary(arg0 context.Context, arg1 []byte) (block.StateSummary, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ParseStateSummary", arg0, arg1) + ret0, _ := ret[0].(block.StateSummary) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ParseStateSummary indicates an expected call of ParseStateSummary. +func (mr *StateSyncableVMMockRecorder) ParseStateSummary(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseStateSummary", reflect.TypeOf((*StateSyncableVM)(nil).ParseStateSummary), arg0, arg1) +} + +// StateSyncEnabled mocks base method. +func (m *StateSyncableVM) StateSyncEnabled(arg0 context.Context) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "StateSyncEnabled", arg0) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// StateSyncEnabled indicates an expected call of StateSyncEnabled. +func (mr *StateSyncableVMMockRecorder) StateSyncEnabled(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateSyncEnabled", reflect.TypeOf((*StateSyncableVM)(nil).StateSyncEnabled), arg0) +} diff --git a/snow/engine/snowman/block/blockmock/with_verify_context.go b/snow/engine/snowman/block/blockmock/with_verify_context.go new file mode 100644 index 000000000000..03b52475e13b --- /dev/null +++ b/snow/engine/snowman/block/blockmock/with_verify_context.go @@ -0,0 +1,70 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/snow/engine/snowman/block (interfaces: WithVerifyContext) +// +// Generated by this command: +// +// mockgen -package=blockmock -destination=snow/engine/snowman/block/blockmock/with_verify_context.go -mock_names=WithVerifyContext=WithVerifyContext github.com/ava-labs/avalanchego/snow/engine/snowman/block WithVerifyContext +// + +// Package blockmock is a generated GoMock package. +package blockmock + +import ( + context "context" + reflect "reflect" + + block "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + gomock "go.uber.org/mock/gomock" +) + +// WithVerifyContext is a mock of WithVerifyContext interface. +type WithVerifyContext struct { + ctrl *gomock.Controller + recorder *WithVerifyContextMockRecorder +} + +// WithVerifyContextMockRecorder is the mock recorder for WithVerifyContext. +type WithVerifyContextMockRecorder struct { + mock *WithVerifyContext +} + +// NewWithVerifyContext creates a new mock instance. +func NewWithVerifyContext(ctrl *gomock.Controller) *WithVerifyContext { + mock := &WithVerifyContext{ctrl: ctrl} + mock.recorder = &WithVerifyContextMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *WithVerifyContext) EXPECT() *WithVerifyContextMockRecorder { + return m.recorder +} + +// ShouldVerifyWithContext mocks base method. +func (m *WithVerifyContext) ShouldVerifyWithContext(arg0 context.Context) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ShouldVerifyWithContext", arg0) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ShouldVerifyWithContext indicates an expected call of ShouldVerifyWithContext. +func (mr *WithVerifyContextMockRecorder) ShouldVerifyWithContext(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ShouldVerifyWithContext", reflect.TypeOf((*WithVerifyContext)(nil).ShouldVerifyWithContext), arg0) +} + +// VerifyWithContext mocks base method. +func (m *WithVerifyContext) VerifyWithContext(arg0 context.Context, arg1 *block.Context) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "VerifyWithContext", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// VerifyWithContext indicates an expected call of VerifyWithContext. +func (mr *WithVerifyContextMockRecorder) VerifyWithContext(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyWithContext", reflect.TypeOf((*WithVerifyContext)(nil).VerifyWithContext), arg0, arg1) +} diff --git a/snow/engine/snowman/block/mock_build_block_with_context_vm.go b/snow/engine/snowman/block/mock_build_block_with_context_vm.go deleted file mode 100644 index 016007b0dee7..000000000000 --- a/snow/engine/snowman/block/mock_build_block_with_context_vm.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/snow/engine/snowman/block (interfaces: BuildBlockWithContextChainVM) -// -// Generated by this command: -// -// mockgen -package=block -destination=snow/engine/snowman/block/mock_build_block_with_context_vm.go github.com/ava-labs/avalanchego/snow/engine/snowman/block BuildBlockWithContextChainVM -// - -// Package block is a generated GoMock package. -package block - -import ( - context "context" - reflect "reflect" - - snowman "github.com/ava-labs/avalanchego/snow/consensus/snowman" - gomock "go.uber.org/mock/gomock" -) - -// MockBuildBlockWithContextChainVM is a mock of BuildBlockWithContextChainVM interface. -type MockBuildBlockWithContextChainVM struct { - ctrl *gomock.Controller - recorder *MockBuildBlockWithContextChainVMMockRecorder -} - -// MockBuildBlockWithContextChainVMMockRecorder is the mock recorder for MockBuildBlockWithContextChainVM. -type MockBuildBlockWithContextChainVMMockRecorder struct { - mock *MockBuildBlockWithContextChainVM -} - -// NewMockBuildBlockWithContextChainVM creates a new mock instance. -func NewMockBuildBlockWithContextChainVM(ctrl *gomock.Controller) *MockBuildBlockWithContextChainVM { - mock := &MockBuildBlockWithContextChainVM{ctrl: ctrl} - mock.recorder = &MockBuildBlockWithContextChainVMMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockBuildBlockWithContextChainVM) EXPECT() *MockBuildBlockWithContextChainVMMockRecorder { - return m.recorder -} - -// BuildBlockWithContext mocks base method. -func (m *MockBuildBlockWithContextChainVM) BuildBlockWithContext(arg0 context.Context, arg1 *Context) (snowman.Block, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "BuildBlockWithContext", arg0, arg1) - ret0, _ := ret[0].(snowman.Block) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// BuildBlockWithContext indicates an expected call of BuildBlockWithContext. -func (mr *MockBuildBlockWithContextChainVMMockRecorder) BuildBlockWithContext(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildBlockWithContext", reflect.TypeOf((*MockBuildBlockWithContextChainVM)(nil).BuildBlockWithContext), arg0, arg1) -} diff --git a/snow/engine/snowman/block/mock_state_syncable_vm.go b/snow/engine/snowman/block/mock_state_syncable_vm.go deleted file mode 100644 index 8d8abca53a0c..000000000000 --- a/snow/engine/snowman/block/mock_state_syncable_vm.go +++ /dev/null @@ -1,115 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/snow/engine/snowman/block (interfaces: StateSyncableVM) -// -// Generated by this command: -// -// mockgen -package=block -destination=snow/engine/snowman/block/mock_state_syncable_vm.go github.com/ava-labs/avalanchego/snow/engine/snowman/block StateSyncableVM -// - -// Package block is a generated GoMock package. -package block - -import ( - context "context" - reflect "reflect" - - gomock "go.uber.org/mock/gomock" -) - -// MockStateSyncableVM is a mock of StateSyncableVM interface. -type MockStateSyncableVM struct { - ctrl *gomock.Controller - recorder *MockStateSyncableVMMockRecorder -} - -// MockStateSyncableVMMockRecorder is the mock recorder for MockStateSyncableVM. -type MockStateSyncableVMMockRecorder struct { - mock *MockStateSyncableVM -} - -// NewMockStateSyncableVM creates a new mock instance. -func NewMockStateSyncableVM(ctrl *gomock.Controller) *MockStateSyncableVM { - mock := &MockStateSyncableVM{ctrl: ctrl} - mock.recorder = &MockStateSyncableVMMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockStateSyncableVM) EXPECT() *MockStateSyncableVMMockRecorder { - return m.recorder -} - -// GetLastStateSummary mocks base method. -func (m *MockStateSyncableVM) GetLastStateSummary(arg0 context.Context) (StateSummary, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetLastStateSummary", arg0) - ret0, _ := ret[0].(StateSummary) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetLastStateSummary indicates an expected call of GetLastStateSummary. -func (mr *MockStateSyncableVMMockRecorder) GetLastStateSummary(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastStateSummary", reflect.TypeOf((*MockStateSyncableVM)(nil).GetLastStateSummary), arg0) -} - -// GetOngoingSyncStateSummary mocks base method. -func (m *MockStateSyncableVM) GetOngoingSyncStateSummary(arg0 context.Context) (StateSummary, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetOngoingSyncStateSummary", arg0) - ret0, _ := ret[0].(StateSummary) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetOngoingSyncStateSummary indicates an expected call of GetOngoingSyncStateSummary. -func (mr *MockStateSyncableVMMockRecorder) GetOngoingSyncStateSummary(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetOngoingSyncStateSummary", reflect.TypeOf((*MockStateSyncableVM)(nil).GetOngoingSyncStateSummary), arg0) -} - -// GetStateSummary mocks base method. -func (m *MockStateSyncableVM) GetStateSummary(arg0 context.Context, arg1 uint64) (StateSummary, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStateSummary", arg0, arg1) - ret0, _ := ret[0].(StateSummary) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetStateSummary indicates an expected call of GetStateSummary. -func (mr *MockStateSyncableVMMockRecorder) GetStateSummary(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStateSummary", reflect.TypeOf((*MockStateSyncableVM)(nil).GetStateSummary), arg0, arg1) -} - -// ParseStateSummary mocks base method. -func (m *MockStateSyncableVM) ParseStateSummary(arg0 context.Context, arg1 []byte) (StateSummary, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ParseStateSummary", arg0, arg1) - ret0, _ := ret[0].(StateSummary) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ParseStateSummary indicates an expected call of ParseStateSummary. -func (mr *MockStateSyncableVMMockRecorder) ParseStateSummary(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ParseStateSummary", reflect.TypeOf((*MockStateSyncableVM)(nil).ParseStateSummary), arg0, arg1) -} - -// StateSyncEnabled mocks base method. -func (m *MockStateSyncableVM) StateSyncEnabled(arg0 context.Context) (bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "StateSyncEnabled", arg0) - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// StateSyncEnabled indicates an expected call of StateSyncEnabled. -func (mr *MockStateSyncableVMMockRecorder) StateSyncEnabled(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StateSyncEnabled", reflect.TypeOf((*MockStateSyncableVM)(nil).StateSyncEnabled), arg0) -} diff --git a/snow/engine/snowman/block/mock_with_verify_context.go b/snow/engine/snowman/block/mock_with_verify_context.go deleted file mode 100644 index 1c18e3e9f6cb..000000000000 --- a/snow/engine/snowman/block/mock_with_verify_context.go +++ /dev/null @@ -1,69 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/snow/engine/snowman/block (interfaces: WithVerifyContext) -// -// Generated by this command: -// -// mockgen -package=block -destination=snow/engine/snowman/block/mock_with_verify_context.go github.com/ava-labs/avalanchego/snow/engine/snowman/block WithVerifyContext -// - -// Package block is a generated GoMock package. -package block - -import ( - context "context" - reflect "reflect" - - gomock "go.uber.org/mock/gomock" -) - -// MockWithVerifyContext is a mock of WithVerifyContext interface. -type MockWithVerifyContext struct { - ctrl *gomock.Controller - recorder *MockWithVerifyContextMockRecorder -} - -// MockWithVerifyContextMockRecorder is the mock recorder for MockWithVerifyContext. -type MockWithVerifyContextMockRecorder struct { - mock *MockWithVerifyContext -} - -// NewMockWithVerifyContext creates a new mock instance. -func NewMockWithVerifyContext(ctrl *gomock.Controller) *MockWithVerifyContext { - mock := &MockWithVerifyContext{ctrl: ctrl} - mock.recorder = &MockWithVerifyContextMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockWithVerifyContext) EXPECT() *MockWithVerifyContextMockRecorder { - return m.recorder -} - -// ShouldVerifyWithContext mocks base method. -func (m *MockWithVerifyContext) ShouldVerifyWithContext(arg0 context.Context) (bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ShouldVerifyWithContext", arg0) - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ShouldVerifyWithContext indicates an expected call of ShouldVerifyWithContext. -func (mr *MockWithVerifyContextMockRecorder) ShouldVerifyWithContext(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ShouldVerifyWithContext", reflect.TypeOf((*MockWithVerifyContext)(nil).ShouldVerifyWithContext), arg0) -} - -// VerifyWithContext mocks base method. -func (m *MockWithVerifyContext) VerifyWithContext(arg0 context.Context, arg1 *Context) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "VerifyWithContext", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// VerifyWithContext indicates an expected call of VerifyWithContext. -func (mr *MockWithVerifyContextMockRecorder) VerifyWithContext(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyWithContext", reflect.TypeOf((*MockWithVerifyContext)(nil).VerifyWithContext), arg0, arg1) -} diff --git a/snow/engine/snowman/getter/getter_test.go b/snow/engine/snowman/getter/getter_test.go index 4454117f345e..e46b1346a761 100644 --- a/snow/engine/snowman/getter/getter_test.go +++ b/snow/engine/snowman/getter/getter_test.go @@ -18,7 +18,7 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/enginetest" - "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/set" @@ -28,15 +28,15 @@ var errUnknownBlock = errors.New("unknown block") type StateSyncEnabledMock struct { *blocktest.VM - *block.MockStateSyncableVM + *blockmock.StateSyncableVM } func newTest(t *testing.T) (common.AllGetsServer, StateSyncEnabledMock, *enginetest.Sender) { ctrl := gomock.NewController(t) vm := StateSyncEnabledMock{ - VM: &blocktest.VM{}, - MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), + VM: &blocktest.VM{}, + StateSyncableVM: blockmock.NewStateSyncableVM(ctrl), } sender := &enginetest.Sender{ diff --git a/snow/networking/handler/handler_test.go b/snow/networking/handler/handler_test.go index faefa616ab91..7bd3f1f3d523 100644 --- a/snow/networking/handler/handler_test.go +++ b/snow/networking/handler/handler_test.go @@ -23,6 +23,7 @@ import ( "github.com/ava-labs/avalanchego/snow/networking/tracker" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" "github.com/ava-labs/avalanchego/subnets" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/math/meter" @@ -440,7 +441,7 @@ func TestHandlerSubnetConnector(t *testing.T) { ) require.NoError(err) ctrl := gomock.NewController(t) - connector := validators.NewMockSubnetConnector(ctrl) + connector := validatorsmock.NewSubnetConnector(ctrl) nodeID := ids.GenerateTestNodeID() subnetID := ids.GenerateTestID() diff --git a/snow/networking/handler/mock_handler.go b/snow/networking/handler/handlermock/handler.go similarity index 55% rename from snow/networking/handler/mock_handler.go rename to snow/networking/handler/handlermock/handler.go index 517fbcd85537..d8e3c23bb0f4 100644 --- a/snow/networking/handler/mock_handler.go +++ b/snow/networking/handler/handlermock/handler.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=handler -destination=snow/networking/handler/mock_handler.go github.com/ava-labs/avalanchego/snow/networking/handler Handler +// mockgen -package=handlermock -destination=snow/networking/handler/handlermock/handler.go -mock_names=Handler=Handler github.com/ava-labs/avalanchego/snow/networking/handler Handler // -// Package handler is a generated GoMock package. -package handler +// Package handlermock is a generated GoMock package. +package handlermock import ( context "context" @@ -16,34 +16,35 @@ import ( ids "github.com/ava-labs/avalanchego/ids" snow "github.com/ava-labs/avalanchego/snow" + handler "github.com/ava-labs/avalanchego/snow/networking/handler" gomock "go.uber.org/mock/gomock" ) -// MockHandler is a mock of Handler interface. -type MockHandler struct { +// Handler is a mock of Handler interface. +type Handler struct { ctrl *gomock.Controller - recorder *MockHandlerMockRecorder + recorder *HandlerMockRecorder } -// MockHandlerMockRecorder is the mock recorder for MockHandler. -type MockHandlerMockRecorder struct { - mock *MockHandler +// HandlerMockRecorder is the mock recorder for Handler. +type HandlerMockRecorder struct { + mock *Handler } -// NewMockHandler creates a new mock instance. -func NewMockHandler(ctrl *gomock.Controller) *MockHandler { - mock := &MockHandler{ctrl: ctrl} - mock.recorder = &MockHandlerMockRecorder{mock} +// NewHandler creates a new mock instance. +func NewHandler(ctrl *gomock.Controller) *Handler { + mock := &Handler{ctrl: ctrl} + mock.recorder = &HandlerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHandler) EXPECT() *MockHandlerMockRecorder { +func (m *Handler) EXPECT() *HandlerMockRecorder { return m.recorder } // AwaitStopped mocks base method. -func (m *MockHandler) AwaitStopped(arg0 context.Context) (time.Duration, error) { +func (m *Handler) AwaitStopped(arg0 context.Context) (time.Duration, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AwaitStopped", arg0) ret0, _ := ret[0].(time.Duration) @@ -52,13 +53,13 @@ func (m *MockHandler) AwaitStopped(arg0 context.Context) (time.Duration, error) } // AwaitStopped indicates an expected call of AwaitStopped. -func (mr *MockHandlerMockRecorder) AwaitStopped(arg0 any) *gomock.Call { +func (mr *HandlerMockRecorder) AwaitStopped(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AwaitStopped", reflect.TypeOf((*MockHandler)(nil).AwaitStopped), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AwaitStopped", reflect.TypeOf((*Handler)(nil).AwaitStopped), arg0) } // Context mocks base method. -func (m *MockHandler) Context() *snow.ConsensusContext { +func (m *Handler) Context() *snow.ConsensusContext { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Context") ret0, _ := ret[0].(*snow.ConsensusContext) @@ -66,27 +67,27 @@ func (m *MockHandler) Context() *snow.ConsensusContext { } // Context indicates an expected call of Context. -func (mr *MockHandlerMockRecorder) Context() *gomock.Call { +func (mr *HandlerMockRecorder) Context() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Context", reflect.TypeOf((*MockHandler)(nil).Context)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Context", reflect.TypeOf((*Handler)(nil).Context)) } // GetEngineManager mocks base method. -func (m *MockHandler) GetEngineManager() *EngineManager { +func (m *Handler) GetEngineManager() *handler.EngineManager { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetEngineManager") - ret0, _ := ret[0].(*EngineManager) + ret0, _ := ret[0].(*handler.EngineManager) return ret0 } // GetEngineManager indicates an expected call of GetEngineManager. -func (mr *MockHandlerMockRecorder) GetEngineManager() *gomock.Call { +func (mr *HandlerMockRecorder) GetEngineManager() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEngineManager", reflect.TypeOf((*MockHandler)(nil).GetEngineManager)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEngineManager", reflect.TypeOf((*Handler)(nil).GetEngineManager)) } // HealthCheck mocks base method. -func (m *MockHandler) HealthCheck(arg0 context.Context) (any, error) { +func (m *Handler) HealthCheck(arg0 context.Context) (any, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HealthCheck", arg0) ret0, _ := ret[0].(any) @@ -95,13 +96,13 @@ func (m *MockHandler) HealthCheck(arg0 context.Context) (any, error) { } // HealthCheck indicates an expected call of HealthCheck. -func (mr *MockHandlerMockRecorder) HealthCheck(arg0 any) *gomock.Call { +func (mr *HandlerMockRecorder) HealthCheck(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*MockHandler)(nil).HealthCheck), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*Handler)(nil).HealthCheck), arg0) } // Len mocks base method. -func (m *MockHandler) Len() int { +func (m *Handler) Len() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Len") ret0, _ := ret[0].(int) @@ -109,61 +110,61 @@ func (m *MockHandler) Len() int { } // Len indicates an expected call of Len. -func (mr *MockHandlerMockRecorder) Len() *gomock.Call { +func (mr *HandlerMockRecorder) Len() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Len", reflect.TypeOf((*MockHandler)(nil).Len)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Len", reflect.TypeOf((*Handler)(nil).Len)) } // Push mocks base method. -func (m *MockHandler) Push(arg0 context.Context, arg1 Message) { +func (m *Handler) Push(arg0 context.Context, arg1 handler.Message) { m.ctrl.T.Helper() m.ctrl.Call(m, "Push", arg0, arg1) } // Push indicates an expected call of Push. -func (mr *MockHandlerMockRecorder) Push(arg0, arg1 any) *gomock.Call { +func (mr *HandlerMockRecorder) Push(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Push", reflect.TypeOf((*MockHandler)(nil).Push), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Push", reflect.TypeOf((*Handler)(nil).Push), arg0, arg1) } // RegisterTimeout mocks base method. -func (m *MockHandler) RegisterTimeout(arg0 time.Duration) { +func (m *Handler) RegisterTimeout(arg0 time.Duration) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterTimeout", arg0) } // RegisterTimeout indicates an expected call of RegisterTimeout. -func (mr *MockHandlerMockRecorder) RegisterTimeout(arg0 any) *gomock.Call { +func (mr *HandlerMockRecorder) RegisterTimeout(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterTimeout", reflect.TypeOf((*MockHandler)(nil).RegisterTimeout), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterTimeout", reflect.TypeOf((*Handler)(nil).RegisterTimeout), arg0) } // SetEngineManager mocks base method. -func (m *MockHandler) SetEngineManager(arg0 *EngineManager) { +func (m *Handler) SetEngineManager(arg0 *handler.EngineManager) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetEngineManager", arg0) } // SetEngineManager indicates an expected call of SetEngineManager. -func (mr *MockHandlerMockRecorder) SetEngineManager(arg0 any) *gomock.Call { +func (mr *HandlerMockRecorder) SetEngineManager(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetEngineManager", reflect.TypeOf((*MockHandler)(nil).SetEngineManager), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetEngineManager", reflect.TypeOf((*Handler)(nil).SetEngineManager), arg0) } // SetOnStopped mocks base method. -func (m *MockHandler) SetOnStopped(arg0 func()) { +func (m *Handler) SetOnStopped(arg0 func()) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetOnStopped", arg0) } // SetOnStopped indicates an expected call of SetOnStopped. -func (mr *MockHandlerMockRecorder) SetOnStopped(arg0 any) *gomock.Call { +func (mr *HandlerMockRecorder) SetOnStopped(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetOnStopped", reflect.TypeOf((*MockHandler)(nil).SetOnStopped), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetOnStopped", reflect.TypeOf((*Handler)(nil).SetOnStopped), arg0) } // ShouldHandle mocks base method. -func (m *MockHandler) ShouldHandle(arg0 ids.NodeID) bool { +func (m *Handler) ShouldHandle(arg0 ids.NodeID) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ShouldHandle", arg0) ret0, _ := ret[0].(bool) @@ -171,43 +172,43 @@ func (m *MockHandler) ShouldHandle(arg0 ids.NodeID) bool { } // ShouldHandle indicates an expected call of ShouldHandle. -func (mr *MockHandlerMockRecorder) ShouldHandle(arg0 any) *gomock.Call { +func (mr *HandlerMockRecorder) ShouldHandle(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ShouldHandle", reflect.TypeOf((*MockHandler)(nil).ShouldHandle), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ShouldHandle", reflect.TypeOf((*Handler)(nil).ShouldHandle), arg0) } // Start mocks base method. -func (m *MockHandler) Start(arg0 context.Context, arg1 bool) { +func (m *Handler) Start(arg0 context.Context, arg1 bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "Start", arg0, arg1) } // Start indicates an expected call of Start. -func (mr *MockHandlerMockRecorder) Start(arg0, arg1 any) *gomock.Call { +func (mr *HandlerMockRecorder) Start(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockHandler)(nil).Start), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*Handler)(nil).Start), arg0, arg1) } // Stop mocks base method. -func (m *MockHandler) Stop(arg0 context.Context) { +func (m *Handler) Stop(arg0 context.Context) { m.ctrl.T.Helper() m.ctrl.Call(m, "Stop", arg0) } // Stop indicates an expected call of Stop. -func (mr *MockHandlerMockRecorder) Stop(arg0 any) *gomock.Call { +func (mr *HandlerMockRecorder) Stop(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*MockHandler)(nil).Stop), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*Handler)(nil).Stop), arg0) } // StopWithError mocks base method. -func (m *MockHandler) StopWithError(arg0 context.Context, arg1 error) { +func (m *Handler) StopWithError(arg0 context.Context, arg1 error) { m.ctrl.T.Helper() m.ctrl.Call(m, "StopWithError", arg0, arg1) } // StopWithError indicates an expected call of StopWithError. -func (mr *MockHandlerMockRecorder) StopWithError(arg0, arg1 any) *gomock.Call { +func (mr *HandlerMockRecorder) StopWithError(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StopWithError", reflect.TypeOf((*MockHandler)(nil).StopWithError), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "StopWithError", reflect.TypeOf((*Handler)(nil).StopWithError), arg0, arg1) } diff --git a/snow/networking/handler/message_queue_test.go b/snow/networking/handler/message_queue_test.go index a74ffcfb4469..810f6185a60b 100644 --- a/snow/networking/handler/message_queue_test.go +++ b/snow/networking/handler/message_queue_test.go @@ -15,7 +15,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/message" "github.com/ava-labs/avalanchego/proto/pb/p2p" - "github.com/ava-labs/avalanchego/snow/networking/tracker" + "github.com/ava-labs/avalanchego/snow/networking/tracker/trackermock" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" @@ -24,7 +24,7 @@ import ( func TestQueue(t *testing.T) { ctrl := gomock.NewController(t) require := require.New(t) - cpuTracker := tracker.NewMockTracker(ctrl) + cpuTracker := trackermock.NewTracker(ctrl) vdrs := validators.NewManager() vdr1ID, vdr2ID := ids.GenerateTestNodeID(), ids.GenerateTestNodeID() require.NoError(vdrs.AddStaker(constants.PrimaryNetworkID, vdr1ID, nil, ids.Empty, 1)) diff --git a/snow/networking/router/chain_router_test.go b/snow/networking/router/chain_router_test.go index b203cc50e131..17c08960fb56 100644 --- a/snow/networking/router/chain_router_test.go +++ b/snow/networking/router/chain_router_test.go @@ -21,6 +21,7 @@ import ( "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/networking/benchlist" "github.com/ava-labs/avalanchego/snow/networking/handler" + "github.com/ava-labs/avalanchego/snow/networking/handler/handlermock" "github.com/ava-labs/avalanchego/snow/networking/timeout" "github.com/ava-labs/avalanchego/snow/networking/tracker" "github.com/ava-labs/avalanchego/snow/snowtest" @@ -827,7 +828,7 @@ func TestRouterHonorsRequestedEngine(t *testing.T) { )) defer chainRouter.Shutdown(context.Background()) - h := handler.NewMockHandler(ctrl) + h := handlermock.NewHandler(ctrl) snowCtx := snowtest.Context(t, snowtest.CChainID) ctx := snowtest.ConsensusContext(snowCtx) @@ -1223,7 +1224,7 @@ func TestConnectedSubnet(t *testing.T) { EngineType: p2ppb.EngineType_ENGINE_TYPE_UNSPECIFIED, } - platformHandler := handler.NewMockHandler(ctrl) + platformHandler := handlermock.NewHandler(ctrl) platformHandler.EXPECT().Context().Return(ctx).AnyTimes() platformHandler.EXPECT().SetOnStopped(gomock.Any()).AnyTimes() platformHandler.EXPECT().Push(gomock.Any(), myConnectedMsg).Times(1) diff --git a/snow/networking/router/mock_router.go b/snow/networking/router/routermock/router.go similarity index 51% rename from snow/networking/router/mock_router.go rename to snow/networking/router/routermock/router.go index 6105b807acd8..8d0610ac5f88 100644 --- a/snow/networking/router/mock_router.go +++ b/snow/networking/router/routermock/router.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -source=snow/networking/router/router.go -destination=snow/networking/router/mock_router.go -package=router -exclude_interfaces=InternalHandler +// mockgen -source=snow/networking/router/router.go -destination=snow/networking/router/routermock/router.go -package=routermock -exclude_interfaces=InternalHandler -mock_names=Router=Router // -// Package router is a generated GoMock package. -package router +// Package routermock is a generated GoMock package. +package routermock import ( context "context" @@ -18,6 +18,7 @@ import ( message "github.com/ava-labs/avalanchego/message" p2p "github.com/ava-labs/avalanchego/proto/pb/p2p" handler "github.com/ava-labs/avalanchego/snow/networking/handler" + router "github.com/ava-labs/avalanchego/snow/networking/router" timeout "github.com/ava-labs/avalanchego/snow/networking/timeout" logging "github.com/ava-labs/avalanchego/utils/logging" set "github.com/ava-labs/avalanchego/utils/set" @@ -26,91 +27,91 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockRouter is a mock of Router interface. -type MockRouter struct { +// Router is a mock of Router interface. +type Router struct { ctrl *gomock.Controller - recorder *MockRouterMockRecorder + recorder *RouterMockRecorder } -// MockRouterMockRecorder is the mock recorder for MockRouter. -type MockRouterMockRecorder struct { - mock *MockRouter +// RouterMockRecorder is the mock recorder for Router. +type RouterMockRecorder struct { + mock *Router } -// NewMockRouter creates a new mock instance. -func NewMockRouter(ctrl *gomock.Controller) *MockRouter { - mock := &MockRouter{ctrl: ctrl} - mock.recorder = &MockRouterMockRecorder{mock} +// NewRouter creates a new mock instance. +func NewRouter(ctrl *gomock.Controller) *Router { + mock := &Router{ctrl: ctrl} + mock.recorder = &RouterMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockRouter) EXPECT() *MockRouterMockRecorder { +func (m *Router) EXPECT() *RouterMockRecorder { return m.recorder } // AddChain mocks base method. -func (m *MockRouter) AddChain(ctx context.Context, chain handler.Handler) { +func (m *Router) AddChain(ctx context.Context, chain handler.Handler) { m.ctrl.T.Helper() m.ctrl.Call(m, "AddChain", ctx, chain) } // AddChain indicates an expected call of AddChain. -func (mr *MockRouterMockRecorder) AddChain(ctx, chain any) *gomock.Call { +func (mr *RouterMockRecorder) AddChain(ctx, chain any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*MockRouter)(nil).AddChain), ctx, chain) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*Router)(nil).AddChain), ctx, chain) } // Benched mocks base method. -func (m *MockRouter) Benched(chainID ids.ID, validatorID ids.NodeID) { +func (m *Router) Benched(chainID ids.ID, validatorID ids.NodeID) { m.ctrl.T.Helper() m.ctrl.Call(m, "Benched", chainID, validatorID) } // Benched indicates an expected call of Benched. -func (mr *MockRouterMockRecorder) Benched(chainID, validatorID any) *gomock.Call { +func (mr *RouterMockRecorder) Benched(chainID, validatorID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Benched", reflect.TypeOf((*MockRouter)(nil).Benched), chainID, validatorID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Benched", reflect.TypeOf((*Router)(nil).Benched), chainID, validatorID) } // Connected mocks base method. -func (m *MockRouter) Connected(nodeID ids.NodeID, nodeVersion *version.Application, subnetID ids.ID) { +func (m *Router) Connected(nodeID ids.NodeID, nodeVersion *version.Application, subnetID ids.ID) { m.ctrl.T.Helper() m.ctrl.Call(m, "Connected", nodeID, nodeVersion, subnetID) } // Connected indicates an expected call of Connected. -func (mr *MockRouterMockRecorder) Connected(nodeID, nodeVersion, subnetID any) *gomock.Call { +func (mr *RouterMockRecorder) Connected(nodeID, nodeVersion, subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connected", reflect.TypeOf((*MockRouter)(nil).Connected), nodeID, nodeVersion, subnetID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connected", reflect.TypeOf((*Router)(nil).Connected), nodeID, nodeVersion, subnetID) } // Disconnected mocks base method. -func (m *MockRouter) Disconnected(nodeID ids.NodeID) { +func (m *Router) Disconnected(nodeID ids.NodeID) { m.ctrl.T.Helper() m.ctrl.Call(m, "Disconnected", nodeID) } // Disconnected indicates an expected call of Disconnected. -func (mr *MockRouterMockRecorder) Disconnected(nodeID any) *gomock.Call { +func (mr *RouterMockRecorder) Disconnected(nodeID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnected", reflect.TypeOf((*MockRouter)(nil).Disconnected), nodeID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnected", reflect.TypeOf((*Router)(nil).Disconnected), nodeID) } // HandleInbound mocks base method. -func (m *MockRouter) HandleInbound(arg0 context.Context, arg1 message.InboundMessage) { +func (m *Router) HandleInbound(arg0 context.Context, arg1 message.InboundMessage) { m.ctrl.T.Helper() m.ctrl.Call(m, "HandleInbound", arg0, arg1) } // HandleInbound indicates an expected call of HandleInbound. -func (mr *MockRouterMockRecorder) HandleInbound(arg0, arg1 any) *gomock.Call { +func (mr *RouterMockRecorder) HandleInbound(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleInbound", reflect.TypeOf((*MockRouter)(nil).HandleInbound), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HandleInbound", reflect.TypeOf((*Router)(nil).HandleInbound), arg0, arg1) } // HealthCheck mocks base method. -func (m *MockRouter) HealthCheck(arg0 context.Context) (any, error) { +func (m *Router) HealthCheck(arg0 context.Context) (any, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HealthCheck", arg0) ret0, _ := ret[0].(any) @@ -119,13 +120,13 @@ func (m *MockRouter) HealthCheck(arg0 context.Context) (any, error) { } // HealthCheck indicates an expected call of HealthCheck. -func (mr *MockRouterMockRecorder) HealthCheck(arg0 any) *gomock.Call { +func (mr *RouterMockRecorder) HealthCheck(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*MockRouter)(nil).HealthCheck), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*Router)(nil).HealthCheck), arg0) } // Initialize mocks base method. -func (m *MockRouter) Initialize(nodeID ids.NodeID, log logging.Logger, timeouts timeout.Manager, shutdownTimeout time.Duration, criticalChains set.Set[ids.ID], sybilProtectionEnabled bool, trackedSubnets set.Set[ids.ID], onFatal func(int), healthConfig HealthConfig, reg prometheus.Registerer) error { +func (m *Router) Initialize(nodeID ids.NodeID, log logging.Logger, timeouts timeout.Manager, shutdownTimeout time.Duration, criticalChains set.Set[ids.ID], sybilProtectionEnabled bool, trackedSubnets set.Set[ids.ID], onFatal func(int), healthConfig router.HealthConfig, reg prometheus.Registerer) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Initialize", nodeID, log, timeouts, shutdownTimeout, criticalChains, sybilProtectionEnabled, trackedSubnets, onFatal, healthConfig, reg) ret0, _ := ret[0].(error) @@ -133,43 +134,43 @@ func (m *MockRouter) Initialize(nodeID ids.NodeID, log logging.Logger, timeouts } // Initialize indicates an expected call of Initialize. -func (mr *MockRouterMockRecorder) Initialize(nodeID, log, timeouts, shutdownTimeout, criticalChains, sybilProtectionEnabled, trackedSubnets, onFatal, healthConfig, reg any) *gomock.Call { +func (mr *RouterMockRecorder) Initialize(nodeID, log, timeouts, shutdownTimeout, criticalChains, sybilProtectionEnabled, trackedSubnets, onFatal, healthConfig, reg any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*MockRouter)(nil).Initialize), nodeID, log, timeouts, shutdownTimeout, criticalChains, sybilProtectionEnabled, trackedSubnets, onFatal, healthConfig, reg) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*Router)(nil).Initialize), nodeID, log, timeouts, shutdownTimeout, criticalChains, sybilProtectionEnabled, trackedSubnets, onFatal, healthConfig, reg) } // RegisterRequest mocks base method. -func (m *MockRouter) RegisterRequest(ctx context.Context, nodeID ids.NodeID, chainID ids.ID, requestID uint32, op message.Op, failedMsg message.InboundMessage, engineType p2p.EngineType) { +func (m *Router) RegisterRequest(ctx context.Context, nodeID ids.NodeID, chainID ids.ID, requestID uint32, op message.Op, failedMsg message.InboundMessage, engineType p2p.EngineType) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterRequest", ctx, nodeID, chainID, requestID, op, failedMsg, engineType) } // RegisterRequest indicates an expected call of RegisterRequest. -func (mr *MockRouterMockRecorder) RegisterRequest(ctx, nodeID, chainID, requestID, op, failedMsg, engineType any) *gomock.Call { +func (mr *RouterMockRecorder) RegisterRequest(ctx, nodeID, chainID, requestID, op, failedMsg, engineType any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRequest", reflect.TypeOf((*MockRouter)(nil).RegisterRequest), ctx, nodeID, chainID, requestID, op, failedMsg, engineType) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRequest", reflect.TypeOf((*Router)(nil).RegisterRequest), ctx, nodeID, chainID, requestID, op, failedMsg, engineType) } // Shutdown mocks base method. -func (m *MockRouter) Shutdown(arg0 context.Context) { +func (m *Router) Shutdown(arg0 context.Context) { m.ctrl.T.Helper() m.ctrl.Call(m, "Shutdown", arg0) } // Shutdown indicates an expected call of Shutdown. -func (mr *MockRouterMockRecorder) Shutdown(arg0 any) *gomock.Call { +func (mr *RouterMockRecorder) Shutdown(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*MockRouter)(nil).Shutdown), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Shutdown", reflect.TypeOf((*Router)(nil).Shutdown), arg0) } // Unbenched mocks base method. -func (m *MockRouter) Unbenched(chainID ids.ID, validatorID ids.NodeID) { +func (m *Router) Unbenched(chainID ids.ID, validatorID ids.NodeID) { m.ctrl.T.Helper() m.ctrl.Call(m, "Unbenched", chainID, validatorID) } // Unbenched indicates an expected call of Unbenched. -func (mr *MockRouterMockRecorder) Unbenched(chainID, validatorID any) *gomock.Call { +func (mr *RouterMockRecorder) Unbenched(chainID, validatorID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unbenched", reflect.TypeOf((*MockRouter)(nil).Unbenched), chainID, validatorID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Unbenched", reflect.TypeOf((*Router)(nil).Unbenched), chainID, validatorID) } diff --git a/snow/networking/sender/mock_external_sender.go b/snow/networking/sender/mock_external_sender.go deleted file mode 100644 index 420f3b79fc4b..000000000000 --- a/snow/networking/sender/mock_external_sender.go +++ /dev/null @@ -1,58 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: snow/networking/sender/external_sender.go -// -// Generated by this command: -// -// mockgen -source=snow/networking/sender/external_sender.go -destination=snow/networking/sender/mock_external_sender.go -package=sender -exclude_interfaces= -// - -// Package sender is a generated GoMock package. -package sender - -import ( - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - message "github.com/ava-labs/avalanchego/message" - common "github.com/ava-labs/avalanchego/snow/engine/common" - subnets "github.com/ava-labs/avalanchego/subnets" - set "github.com/ava-labs/avalanchego/utils/set" - gomock "go.uber.org/mock/gomock" -) - -// MockExternalSender is a mock of ExternalSender interface. -type MockExternalSender struct { - ctrl *gomock.Controller - recorder *MockExternalSenderMockRecorder -} - -// MockExternalSenderMockRecorder is the mock recorder for MockExternalSender. -type MockExternalSenderMockRecorder struct { - mock *MockExternalSender -} - -// NewMockExternalSender creates a new mock instance. -func NewMockExternalSender(ctrl *gomock.Controller) *MockExternalSender { - mock := &MockExternalSender{ctrl: ctrl} - mock.recorder = &MockExternalSenderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockExternalSender) EXPECT() *MockExternalSenderMockRecorder { - return m.recorder -} - -// Send mocks base method. -func (m *MockExternalSender) Send(msg message.OutboundMessage, config common.SendConfig, subnetID ids.ID, allower subnets.Allower) set.Set[ids.NodeID] { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Send", msg, config, subnetID, allower) - ret0, _ := ret[0].(set.Set[ids.NodeID]) - return ret0 -} - -// Send indicates an expected call of Send. -func (mr *MockExternalSenderMockRecorder) Send(msg, config, subnetID, allower any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*MockExternalSender)(nil).Send), msg, config, subnetID, allower) -} diff --git a/snow/networking/sender/sender_test.go b/snow/networking/sender/sender_test.go index 10033ada9b12..ef9081b45819 100644 --- a/snow/networking/sender/sender_test.go +++ b/snow/networking/sender/sender_test.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/message" + "github.com/ava-labs/avalanchego/message/messagemock" "github.com/ava-labs/avalanchego/network/p2p" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/engine/common" @@ -23,8 +24,11 @@ import ( "github.com/ava-labs/avalanchego/snow/networking/benchlist" "github.com/ava-labs/avalanchego/snow/networking/handler" "github.com/ava-labs/avalanchego/snow/networking/router" + "github.com/ava-labs/avalanchego/snow/networking/router/routermock" + "github.com/ava-labs/avalanchego/snow/networking/sender/sendermock" "github.com/ava-labs/avalanchego/snow/networking/sender/sendertest" "github.com/ava-labs/avalanchego/snow/networking/timeout" + "github.com/ava-labs/avalanchego/snow/networking/timeout/timeoutmock" "github.com/ava-labs/avalanchego/snow/networking/tracker" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" @@ -634,8 +638,8 @@ func TestSender_Bootstrap_Requests(t *testing.T) { failedMsgF func(nodeID ids.NodeID) message.InboundMessage assertMsgToMyself func(require *require.Assertions, msg message.InboundMessage) expectedResponseOp message.Op - setMsgCreatorExpect func(msgCreator *message.MockOutboundMsgBuilder) - setExternalSenderExpect func(externalSender *MockExternalSender) + setMsgCreatorExpect func(msgCreator *messagemock.OutboundMsgBuilder) + setExternalSenderExpect func(externalSender *sendermock.ExternalSender) sendF func(require *require.Assertions, sender common.Sender, nodeIDs set.Set[ids.NodeID]) } @@ -657,14 +661,14 @@ func TestSender_Bootstrap_Requests(t *testing.T) { require.Equal(uint64(deadline), innerMsg.Deadline) }, expectedResponseOp: message.StateSummaryFrontierOp, - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().GetStateSummaryFrontier( ctx.ChainID, requestID, deadline, ).Return(nil, nil) }, - setExternalSenderExpect: func(externalSender *MockExternalSender) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -701,7 +705,7 @@ func TestSender_Bootstrap_Requests(t *testing.T) { require.Equal(heights, innerMsg.Heights) }, expectedResponseOp: message.AcceptedStateSummaryOp, - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().GetAcceptedStateSummary( ctx.ChainID, requestID, @@ -709,7 +713,7 @@ func TestSender_Bootstrap_Requests(t *testing.T) { heights, ).Return(nil, nil) }, - setExternalSenderExpect: func(externalSender *MockExternalSender) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -741,14 +745,14 @@ func TestSender_Bootstrap_Requests(t *testing.T) { require.Equal(uint64(deadline), innerMsg.Deadline) }, expectedResponseOp: message.AcceptedFrontierOp, - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().GetAcceptedFrontier( ctx.ChainID, requestID, deadline, ).Return(nil, nil) }, - setExternalSenderExpect: func(externalSender *MockExternalSender) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -780,7 +784,7 @@ func TestSender_Bootstrap_Requests(t *testing.T) { require.Equal(uint64(deadline), innerMsg.Deadline) }, expectedResponseOp: message.AcceptedOp, - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().GetAccepted( ctx.ChainID, requestID, @@ -788,7 +792,7 @@ func TestSender_Bootstrap_Requests(t *testing.T) { containerIDs, ).Return(nil, nil) }, - setExternalSenderExpect: func(externalSender *MockExternalSender) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -811,10 +815,10 @@ func TestSender_Bootstrap_Requests(t *testing.T) { ctrl := gomock.NewController(t) var ( - msgCreator = message.NewMockOutboundMsgBuilder(ctrl) - externalSender = NewMockExternalSender(ctrl) - timeoutManager = timeout.NewMockManager(ctrl) - router = router.NewMockRouter(ctrl) + msgCreator = messagemock.NewOutboundMsgBuilder(ctrl) + externalSender = sendermock.NewExternalSender(ctrl) + timeoutManager = timeoutmock.NewManager(ctrl) + router = routermock.NewRouter(ctrl) nodeIDs = set.Of(successNodeID, failedNodeID, ctx.NodeID) nodeIDsCopy set.Set[ids.NodeID] ) @@ -894,15 +898,15 @@ func TestSender_Bootstrap_Responses(t *testing.T) { type test struct { name string assertMsgToMyself func(require *require.Assertions, msg message.InboundMessage) - setMsgCreatorExpect func(msgCreator *message.MockOutboundMsgBuilder) - setExternalSenderExpect func(externalSender *MockExternalSender) + setMsgCreatorExpect func(msgCreator *messagemock.OutboundMsgBuilder) + setExternalSenderExpect func(externalSender *sendermock.ExternalSender) sendF func(require *require.Assertions, sender common.Sender, nodeID ids.NodeID) } tests := []test{ { name: "StateSummaryFrontier", - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().StateSummaryFrontier( ctx.ChainID, requestID, @@ -916,7 +920,7 @@ func TestSender_Bootstrap_Responses(t *testing.T) { require.Equal(requestID, innerMsg.RequestId) require.Equal(summary, innerMsg.Summary) }, - setExternalSenderExpect: func(externalSender *MockExternalSender) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -932,7 +936,7 @@ func TestSender_Bootstrap_Responses(t *testing.T) { }, { name: "AcceptedStateSummary", - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().AcceptedStateSummary( ctx.ChainID, requestID, @@ -948,7 +952,7 @@ func TestSender_Bootstrap_Responses(t *testing.T) { require.Equal(summaryID[:], innerMsg.SummaryIds[i]) } }, - setExternalSenderExpect: func(externalSender *MockExternalSender) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -964,7 +968,7 @@ func TestSender_Bootstrap_Responses(t *testing.T) { }, { name: "AcceptedFrontier", - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().AcceptedFrontier( ctx.ChainID, requestID, @@ -978,7 +982,7 @@ func TestSender_Bootstrap_Responses(t *testing.T) { require.Equal(requestID, innerMsg.RequestId) require.Equal(summaryIDs[0][:], innerMsg.ContainerId) }, - setExternalSenderExpect: func(externalSender *MockExternalSender) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -994,7 +998,7 @@ func TestSender_Bootstrap_Responses(t *testing.T) { }, { name: "Accepted", - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().Accepted( ctx.ChainID, requestID, @@ -1010,7 +1014,7 @@ func TestSender_Bootstrap_Responses(t *testing.T) { require.Equal(summaryID[:], innerMsg.ContainerIds[i]) } }, - setExternalSenderExpect: func(externalSender *MockExternalSender) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -1032,10 +1036,10 @@ func TestSender_Bootstrap_Responses(t *testing.T) { ctrl := gomock.NewController(t) var ( - msgCreator = message.NewMockOutboundMsgBuilder(ctrl) - externalSender = NewMockExternalSender(ctrl) - timeoutManager = timeout.NewMockManager(ctrl) - router = router.NewMockRouter(ctrl) + msgCreator = messagemock.NewOutboundMsgBuilder(ctrl) + externalSender = sendermock.NewExternalSender(ctrl) + timeoutManager = timeoutmock.NewManager(ctrl) + router = routermock.NewRouter(ctrl) ) sender, err := New( @@ -1098,8 +1102,8 @@ func TestSender_Single_Request(t *testing.T) { shouldFailMessageToSelf bool assertMsg func(require *require.Assertions, msg message.InboundMessage) expectedResponseOp message.Op - setMsgCreatorExpect func(msgCreator *message.MockOutboundMsgBuilder) - setExternalSenderExpect func(externalSender *MockExternalSender, sentTo set.Set[ids.NodeID]) + setMsgCreatorExpect func(msgCreator *messagemock.OutboundMsgBuilder) + setExternalSenderExpect func(externalSender *sendermock.ExternalSender, sentTo set.Set[ids.NodeID]) sendF func(require *require.Assertions, sender common.Sender, nodeID ids.NodeID) expectedEngineType p2ppb.EngineType } @@ -1124,7 +1128,7 @@ func TestSender_Single_Request(t *testing.T) { require.Equal(engineType, innerMsg.EngineType) }, expectedResponseOp: message.AncestorsOp, - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().GetAncestors( ctx.ChainID, requestID, @@ -1133,7 +1137,7 @@ func TestSender_Single_Request(t *testing.T) { engineType, ).Return(nil, nil) }, - setExternalSenderExpect: func(externalSender *MockExternalSender, sentTo set.Set[ids.NodeID]) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender, sentTo set.Set[ids.NodeID]) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -1165,7 +1169,7 @@ func TestSender_Single_Request(t *testing.T) { require.Equal(requestID, innerMsg.RequestID) }, expectedResponseOp: message.PutOp, - setMsgCreatorExpect: func(msgCreator *message.MockOutboundMsgBuilder) { + setMsgCreatorExpect: func(msgCreator *messagemock.OutboundMsgBuilder) { msgCreator.EXPECT().Get( ctx.ChainID, requestID, @@ -1173,7 +1177,7 @@ func TestSender_Single_Request(t *testing.T) { containerID, ).Return(nil, nil) }, - setExternalSenderExpect: func(externalSender *MockExternalSender, sentTo set.Set[ids.NodeID]) { + setExternalSenderExpect: func(externalSender *sendermock.ExternalSender, sentTo set.Set[ids.NodeID]) { externalSender.EXPECT().Send( gomock.Any(), // Outbound message common.SendConfig{ @@ -1195,10 +1199,10 @@ func TestSender_Single_Request(t *testing.T) { ctrl := gomock.NewController(t) var ( - msgCreator = message.NewMockOutboundMsgBuilder(ctrl) - externalSender = NewMockExternalSender(ctrl) - timeoutManager = timeout.NewMockManager(ctrl) - router = router.NewMockRouter(ctrl) + msgCreator = messagemock.NewOutboundMsgBuilder(ctrl) + externalSender = sendermock.NewExternalSender(ctrl) + timeoutManager = timeoutmock.NewManager(ctrl) + router = routermock.NewRouter(ctrl) ) // Instantiate new registerers to avoid duplicate metrics diff --git a/snow/networking/sender/sendermock/external_sender.go b/snow/networking/sender/sendermock/external_sender.go new file mode 100644 index 000000000000..bdef54250909 --- /dev/null +++ b/snow/networking/sender/sendermock/external_sender.go @@ -0,0 +1,58 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: snow/networking/sender/external_sender.go +// +// Generated by this command: +// +// mockgen -source=snow/networking/sender/external_sender.go -destination=snow/networking/sender/sendermock/external_sender.go -package=sendermock -exclude_interfaces= -mock_names=ExternalSender=ExternalSender +// + +// Package sendermock is a generated GoMock package. +package sendermock + +import ( + reflect "reflect" + + ids "github.com/ava-labs/avalanchego/ids" + message "github.com/ava-labs/avalanchego/message" + common "github.com/ava-labs/avalanchego/snow/engine/common" + subnets "github.com/ava-labs/avalanchego/subnets" + set "github.com/ava-labs/avalanchego/utils/set" + gomock "go.uber.org/mock/gomock" +) + +// ExternalSender is a mock of ExternalSender interface. +type ExternalSender struct { + ctrl *gomock.Controller + recorder *ExternalSenderMockRecorder +} + +// ExternalSenderMockRecorder is the mock recorder for ExternalSender. +type ExternalSenderMockRecorder struct { + mock *ExternalSender +} + +// NewExternalSender creates a new mock instance. +func NewExternalSender(ctrl *gomock.Controller) *ExternalSender { + mock := &ExternalSender{ctrl: ctrl} + mock.recorder = &ExternalSenderMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *ExternalSender) EXPECT() *ExternalSenderMockRecorder { + return m.recorder +} + +// Send mocks base method. +func (m *ExternalSender) Send(msg message.OutboundMessage, config common.SendConfig, subnetID ids.ID, allower subnets.Allower) set.Set[ids.NodeID] { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Send", msg, config, subnetID, allower) + ret0, _ := ret[0].(set.Set[ids.NodeID]) + return ret0 +} + +// Send indicates an expected call of Send. +func (mr *ExternalSenderMockRecorder) Send(msg, config, subnetID, allower any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Send", reflect.TypeOf((*ExternalSender)(nil).Send), msg, config, subnetID, allower) +} diff --git a/snow/networking/timeout/mock_manager.go b/snow/networking/timeout/timeoutmock/manager.go similarity index 53% rename from snow/networking/timeout/mock_manager.go rename to snow/networking/timeout/timeoutmock/manager.go index 8eeac4c6f8dc..317336cc7a64 100644 --- a/snow/networking/timeout/mock_manager.go +++ b/snow/networking/timeout/timeoutmock/manager.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=timeout -destination=snow/networking/timeout/mock_manager.go github.com/ava-labs/avalanchego/snow/networking/timeout Manager +// mockgen -package=timeoutmock -destination=snow/networking/timeout/timeoutmock/manager.go -mock_names=Manager=Manager github.com/ava-labs/avalanchego/snow/networking/timeout Manager // -// Package timeout is a generated GoMock package. -package timeout +// Package timeoutmock is a generated GoMock package. +package timeoutmock import ( reflect "reflect" @@ -19,43 +19,43 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockManager is a mock of Manager interface. -type MockManager struct { +// Manager is a mock of Manager interface. +type Manager struct { ctrl *gomock.Controller - recorder *MockManagerMockRecorder + recorder *ManagerMockRecorder } -// MockManagerMockRecorder is the mock recorder for MockManager. -type MockManagerMockRecorder struct { - mock *MockManager +// ManagerMockRecorder is the mock recorder for Manager. +type ManagerMockRecorder struct { + mock *Manager } -// NewMockManager creates a new mock instance. -func NewMockManager(ctrl *gomock.Controller) *MockManager { - mock := &MockManager{ctrl: ctrl} - mock.recorder = &MockManagerMockRecorder{mock} +// NewManager creates a new mock instance. +func NewManager(ctrl *gomock.Controller) *Manager { + mock := &Manager{ctrl: ctrl} + mock.recorder = &ManagerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockManager) EXPECT() *MockManagerMockRecorder { +func (m *Manager) EXPECT() *ManagerMockRecorder { return m.recorder } // Dispatch mocks base method. -func (m *MockManager) Dispatch() { +func (m *Manager) Dispatch() { m.ctrl.T.Helper() m.ctrl.Call(m, "Dispatch") } // Dispatch indicates an expected call of Dispatch. -func (mr *MockManagerMockRecorder) Dispatch() *gomock.Call { +func (mr *ManagerMockRecorder) Dispatch() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dispatch", reflect.TypeOf((*MockManager)(nil).Dispatch)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dispatch", reflect.TypeOf((*Manager)(nil).Dispatch)) } // IsBenched mocks base method. -func (m *MockManager) IsBenched(arg0 ids.NodeID, arg1 ids.ID) bool { +func (m *Manager) IsBenched(arg0 ids.NodeID, arg1 ids.ID) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "IsBenched", arg0, arg1) ret0, _ := ret[0].(bool) @@ -63,13 +63,13 @@ func (m *MockManager) IsBenched(arg0 ids.NodeID, arg1 ids.ID) bool { } // IsBenched indicates an expected call of IsBenched. -func (mr *MockManagerMockRecorder) IsBenched(arg0, arg1 any) *gomock.Call { +func (mr *ManagerMockRecorder) IsBenched(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsBenched", reflect.TypeOf((*MockManager)(nil).IsBenched), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsBenched", reflect.TypeOf((*Manager)(nil).IsBenched), arg0, arg1) } // RegisterChain mocks base method. -func (m *MockManager) RegisterChain(arg0 *snow.ConsensusContext) error { +func (m *Manager) RegisterChain(arg0 *snow.ConsensusContext) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RegisterChain", arg0) ret0, _ := ret[0].(error) @@ -77,73 +77,73 @@ func (m *MockManager) RegisterChain(arg0 *snow.ConsensusContext) error { } // RegisterChain indicates an expected call of RegisterChain. -func (mr *MockManagerMockRecorder) RegisterChain(arg0 any) *gomock.Call { +func (mr *ManagerMockRecorder) RegisterChain(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterChain", reflect.TypeOf((*MockManager)(nil).RegisterChain), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterChain", reflect.TypeOf((*Manager)(nil).RegisterChain), arg0) } // RegisterRequest mocks base method. -func (m *MockManager) RegisterRequest(arg0 ids.NodeID, arg1 ids.ID, arg2 bool, arg3 ids.RequestID, arg4 func()) { +func (m *Manager) RegisterRequest(arg0 ids.NodeID, arg1 ids.ID, arg2 bool, arg3 ids.RequestID, arg4 func()) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterRequest", arg0, arg1, arg2, arg3, arg4) } // RegisterRequest indicates an expected call of RegisterRequest. -func (mr *MockManagerMockRecorder) RegisterRequest(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { +func (mr *ManagerMockRecorder) RegisterRequest(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRequest", reflect.TypeOf((*MockManager)(nil).RegisterRequest), arg0, arg1, arg2, arg3, arg4) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRequest", reflect.TypeOf((*Manager)(nil).RegisterRequest), arg0, arg1, arg2, arg3, arg4) } // RegisterRequestToUnreachableValidator mocks base method. -func (m *MockManager) RegisterRequestToUnreachableValidator() { +func (m *Manager) RegisterRequestToUnreachableValidator() { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterRequestToUnreachableValidator") } // RegisterRequestToUnreachableValidator indicates an expected call of RegisterRequestToUnreachableValidator. -func (mr *MockManagerMockRecorder) RegisterRequestToUnreachableValidator() *gomock.Call { +func (mr *ManagerMockRecorder) RegisterRequestToUnreachableValidator() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRequestToUnreachableValidator", reflect.TypeOf((*MockManager)(nil).RegisterRequestToUnreachableValidator)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterRequestToUnreachableValidator", reflect.TypeOf((*Manager)(nil).RegisterRequestToUnreachableValidator)) } // RegisterResponse mocks base method. -func (m *MockManager) RegisterResponse(arg0 ids.NodeID, arg1 ids.ID, arg2 ids.RequestID, arg3 message.Op, arg4 time.Duration) { +func (m *Manager) RegisterResponse(arg0 ids.NodeID, arg1 ids.ID, arg2 ids.RequestID, arg3 message.Op, arg4 time.Duration) { m.ctrl.T.Helper() m.ctrl.Call(m, "RegisterResponse", arg0, arg1, arg2, arg3, arg4) } // RegisterResponse indicates an expected call of RegisterResponse. -func (mr *MockManagerMockRecorder) RegisterResponse(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { +func (mr *ManagerMockRecorder) RegisterResponse(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterResponse", reflect.TypeOf((*MockManager)(nil).RegisterResponse), arg0, arg1, arg2, arg3, arg4) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterResponse", reflect.TypeOf((*Manager)(nil).RegisterResponse), arg0, arg1, arg2, arg3, arg4) } // RemoveRequest mocks base method. -func (m *MockManager) RemoveRequest(arg0 ids.RequestID) { +func (m *Manager) RemoveRequest(arg0 ids.RequestID) { m.ctrl.T.Helper() m.ctrl.Call(m, "RemoveRequest", arg0) } // RemoveRequest indicates an expected call of RemoveRequest. -func (mr *MockManagerMockRecorder) RemoveRequest(arg0 any) *gomock.Call { +func (mr *ManagerMockRecorder) RemoveRequest(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveRequest", reflect.TypeOf((*MockManager)(nil).RemoveRequest), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveRequest", reflect.TypeOf((*Manager)(nil).RemoveRequest), arg0) } // Stop mocks base method. -func (m *MockManager) Stop() { +func (m *Manager) Stop() { m.ctrl.T.Helper() m.ctrl.Call(m, "Stop") } // Stop indicates an expected call of Stop. -func (mr *MockManagerMockRecorder) Stop() *gomock.Call { +func (mr *ManagerMockRecorder) Stop() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*MockManager)(nil).Stop)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Stop", reflect.TypeOf((*Manager)(nil).Stop)) } // TimeoutDuration mocks base method. -func (m *MockManager) TimeoutDuration() time.Duration { +func (m *Manager) TimeoutDuration() time.Duration { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TimeoutDuration") ret0, _ := ret[0].(time.Duration) @@ -151,7 +151,7 @@ func (m *MockManager) TimeoutDuration() time.Duration { } // TimeoutDuration indicates an expected call of TimeoutDuration. -func (mr *MockManagerMockRecorder) TimeoutDuration() *gomock.Call { +func (mr *ManagerMockRecorder) TimeoutDuration() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TimeoutDuration", reflect.TypeOf((*MockManager)(nil).TimeoutDuration)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TimeoutDuration", reflect.TypeOf((*Manager)(nil).TimeoutDuration)) } diff --git a/snow/networking/tracker/mock_targeter.go b/snow/networking/tracker/mock_targeter.go deleted file mode 100644 index 7e260fe69d6d..000000000000 --- a/snow/networking/tracker/mock_targeter.go +++ /dev/null @@ -1,54 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/snow/networking/tracker (interfaces: Targeter) -// -// Generated by this command: -// -// mockgen -package=tracker -destination=snow/networking/tracker/mock_targeter.go github.com/ava-labs/avalanchego/snow/networking/tracker Targeter -// - -// Package tracker is a generated GoMock package. -package tracker - -import ( - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - gomock "go.uber.org/mock/gomock" -) - -// MockTargeter is a mock of Targeter interface. -type MockTargeter struct { - ctrl *gomock.Controller - recorder *MockTargeterMockRecorder -} - -// MockTargeterMockRecorder is the mock recorder for MockTargeter. -type MockTargeterMockRecorder struct { - mock *MockTargeter -} - -// NewMockTargeter creates a new mock instance. -func NewMockTargeter(ctrl *gomock.Controller) *MockTargeter { - mock := &MockTargeter{ctrl: ctrl} - mock.recorder = &MockTargeterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTargeter) EXPECT() *MockTargeterMockRecorder { - return m.recorder -} - -// TargetUsage mocks base method. -func (m *MockTargeter) TargetUsage(arg0 ids.NodeID) float64 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "TargetUsage", arg0) - ret0, _ := ret[0].(float64) - return ret0 -} - -// TargetUsage indicates an expected call of TargetUsage. -func (mr *MockTargeterMockRecorder) TargetUsage(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TargetUsage", reflect.TypeOf((*MockTargeter)(nil).TargetUsage), arg0) -} diff --git a/snow/networking/tracker/resource_tracker_test.go b/snow/networking/tracker/resource_tracker_test.go index 22b477e0890a..d86afbfeb0a6 100644 --- a/snow/networking/tracker/resource_tracker_test.go +++ b/snow/networking/tracker/resource_tracker_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/math/meter" "github.com/ava-labs/avalanchego/utils/resource" + "github.com/ava-labs/avalanchego/utils/resource/resourcemock" ) func TestNewCPUTracker(t *testing.T) { @@ -40,7 +41,7 @@ func TestCPUTracker(t *testing.T) { halflife := 5 * time.Second ctrl := gomock.NewController(t) - mockUser := resource.NewMockUser(ctrl) + mockUser := resourcemock.NewUser(ctrl) mockUser.EXPECT().CPUUsage().Return(1.0).Times(3) tracker, err := NewResourceTracker(prometheus.NewRegistry(), mockUser, meter.ContinuousFactory{}, time.Second) diff --git a/snow/networking/tracker/targeter_test.go b/snow/networking/tracker/targeter_test.go index d31e64e0e93f..378cdde7affe 100644 --- a/snow/networking/tracker/targeter_test.go +++ b/snow/networking/tracker/targeter_test.go @@ -10,6 +10,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow/networking/tracker/trackermock" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/logging" @@ -26,7 +27,7 @@ func TestNewTargeter(t *testing.T) { MaxNonVdrNodeUsage: 10, } vdrs := validators.NewManager() - tracker := NewMockTracker(ctrl) + tracker := trackermock.NewTracker(ctrl) targeterIntf := NewTargeter( logging.NoLog{}, @@ -53,7 +54,7 @@ func TestTarget(t *testing.T) { require.NoError(t, vdrs.AddStaker(constants.PrimaryNetworkID, vdr, nil, ids.Empty, 1)) require.NoError(t, vdrs.AddStaker(constants.PrimaryNetworkID, ids.GenerateTestNodeID(), nil, ids.Empty, totalVdrWeight-vdrWeight)) - tracker := NewMockTracker(ctrl) + tracker := trackermock.NewTracker(ctrl) config := &TargeterConfig{ VdrAlloc: 20, MaxNonVdrUsage: 10, diff --git a/snow/networking/tracker/trackermock/targeter.go b/snow/networking/tracker/trackermock/targeter.go new file mode 100644 index 000000000000..81bf539b3c96 --- /dev/null +++ b/snow/networking/tracker/trackermock/targeter.go @@ -0,0 +1,54 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/snow/networking/tracker (interfaces: Targeter) +// +// Generated by this command: +// +// mockgen -package=trackermock -destination=snow/networking/tracker/trackermock/targeter.go -mock_names=Targeter=Targeter github.com/ava-labs/avalanchego/snow/networking/tracker Targeter +// + +// Package trackermock is a generated GoMock package. +package trackermock + +import ( + reflect "reflect" + + ids "github.com/ava-labs/avalanchego/ids" + gomock "go.uber.org/mock/gomock" +) + +// Targeter is a mock of Targeter interface. +type Targeter struct { + ctrl *gomock.Controller + recorder *TargeterMockRecorder +} + +// TargeterMockRecorder is the mock recorder for Targeter. +type TargeterMockRecorder struct { + mock *Targeter +} + +// NewTargeter creates a new mock instance. +func NewTargeter(ctrl *gomock.Controller) *Targeter { + mock := &Targeter{ctrl: ctrl} + mock.recorder = &TargeterMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Targeter) EXPECT() *TargeterMockRecorder { + return m.recorder +} + +// TargetUsage mocks base method. +func (m *Targeter) TargetUsage(arg0 ids.NodeID) float64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "TargetUsage", arg0) + ret0, _ := ret[0].(float64) + return ret0 +} + +// TargetUsage indicates an expected call of TargetUsage. +func (mr *TargeterMockRecorder) TargetUsage(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TargetUsage", reflect.TypeOf((*Targeter)(nil).TargetUsage), arg0) +} diff --git a/snow/networking/tracker/mock_resource_tracker.go b/snow/networking/tracker/trackermock/tracker.go similarity index 50% rename from snow/networking/tracker/mock_resource_tracker.go rename to snow/networking/tracker/trackermock/tracker.go index 438bd44d9b4f..9c8aaa178d64 100644 --- a/snow/networking/tracker/mock_resource_tracker.go +++ b/snow/networking/tracker/trackermock/tracker.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=tracker -destination=snow/networking/tracker/mock_resource_tracker.go github.com/ava-labs/avalanchego/snow/networking/tracker Tracker +// mockgen -package=trackermock -destination=snow/networking/tracker/trackermock/tracker.go -mock_names=Tracker=Tracker github.com/ava-labs/avalanchego/snow/networking/tracker Tracker // -// Package tracker is a generated GoMock package. -package tracker +// Package trackermock is a generated GoMock package. +package trackermock import ( reflect "reflect" @@ -17,31 +17,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockTracker is a mock of Tracker interface. -type MockTracker struct { +// Tracker is a mock of Tracker interface. +type Tracker struct { ctrl *gomock.Controller - recorder *MockTrackerMockRecorder + recorder *TrackerMockRecorder } -// MockTrackerMockRecorder is the mock recorder for MockTracker. -type MockTrackerMockRecorder struct { - mock *MockTracker +// TrackerMockRecorder is the mock recorder for Tracker. +type TrackerMockRecorder struct { + mock *Tracker } -// NewMockTracker creates a new mock instance. -func NewMockTracker(ctrl *gomock.Controller) *MockTracker { - mock := &MockTracker{ctrl: ctrl} - mock.recorder = &MockTrackerMockRecorder{mock} +// NewTracker creates a new mock instance. +func NewTracker(ctrl *gomock.Controller) *Tracker { + mock := &Tracker{ctrl: ctrl} + mock.recorder = &TrackerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTracker) EXPECT() *MockTrackerMockRecorder { +func (m *Tracker) EXPECT() *TrackerMockRecorder { return m.recorder } // TimeUntilUsage mocks base method. -func (m *MockTracker) TimeUntilUsage(arg0 ids.NodeID, arg1 time.Time, arg2 float64) time.Duration { +func (m *Tracker) TimeUntilUsage(arg0 ids.NodeID, arg1 time.Time, arg2 float64) time.Duration { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TimeUntilUsage", arg0, arg1, arg2) ret0, _ := ret[0].(time.Duration) @@ -49,13 +49,13 @@ func (m *MockTracker) TimeUntilUsage(arg0 ids.NodeID, arg1 time.Time, arg2 float } // TimeUntilUsage indicates an expected call of TimeUntilUsage. -func (mr *MockTrackerMockRecorder) TimeUntilUsage(arg0, arg1, arg2 any) *gomock.Call { +func (mr *TrackerMockRecorder) TimeUntilUsage(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TimeUntilUsage", reflect.TypeOf((*MockTracker)(nil).TimeUntilUsage), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TimeUntilUsage", reflect.TypeOf((*Tracker)(nil).TimeUntilUsage), arg0, arg1, arg2) } // TotalUsage mocks base method. -func (m *MockTracker) TotalUsage() float64 { +func (m *Tracker) TotalUsage() float64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TotalUsage") ret0, _ := ret[0].(float64) @@ -63,13 +63,13 @@ func (m *MockTracker) TotalUsage() float64 { } // TotalUsage indicates an expected call of TotalUsage. -func (mr *MockTrackerMockRecorder) TotalUsage() *gomock.Call { +func (mr *TrackerMockRecorder) TotalUsage() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TotalUsage", reflect.TypeOf((*MockTracker)(nil).TotalUsage)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TotalUsage", reflect.TypeOf((*Tracker)(nil).TotalUsage)) } // Usage mocks base method. -func (m *MockTracker) Usage(arg0 ids.NodeID, arg1 time.Time) float64 { +func (m *Tracker) Usage(arg0 ids.NodeID, arg1 time.Time) float64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Usage", arg0, arg1) ret0, _ := ret[0].(float64) @@ -77,7 +77,7 @@ func (m *MockTracker) Usage(arg0 ids.NodeID, arg1 time.Time) float64 { } // Usage indicates an expected call of Usage. -func (mr *MockTrackerMockRecorder) Usage(arg0, arg1 any) *gomock.Call { +func (mr *TrackerMockRecorder) Usage(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Usage", reflect.TypeOf((*MockTracker)(nil).Usage), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Usage", reflect.TypeOf((*Tracker)(nil).Usage), arg0, arg1) } diff --git a/snow/uptime/locked_calculator_test.go b/snow/uptime/locked_calculator_test.go index 966722f6457d..60735985f657 100644 --- a/snow/uptime/locked_calculator_test.go +++ b/snow/uptime/locked_calculator_test.go @@ -12,6 +12,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow/uptime/uptimemock" "github.com/ava-labs/avalanchego/utils" ) @@ -35,7 +36,7 @@ func TestLockedCalculator(t *testing.T) { require.ErrorIs(err, errStillBootstrapping) var isBootstrapped utils.Atomic[bool] - mockCalc := NewMockCalculator(ctrl) + mockCalc := uptimemock.NewCalculator(ctrl) // Should still error because ctx is not bootstrapped lc.SetCalculator(&isBootstrapped, &sync.Mutex{}, mockCalc) diff --git a/snow/uptime/mock_calculator.go b/snow/uptime/uptimemock/calculator.go similarity index 50% rename from snow/uptime/mock_calculator.go rename to snow/uptime/uptimemock/calculator.go index cc5b5942e639..0203b6b4a79a 100644 --- a/snow/uptime/mock_calculator.go +++ b/snow/uptime/uptimemock/calculator.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=uptime -destination=snow/uptime/mock_calculator.go github.com/ava-labs/avalanchego/snow/uptime Calculator +// mockgen -package=uptimemock -destination=snow/uptime/uptimemock/calculator.go -mock_names=Calculator=Calculator github.com/ava-labs/avalanchego/snow/uptime Calculator // -// Package uptime is a generated GoMock package. -package uptime +// Package uptimemock is a generated GoMock package. +package uptimemock import ( reflect "reflect" @@ -17,31 +17,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockCalculator is a mock of Calculator interface. -type MockCalculator struct { +// Calculator is a mock of Calculator interface. +type Calculator struct { ctrl *gomock.Controller - recorder *MockCalculatorMockRecorder + recorder *CalculatorMockRecorder } -// MockCalculatorMockRecorder is the mock recorder for MockCalculator. -type MockCalculatorMockRecorder struct { - mock *MockCalculator +// CalculatorMockRecorder is the mock recorder for Calculator. +type CalculatorMockRecorder struct { + mock *Calculator } -// NewMockCalculator creates a new mock instance. -func NewMockCalculator(ctrl *gomock.Controller) *MockCalculator { - mock := &MockCalculator{ctrl: ctrl} - mock.recorder = &MockCalculatorMockRecorder{mock} +// NewCalculator creates a new mock instance. +func NewCalculator(ctrl *gomock.Controller) *Calculator { + mock := &Calculator{ctrl: ctrl} + mock.recorder = &CalculatorMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockCalculator) EXPECT() *MockCalculatorMockRecorder { +func (m *Calculator) EXPECT() *CalculatorMockRecorder { return m.recorder } // CalculateUptime mocks base method. -func (m *MockCalculator) CalculateUptime(arg0 ids.NodeID, arg1 ids.ID) (time.Duration, time.Time, error) { +func (m *Calculator) CalculateUptime(arg0 ids.NodeID, arg1 ids.ID) (time.Duration, time.Time, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CalculateUptime", arg0, arg1) ret0, _ := ret[0].(time.Duration) @@ -51,13 +51,13 @@ func (m *MockCalculator) CalculateUptime(arg0 ids.NodeID, arg1 ids.ID) (time.Dur } // CalculateUptime indicates an expected call of CalculateUptime. -func (mr *MockCalculatorMockRecorder) CalculateUptime(arg0, arg1 any) *gomock.Call { +func (mr *CalculatorMockRecorder) CalculateUptime(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateUptime", reflect.TypeOf((*MockCalculator)(nil).CalculateUptime), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateUptime", reflect.TypeOf((*Calculator)(nil).CalculateUptime), arg0, arg1) } // CalculateUptimePercent mocks base method. -func (m *MockCalculator) CalculateUptimePercent(arg0 ids.NodeID, arg1 ids.ID) (float64, error) { +func (m *Calculator) CalculateUptimePercent(arg0 ids.NodeID, arg1 ids.ID) (float64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CalculateUptimePercent", arg0, arg1) ret0, _ := ret[0].(float64) @@ -66,13 +66,13 @@ func (m *MockCalculator) CalculateUptimePercent(arg0 ids.NodeID, arg1 ids.ID) (f } // CalculateUptimePercent indicates an expected call of CalculateUptimePercent. -func (mr *MockCalculatorMockRecorder) CalculateUptimePercent(arg0, arg1 any) *gomock.Call { +func (mr *CalculatorMockRecorder) CalculateUptimePercent(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateUptimePercent", reflect.TypeOf((*MockCalculator)(nil).CalculateUptimePercent), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateUptimePercent", reflect.TypeOf((*Calculator)(nil).CalculateUptimePercent), arg0, arg1) } // CalculateUptimePercentFrom mocks base method. -func (m *MockCalculator) CalculateUptimePercentFrom(arg0 ids.NodeID, arg1 ids.ID, arg2 time.Time) (float64, error) { +func (m *Calculator) CalculateUptimePercentFrom(arg0 ids.NodeID, arg1 ids.ID, arg2 time.Time) (float64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CalculateUptimePercentFrom", arg0, arg1, arg2) ret0, _ := ret[0].(float64) @@ -81,7 +81,7 @@ func (m *MockCalculator) CalculateUptimePercentFrom(arg0 ids.NodeID, arg1 ids.ID } // CalculateUptimePercentFrom indicates an expected call of CalculateUptimePercentFrom. -func (mr *MockCalculatorMockRecorder) CalculateUptimePercentFrom(arg0, arg1, arg2 any) *gomock.Call { +func (mr *CalculatorMockRecorder) CalculateUptimePercentFrom(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateUptimePercentFrom", reflect.TypeOf((*MockCalculator)(nil).CalculateUptimePercentFrom), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CalculateUptimePercentFrom", reflect.TypeOf((*Calculator)(nil).CalculateUptimePercentFrom), arg0, arg1, arg2) } diff --git a/snow/validators/gvalidators/validator_state_test.go b/snow/validators/gvalidators/validator_state_test.go index 8944e5c9588a..21afa1cadfb8 100644 --- a/snow/validators/gvalidators/validator_state_test.go +++ b/snow/validators/gvalidators/validator_state_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/vms/rpcchainvm/grpcutils" @@ -24,7 +25,7 @@ var errCustom = errors.New("custom") type testState struct { client *Client - server *validators.MockState + server *validatorsmock.State } func setupState(t testing.TB, ctrl *gomock.Controller) *testState { @@ -33,7 +34,7 @@ func setupState(t testing.TB, ctrl *gomock.Controller) *testState { t.Helper() state := &testState{ - server: validators.NewMockState(ctrl), + server: validatorsmock.NewState(ctrl), } listener, err := grpcutils.NewListener() diff --git a/snow/validators/mock_subnet_connector.go b/snow/validators/mock_subnet_connector.go deleted file mode 100644 index b9f3ee0519b8..000000000000 --- a/snow/validators/mock_subnet_connector.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/snow/validators (interfaces: SubnetConnector) -// -// Generated by this command: -// -// mockgen -package=validators -destination=snow/validators/mock_subnet_connector.go github.com/ava-labs/avalanchego/snow/validators SubnetConnector -// - -// Package validators is a generated GoMock package. -package validators - -import ( - context "context" - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - gomock "go.uber.org/mock/gomock" -) - -// MockSubnetConnector is a mock of SubnetConnector interface. -type MockSubnetConnector struct { - ctrl *gomock.Controller - recorder *MockSubnetConnectorMockRecorder -} - -// MockSubnetConnectorMockRecorder is the mock recorder for MockSubnetConnector. -type MockSubnetConnectorMockRecorder struct { - mock *MockSubnetConnector -} - -// NewMockSubnetConnector creates a new mock instance. -func NewMockSubnetConnector(ctrl *gomock.Controller) *MockSubnetConnector { - mock := &MockSubnetConnector{ctrl: ctrl} - mock.recorder = &MockSubnetConnectorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSubnetConnector) EXPECT() *MockSubnetConnectorMockRecorder { - return m.recorder -} - -// ConnectedSubnet mocks base method. -func (m *MockSubnetConnector) ConnectedSubnet(arg0 context.Context, arg1 ids.NodeID, arg2 ids.ID) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConnectedSubnet", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// ConnectedSubnet indicates an expected call of ConnectedSubnet. -func (mr *MockSubnetConnectorMockRecorder) ConnectedSubnet(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConnectedSubnet", reflect.TypeOf((*MockSubnetConnector)(nil).ConnectedSubnet), arg0, arg1, arg2) -} diff --git a/snow/validators/mock_state.go b/snow/validators/validatorsmock/state.go similarity index 51% rename from snow/validators/mock_state.go rename to snow/validators/validatorsmock/state.go index 6bed638becd8..7bf898d0d4e8 100644 --- a/snow/validators/mock_state.go +++ b/snow/validators/validatorsmock/state.go @@ -3,45 +3,46 @@ // // Generated by this command: // -// mockgen -package=validators -destination=snow/validators/mock_state.go github.com/ava-labs/avalanchego/snow/validators State +// mockgen -package=validatorsmock -destination=snow/validators/validatorsmock/state.go -mock_names=State=State github.com/ava-labs/avalanchego/snow/validators State // -// Package validators is a generated GoMock package. -package validators +// Package validatorsmock is a generated GoMock package. +package validatorsmock import ( context "context" reflect "reflect" ids "github.com/ava-labs/avalanchego/ids" + validators "github.com/ava-labs/avalanchego/snow/validators" gomock "go.uber.org/mock/gomock" ) -// MockState is a mock of State interface. -type MockState struct { +// State is a mock of State interface. +type State struct { ctrl *gomock.Controller - recorder *MockStateMockRecorder + recorder *StateMockRecorder } -// MockStateMockRecorder is the mock recorder for MockState. -type MockStateMockRecorder struct { - mock *MockState +// StateMockRecorder is the mock recorder for State. +type StateMockRecorder struct { + mock *State } -// NewMockState creates a new mock instance. -func NewMockState(ctrl *gomock.Controller) *MockState { - mock := &MockState{ctrl: ctrl} - mock.recorder = &MockStateMockRecorder{mock} +// NewState creates a new mock instance. +func NewState(ctrl *gomock.Controller) *State { + mock := &State{ctrl: ctrl} + mock.recorder = &StateMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockState) EXPECT() *MockStateMockRecorder { +func (m *State) EXPECT() *StateMockRecorder { return m.recorder } // GetCurrentHeight mocks base method. -func (m *MockState) GetCurrentHeight(arg0 context.Context) (uint64, error) { +func (m *State) GetCurrentHeight(arg0 context.Context) (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetCurrentHeight", arg0) ret0, _ := ret[0].(uint64) @@ -50,13 +51,13 @@ func (m *MockState) GetCurrentHeight(arg0 context.Context) (uint64, error) { } // GetCurrentHeight indicates an expected call of GetCurrentHeight. -func (mr *MockStateMockRecorder) GetCurrentHeight(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) GetCurrentHeight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentHeight", reflect.TypeOf((*MockState)(nil).GetCurrentHeight), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentHeight", reflect.TypeOf((*State)(nil).GetCurrentHeight), arg0) } // GetMinimumHeight mocks base method. -func (m *MockState) GetMinimumHeight(arg0 context.Context) (uint64, error) { +func (m *State) GetMinimumHeight(arg0 context.Context) (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetMinimumHeight", arg0) ret0, _ := ret[0].(uint64) @@ -65,13 +66,13 @@ func (m *MockState) GetMinimumHeight(arg0 context.Context) (uint64, error) { } // GetMinimumHeight indicates an expected call of GetMinimumHeight. -func (mr *MockStateMockRecorder) GetMinimumHeight(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) GetMinimumHeight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMinimumHeight", reflect.TypeOf((*MockState)(nil).GetMinimumHeight), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMinimumHeight", reflect.TypeOf((*State)(nil).GetMinimumHeight), arg0) } // GetSubnetID mocks base method. -func (m *MockState) GetSubnetID(arg0 context.Context, arg1 ids.ID) (ids.ID, error) { +func (m *State) GetSubnetID(arg0 context.Context, arg1 ids.ID) (ids.ID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetSubnetID", arg0, arg1) ret0, _ := ret[0].(ids.ID) @@ -80,22 +81,22 @@ func (m *MockState) GetSubnetID(arg0 context.Context, arg1 ids.ID) (ids.ID, erro } // GetSubnetID indicates an expected call of GetSubnetID. -func (mr *MockStateMockRecorder) GetSubnetID(arg0, arg1 any) *gomock.Call { +func (mr *StateMockRecorder) GetSubnetID(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetID", reflect.TypeOf((*MockState)(nil).GetSubnetID), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetID", reflect.TypeOf((*State)(nil).GetSubnetID), arg0, arg1) } // GetValidatorSet mocks base method. -func (m *MockState) GetValidatorSet(arg0 context.Context, arg1 uint64, arg2 ids.ID) (map[ids.NodeID]*GetValidatorOutput, error) { +func (m *State) GetValidatorSet(arg0 context.Context, arg1 uint64, arg2 ids.ID) (map[ids.NodeID]*validators.GetValidatorOutput, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetValidatorSet", arg0, arg1, arg2) - ret0, _ := ret[0].(map[ids.NodeID]*GetValidatorOutput) + ret0, _ := ret[0].(map[ids.NodeID]*validators.GetValidatorOutput) ret1, _ := ret[1].(error) return ret0, ret1 } // GetValidatorSet indicates an expected call of GetValidatorSet. -func (mr *MockStateMockRecorder) GetValidatorSet(arg0, arg1, arg2 any) *gomock.Call { +func (mr *StateMockRecorder) GetValidatorSet(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetValidatorSet", reflect.TypeOf((*MockState)(nil).GetValidatorSet), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetValidatorSet", reflect.TypeOf((*State)(nil).GetValidatorSet), arg0, arg1, arg2) } diff --git a/snow/validators/validatorsmock/subnet_connector.go b/snow/validators/validatorsmock/subnet_connector.go new file mode 100644 index 000000000000..118a287ac68a --- /dev/null +++ b/snow/validators/validatorsmock/subnet_connector.go @@ -0,0 +1,55 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/snow/validators (interfaces: SubnetConnector) +// +// Generated by this command: +// +// mockgen -package=validatorsmock -destination=snow/validators/validatorsmock/subnet_connector.go -mock_names=SubnetConnector=SubnetConnector github.com/ava-labs/avalanchego/snow/validators SubnetConnector +// + +// Package validatorsmock is a generated GoMock package. +package validatorsmock + +import ( + context "context" + reflect "reflect" + + ids "github.com/ava-labs/avalanchego/ids" + gomock "go.uber.org/mock/gomock" +) + +// SubnetConnector is a mock of SubnetConnector interface. +type SubnetConnector struct { + ctrl *gomock.Controller + recorder *SubnetConnectorMockRecorder +} + +// SubnetConnectorMockRecorder is the mock recorder for SubnetConnector. +type SubnetConnectorMockRecorder struct { + mock *SubnetConnector +} + +// NewSubnetConnector creates a new mock instance. +func NewSubnetConnector(ctrl *gomock.Controller) *SubnetConnector { + mock := &SubnetConnector{ctrl: ctrl} + mock.recorder = &SubnetConnectorMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *SubnetConnector) EXPECT() *SubnetConnectorMockRecorder { + return m.recorder +} + +// ConnectedSubnet mocks base method. +func (m *SubnetConnector) ConnectedSubnet(arg0 context.Context, arg1 ids.NodeID, arg2 ids.ID) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ConnectedSubnet", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 +} + +// ConnectedSubnet indicates an expected call of ConnectedSubnet. +func (mr *SubnetConnectorMockRecorder) ConnectedSubnet(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConnectedSubnet", reflect.TypeOf((*SubnetConnector)(nil).ConnectedSubnet), arg0, arg1, arg2) +} diff --git a/utils/crypto/keychain/keychain_test.go b/utils/crypto/keychain/keychain_test.go index f0ffba7f0438..2daa231a014a 100644 --- a/utils/crypto/keychain/keychain_test.go +++ b/utils/crypto/keychain/keychain_test.go @@ -11,6 +11,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/crypto/keychain/keychainmock" ) var errTest = errors.New("test") @@ -22,24 +23,24 @@ func TestNewLedgerKeychain(t *testing.T) { addr := ids.GenerateTestShortID() // user request invalid number of addresses to derive - ledger := NewMockLedger(ctrl) + ledger := keychainmock.NewLedger(ctrl) _, err := NewLedgerKeychain(ledger, 0) require.ErrorIs(err, ErrInvalidNumAddrsToDerive) // ledger does not return expected number of derived addresses - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{}, nil).Times(1) _, err = NewLedgerKeychain(ledger, 1) require.ErrorIs(err, ErrInvalidNumAddrsDerived) // ledger return error when asked for derived addresses - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr}, errTest).Times(1) _, err = NewLedgerKeychain(ledger, 1) require.ErrorIs(err, errTest) // good path - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr}, nil).Times(1) _, err = NewLedgerKeychain(ledger, 1) require.NoError(err) @@ -54,7 +55,7 @@ func TestLedgerKeychain_Addresses(t *testing.T) { addr3 := ids.GenerateTestShortID() // 1 addr - ledger := NewMockLedger(ctrl) + ledger := keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) kc, err := NewLedgerKeychain(ledger, 1) require.NoError(err) @@ -64,7 +65,7 @@ func TestLedgerKeychain_Addresses(t *testing.T) { require.True(addrs.Contains(addr1)) // multiple addresses - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0, 1, 2}).Return([]ids.ShortID{addr1, addr2, addr3}, nil).Times(1) kc, err = NewLedgerKeychain(ledger, 3) require.NoError(err) @@ -85,7 +86,7 @@ func TestLedgerKeychain_Get(t *testing.T) { addr3 := ids.GenerateTestShortID() // 1 addr - ledger := NewMockLedger(ctrl) + ledger := keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) kc, err := NewLedgerKeychain(ledger, 1) require.NoError(err) @@ -98,7 +99,7 @@ func TestLedgerKeychain_Get(t *testing.T) { require.True(b) // multiple addresses - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0, 1, 2}).Return([]ids.ShortID{addr1, addr2, addr3}, nil).Times(1) kc, err = NewLedgerKeychain(ledger, 3) require.NoError(err) @@ -132,7 +133,7 @@ func TestLedgerSigner_SignHash(t *testing.T) { expectedSignature3 := []byte{3, 3, 3} // ledger returns an incorrect number of signatures - ledger := NewMockLedger(ctrl) + ledger := keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{0}).Return([][]byte{}, nil).Times(1) kc, err := NewLedgerKeychain(ledger, 1) @@ -145,7 +146,7 @@ func TestLedgerSigner_SignHash(t *testing.T) { require.ErrorIs(err, ErrInvalidNumSignatures) // ledger returns an error when asked for signature - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{0}).Return([][]byte{expectedSignature1}, errTest).Times(1) kc, err = NewLedgerKeychain(ledger, 1) @@ -158,7 +159,7 @@ func TestLedgerSigner_SignHash(t *testing.T) { require.ErrorIs(err, errTest) // good path 1 addr - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{0}).Return([][]byte{expectedSignature1}, nil).Times(1) kc, err = NewLedgerKeychain(ledger, 1) @@ -172,7 +173,7 @@ func TestLedgerSigner_SignHash(t *testing.T) { require.Equal(expectedSignature1, signature) // good path 3 addr - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0, 1, 2}).Return([]ids.ShortID{addr1, addr2, addr3}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{0}).Return([][]byte{expectedSignature1}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{1}).Return([][]byte{expectedSignature2}, nil).Times(1) @@ -210,24 +211,24 @@ func TestNewLedgerKeychainFromIndices(t *testing.T) { _ = addr // user request invalid number of indices - ledger := NewMockLedger(ctrl) + ledger := keychainmock.NewLedger(ctrl) _, err := NewLedgerKeychainFromIndices(ledger, []uint32{}) require.ErrorIs(err, ErrInvalidIndicesLength) // ledger does not return expected number of derived addresses - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{}, nil).Times(1) _, err = NewLedgerKeychainFromIndices(ledger, []uint32{0}) require.ErrorIs(err, ErrInvalidNumAddrsDerived) // ledger return error when asked for derived addresses - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr}, errTest).Times(1) _, err = NewLedgerKeychainFromIndices(ledger, []uint32{0}) require.ErrorIs(err, errTest) // good path - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr}, nil).Times(1) _, err = NewLedgerKeychainFromIndices(ledger, []uint32{0}) require.NoError(err) @@ -242,7 +243,7 @@ func TestLedgerKeychainFromIndices_Addresses(t *testing.T) { addr3 := ids.GenerateTestShortID() // 1 addr - ledger := NewMockLedger(ctrl) + ledger := keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) kc, err := NewLedgerKeychainFromIndices(ledger, []uint32{0}) require.NoError(err) @@ -252,7 +253,7 @@ func TestLedgerKeychainFromIndices_Addresses(t *testing.T) { require.True(addrs.Contains(addr1)) // first 3 addresses - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0, 1, 2}).Return([]ids.ShortID{addr1, addr2, addr3}, nil).Times(1) kc, err = NewLedgerKeychainFromIndices(ledger, []uint32{0, 1, 2}) require.NoError(err) @@ -266,7 +267,7 @@ func TestLedgerKeychainFromIndices_Addresses(t *testing.T) { // some 3 addresses indices := []uint32{3, 7, 1} addresses := []ids.ShortID{addr1, addr2, addr3} - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses(indices).Return(addresses, nil).Times(1) kc, err = NewLedgerKeychainFromIndices(ledger, indices) require.NoError(err) @@ -280,7 +281,7 @@ func TestLedgerKeychainFromIndices_Addresses(t *testing.T) { // repeated addresses indices = []uint32{3, 7, 1, 3, 1, 7} addresses = []ids.ShortID{addr1, addr2, addr3, addr1, addr2, addr3} - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses(indices).Return(addresses, nil).Times(1) kc, err = NewLedgerKeychainFromIndices(ledger, indices) require.NoError(err) @@ -301,7 +302,7 @@ func TestLedgerKeychainFromIndices_Get(t *testing.T) { addr3 := ids.GenerateTestShortID() // 1 addr - ledger := NewMockLedger(ctrl) + ledger := keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) kc, err := NewLedgerKeychainFromIndices(ledger, []uint32{0}) require.NoError(err) @@ -316,7 +317,7 @@ func TestLedgerKeychainFromIndices_Get(t *testing.T) { // some 3 addresses indices := []uint32{3, 7, 1} addresses := []ids.ShortID{addr1, addr2, addr3} - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses(indices).Return(addresses, nil).Times(1) kc, err = NewLedgerKeychainFromIndices(ledger, indices) require.NoError(err) @@ -350,7 +351,7 @@ func TestLedgerSignerFromIndices_SignHash(t *testing.T) { expectedSignature3 := []byte{3, 3, 3} // ledger returns an incorrect number of signatures - ledger := NewMockLedger(ctrl) + ledger := keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{0}).Return([][]byte{}, nil).Times(1) kc, err := NewLedgerKeychainFromIndices(ledger, []uint32{0}) @@ -363,7 +364,7 @@ func TestLedgerSignerFromIndices_SignHash(t *testing.T) { require.ErrorIs(err, ErrInvalidNumSignatures) // ledger returns an error when asked for signature - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{0}).Return([][]byte{expectedSignature1}, errTest).Times(1) kc, err = NewLedgerKeychainFromIndices(ledger, []uint32{0}) @@ -376,7 +377,7 @@ func TestLedgerSignerFromIndices_SignHash(t *testing.T) { require.ErrorIs(err, errTest) // good path 1 addr - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses([]uint32{0}).Return([]ids.ShortID{addr1}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{0}).Return([][]byte{expectedSignature1}, nil).Times(1) kc, err = NewLedgerKeychainFromIndices(ledger, []uint32{0}) @@ -392,7 +393,7 @@ func TestLedgerSignerFromIndices_SignHash(t *testing.T) { // good path some 3 addresses indices := []uint32{3, 7, 1} addresses := []ids.ShortID{addr1, addr2, addr3} - ledger = NewMockLedger(ctrl) + ledger = keychainmock.NewLedger(ctrl) ledger.EXPECT().Addresses(indices).Return(addresses, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{indices[0]}).Return([][]byte{expectedSignature1}, nil).Times(1) ledger.EXPECT().SignHash(toSign, []uint32{indices[1]}).Return([][]byte{expectedSignature2}, nil).Times(1) diff --git a/utils/crypto/keychain/mock_ledger.go b/utils/crypto/keychain/keychainmock/ledger.go similarity index 56% rename from utils/crypto/keychain/mock_ledger.go rename to utils/crypto/keychain/keychainmock/ledger.go index b082631c416e..378001e1d3ba 100644 --- a/utils/crypto/keychain/mock_ledger.go +++ b/utils/crypto/keychain/keychainmock/ledger.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=keychain -destination=utils/crypto/keychain/mock_ledger.go github.com/ava-labs/avalanchego/utils/crypto/keychain Ledger +// mockgen -package=keychainmock -destination=utils/crypto/keychain/keychainmock/ledger.go -mock_names=Ledger=Ledger github.com/ava-labs/avalanchego/utils/crypto/keychain Ledger // -// Package keychain is a generated GoMock package. -package keychain +// Package keychainmock is a generated GoMock package. +package keychainmock import ( reflect "reflect" @@ -17,31 +17,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockLedger is a mock of Ledger interface. -type MockLedger struct { +// Ledger is a mock of Ledger interface. +type Ledger struct { ctrl *gomock.Controller - recorder *MockLedgerMockRecorder + recorder *LedgerMockRecorder } -// MockLedgerMockRecorder is the mock recorder for MockLedger. -type MockLedgerMockRecorder struct { - mock *MockLedger +// LedgerMockRecorder is the mock recorder for Ledger. +type LedgerMockRecorder struct { + mock *Ledger } -// NewMockLedger creates a new mock instance. -func NewMockLedger(ctrl *gomock.Controller) *MockLedger { - mock := &MockLedger{ctrl: ctrl} - mock.recorder = &MockLedgerMockRecorder{mock} +// NewLedger creates a new mock instance. +func NewLedger(ctrl *gomock.Controller) *Ledger { + mock := &Ledger{ctrl: ctrl} + mock.recorder = &LedgerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockLedger) EXPECT() *MockLedgerMockRecorder { +func (m *Ledger) EXPECT() *LedgerMockRecorder { return m.recorder } // Address mocks base method. -func (m *MockLedger) Address(arg0 string, arg1 uint32) (ids.ShortID, error) { +func (m *Ledger) Address(arg0 string, arg1 uint32) (ids.ShortID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Address", arg0, arg1) ret0, _ := ret[0].(ids.ShortID) @@ -50,13 +50,13 @@ func (m *MockLedger) Address(arg0 string, arg1 uint32) (ids.ShortID, error) { } // Address indicates an expected call of Address. -func (mr *MockLedgerMockRecorder) Address(arg0, arg1 any) *gomock.Call { +func (mr *LedgerMockRecorder) Address(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Address", reflect.TypeOf((*MockLedger)(nil).Address), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Address", reflect.TypeOf((*Ledger)(nil).Address), arg0, arg1) } // Addresses mocks base method. -func (m *MockLedger) Addresses(arg0 []uint32) ([]ids.ShortID, error) { +func (m *Ledger) Addresses(arg0 []uint32) ([]ids.ShortID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Addresses", arg0) ret0, _ := ret[0].([]ids.ShortID) @@ -65,13 +65,13 @@ func (m *MockLedger) Addresses(arg0 []uint32) ([]ids.ShortID, error) { } // Addresses indicates an expected call of Addresses. -func (mr *MockLedgerMockRecorder) Addresses(arg0 any) *gomock.Call { +func (mr *LedgerMockRecorder) Addresses(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Addresses", reflect.TypeOf((*MockLedger)(nil).Addresses), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Addresses", reflect.TypeOf((*Ledger)(nil).Addresses), arg0) } // Disconnect mocks base method. -func (m *MockLedger) Disconnect() error { +func (m *Ledger) Disconnect() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Disconnect") ret0, _ := ret[0].(error) @@ -79,13 +79,13 @@ func (m *MockLedger) Disconnect() error { } // Disconnect indicates an expected call of Disconnect. -func (mr *MockLedgerMockRecorder) Disconnect() *gomock.Call { +func (mr *LedgerMockRecorder) Disconnect() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnect", reflect.TypeOf((*MockLedger)(nil).Disconnect)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnect", reflect.TypeOf((*Ledger)(nil).Disconnect)) } // Sign mocks base method. -func (m *MockLedger) Sign(arg0 []byte, arg1 []uint32) ([][]byte, error) { +func (m *Ledger) Sign(arg0 []byte, arg1 []uint32) ([][]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Sign", arg0, arg1) ret0, _ := ret[0].([][]byte) @@ -94,13 +94,13 @@ func (m *MockLedger) Sign(arg0 []byte, arg1 []uint32) ([][]byte, error) { } // Sign indicates an expected call of Sign. -func (mr *MockLedgerMockRecorder) Sign(arg0, arg1 any) *gomock.Call { +func (mr *LedgerMockRecorder) Sign(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sign", reflect.TypeOf((*MockLedger)(nil).Sign), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Sign", reflect.TypeOf((*Ledger)(nil).Sign), arg0, arg1) } // SignHash mocks base method. -func (m *MockLedger) SignHash(arg0 []byte, arg1 []uint32) ([][]byte, error) { +func (m *Ledger) SignHash(arg0 []byte, arg1 []uint32) ([][]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SignHash", arg0, arg1) ret0, _ := ret[0].([][]byte) @@ -109,13 +109,13 @@ func (m *MockLedger) SignHash(arg0 []byte, arg1 []uint32) ([][]byte, error) { } // SignHash indicates an expected call of SignHash. -func (mr *MockLedgerMockRecorder) SignHash(arg0, arg1 any) *gomock.Call { +func (mr *LedgerMockRecorder) SignHash(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SignHash", reflect.TypeOf((*MockLedger)(nil).SignHash), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SignHash", reflect.TypeOf((*Ledger)(nil).SignHash), arg0, arg1) } // Version mocks base method. -func (m *MockLedger) Version() (*version.Semantic, error) { +func (m *Ledger) Version() (*version.Semantic, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Version") ret0, _ := ret[0].(*version.Semantic) @@ -124,7 +124,7 @@ func (m *MockLedger) Version() (*version.Semantic, error) { } // Version indicates an expected call of Version. -func (mr *MockLedgerMockRecorder) Version() *gomock.Call { +func (mr *LedgerMockRecorder) Version() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Version", reflect.TypeOf((*MockLedger)(nil).Version)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Version", reflect.TypeOf((*Ledger)(nil).Version)) } diff --git a/utils/filesystem/filesystemmock/reader.go b/utils/filesystem/filesystemmock/reader.go new file mode 100644 index 000000000000..3875190621ce --- /dev/null +++ b/utils/filesystem/filesystemmock/reader.go @@ -0,0 +1,55 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/utils/filesystem (interfaces: Reader) +// +// Generated by this command: +// +// mockgen -package=filesystemmock -destination=utils/filesystem/filesystemmock/reader.go -mock_names=Reader=Reader github.com/ava-labs/avalanchego/utils/filesystem Reader +// + +// Package filesystemmock is a generated GoMock package. +package filesystemmock + +import ( + fs "io/fs" + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// Reader is a mock of Reader interface. +type Reader struct { + ctrl *gomock.Controller + recorder *ReaderMockRecorder +} + +// ReaderMockRecorder is the mock recorder for Reader. +type ReaderMockRecorder struct { + mock *Reader +} + +// NewReader creates a new mock instance. +func NewReader(ctrl *gomock.Controller) *Reader { + mock := &Reader{ctrl: ctrl} + mock.recorder = &ReaderMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Reader) EXPECT() *ReaderMockRecorder { + return m.recorder +} + +// ReadDir mocks base method. +func (m *Reader) ReadDir(arg0 string) ([]fs.DirEntry, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ReadDir", arg0) + ret0, _ := ret[0].([]fs.DirEntry) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ReadDir indicates an expected call of ReadDir. +func (mr *ReaderMockRecorder) ReadDir(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadDir", reflect.TypeOf((*Reader)(nil).ReadDir), arg0) +} diff --git a/utils/filesystem/mock_io.go b/utils/filesystem/mock_io.go deleted file mode 100644 index 06b27dd18dd0..000000000000 --- a/utils/filesystem/mock_io.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/utils/filesystem (interfaces: Reader) -// -// Generated by this command: -// -// mockgen -package=filesystem -destination=utils/filesystem/mock_io.go github.com/ava-labs/avalanchego/utils/filesystem Reader -// - -// Package filesystem is a generated GoMock package. -package filesystem - -import ( - fs "io/fs" - reflect "reflect" - - gomock "go.uber.org/mock/gomock" -) - -// MockReader is a mock of Reader interface. -type MockReader struct { - ctrl *gomock.Controller - recorder *MockReaderMockRecorder -} - -// MockReaderMockRecorder is the mock recorder for MockReader. -type MockReaderMockRecorder struct { - mock *MockReader -} - -// NewMockReader creates a new mock instance. -func NewMockReader(ctrl *gomock.Controller) *MockReader { - mock := &MockReader{ctrl: ctrl} - mock.recorder = &MockReaderMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockReader) EXPECT() *MockReaderMockRecorder { - return m.recorder -} - -// ReadDir mocks base method. -func (m *MockReader) ReadDir(arg0 string) ([]fs.DirEntry, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ReadDir", arg0) - ret0, _ := ret[0].([]fs.DirEntry) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ReadDir indicates an expected call of ReadDir. -func (mr *MockReaderMockRecorder) ReadDir(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReadDir", reflect.TypeOf((*MockReader)(nil).ReadDir), arg0) -} diff --git a/utils/hashing/consistent/ring_test.go b/utils/hashing/consistent/ring_test.go index e22848368494..34d29eeeb471 100644 --- a/utils/hashing/consistent/ring_test.go +++ b/utils/hashing/consistent/ring_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" - "github.com/ava-labs/avalanchego/utils/hashing" + "github.com/ava-labs/avalanchego/utils/hashing/hashingmock" ) var ( @@ -435,9 +435,9 @@ func TestIteration(t *testing.T) { require.Equal(node2, node) } -func setupTest(t *testing.T, virtualNodes int) (Ring, *hashing.MockHasher) { +func setupTest(t *testing.T, virtualNodes int) (Ring, *hashingmock.Hasher) { ctrl := gomock.NewController(t) - hasher := hashing.NewMockHasher(ctrl) + hasher := hashingmock.NewHasher(ctrl) return NewHashRing(RingConfig{ VirtualNodes: virtualNodes, diff --git a/utils/hashing/hashingmock/hasher.go b/utils/hashing/hashingmock/hasher.go new file mode 100644 index 000000000000..dc0642b45800 --- /dev/null +++ b/utils/hashing/hashingmock/hasher.go @@ -0,0 +1,53 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/utils/hashing (interfaces: Hasher) +// +// Generated by this command: +// +// mockgen -package=hashingmock -destination=utils/hashing/hashingmock/hasher.go -mock_names=Hasher=Hasher github.com/ava-labs/avalanchego/utils/hashing Hasher +// + +// Package hashingmock is a generated GoMock package. +package hashingmock + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// Hasher is a mock of Hasher interface. +type Hasher struct { + ctrl *gomock.Controller + recorder *HasherMockRecorder +} + +// HasherMockRecorder is the mock recorder for Hasher. +type HasherMockRecorder struct { + mock *Hasher +} + +// NewHasher creates a new mock instance. +func NewHasher(ctrl *gomock.Controller) *Hasher { + mock := &Hasher{ctrl: ctrl} + mock.recorder = &HasherMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Hasher) EXPECT() *HasherMockRecorder { + return m.recorder +} + +// Hash mocks base method. +func (m *Hasher) Hash(arg0 []byte) uint64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Hash", arg0) + ret0, _ := ret[0].(uint64) + return ret0 +} + +// Hash indicates an expected call of Hash. +func (mr *HasherMockRecorder) Hash(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Hash", reflect.TypeOf((*Hasher)(nil).Hash), arg0) +} diff --git a/utils/hashing/mock_hasher.go b/utils/hashing/mock_hasher.go deleted file mode 100644 index c2d5ea4b3918..000000000000 --- a/utils/hashing/mock_hasher.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/utils/hashing (interfaces: Hasher) -// -// Generated by this command: -// -// mockgen -package=hashing -destination=utils/hashing/mock_hasher.go github.com/ava-labs/avalanchego/utils/hashing Hasher -// - -// Package hashing is a generated GoMock package. -package hashing - -import ( - reflect "reflect" - - gomock "go.uber.org/mock/gomock" -) - -// MockHasher is a mock of Hasher interface. -type MockHasher struct { - ctrl *gomock.Controller - recorder *MockHasherMockRecorder -} - -// MockHasherMockRecorder is the mock recorder for MockHasher. -type MockHasherMockRecorder struct { - mock *MockHasher -} - -// NewMockHasher creates a new mock instance. -func NewMockHasher(ctrl *gomock.Controller) *MockHasher { - mock := &MockHasher{ctrl: ctrl} - mock.recorder = &MockHasherMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockHasher) EXPECT() *MockHasherMockRecorder { - return m.recorder -} - -// Hash mocks base method. -func (m *MockHasher) Hash(arg0 []byte) uint64 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Hash", arg0) - ret0, _ := ret[0].(uint64) - return ret0 -} - -// Hash indicates an expected call of Hash. -func (mr *MockHasherMockRecorder) Hash(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Hash", reflect.TypeOf((*MockHasher)(nil).Hash), arg0) -} diff --git a/utils/resource/mock_user.go b/utils/resource/resourcemock/user.go similarity index 53% rename from utils/resource/mock_user.go rename to utils/resource/resourcemock/user.go index d333f2c58e4b..01e634ae2ee0 100644 --- a/utils/resource/mock_user.go +++ b/utils/resource/resourcemock/user.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=resource -destination=utils/resource/mock_user.go github.com/ava-labs/avalanchego/utils/resource User +// mockgen -package=resourcemock -destination=utils/resource/resourcemock/user.go -mock_names=User=User github.com/ava-labs/avalanchego/utils/resource User // -// Package resource is a generated GoMock package. -package resource +// Package resourcemock is a generated GoMock package. +package resourcemock import ( reflect "reflect" @@ -15,31 +15,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockUser is a mock of User interface. -type MockUser struct { +// User is a mock of User interface. +type User struct { ctrl *gomock.Controller - recorder *MockUserMockRecorder + recorder *UserMockRecorder } -// MockUserMockRecorder is the mock recorder for MockUser. -type MockUserMockRecorder struct { - mock *MockUser +// UserMockRecorder is the mock recorder for User. +type UserMockRecorder struct { + mock *User } -// NewMockUser creates a new mock instance. -func NewMockUser(ctrl *gomock.Controller) *MockUser { - mock := &MockUser{ctrl: ctrl} - mock.recorder = &MockUserMockRecorder{mock} +// NewUser creates a new mock instance. +func NewUser(ctrl *gomock.Controller) *User { + mock := &User{ctrl: ctrl} + mock.recorder = &UserMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockUser) EXPECT() *MockUserMockRecorder { +func (m *User) EXPECT() *UserMockRecorder { return m.recorder } // AvailableDiskBytes mocks base method. -func (m *MockUser) AvailableDiskBytes() uint64 { +func (m *User) AvailableDiskBytes() uint64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AvailableDiskBytes") ret0, _ := ret[0].(uint64) @@ -47,13 +47,13 @@ func (m *MockUser) AvailableDiskBytes() uint64 { } // AvailableDiskBytes indicates an expected call of AvailableDiskBytes. -func (mr *MockUserMockRecorder) AvailableDiskBytes() *gomock.Call { +func (mr *UserMockRecorder) AvailableDiskBytes() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AvailableDiskBytes", reflect.TypeOf((*MockUser)(nil).AvailableDiskBytes)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AvailableDiskBytes", reflect.TypeOf((*User)(nil).AvailableDiskBytes)) } // CPUUsage mocks base method. -func (m *MockUser) CPUUsage() float64 { +func (m *User) CPUUsage() float64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "CPUUsage") ret0, _ := ret[0].(float64) @@ -61,13 +61,13 @@ func (m *MockUser) CPUUsage() float64 { } // CPUUsage indicates an expected call of CPUUsage. -func (mr *MockUserMockRecorder) CPUUsage() *gomock.Call { +func (mr *UserMockRecorder) CPUUsage() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CPUUsage", reflect.TypeOf((*MockUser)(nil).CPUUsage)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CPUUsage", reflect.TypeOf((*User)(nil).CPUUsage)) } // DiskUsage mocks base method. -func (m *MockUser) DiskUsage() (float64, float64) { +func (m *User) DiskUsage() (float64, float64) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DiskUsage") ret0, _ := ret[0].(float64) @@ -76,7 +76,7 @@ func (m *MockUser) DiskUsage() (float64, float64) { } // DiskUsage indicates an expected call of DiskUsage. -func (mr *MockUserMockRecorder) DiskUsage() *gomock.Call { +func (mr *UserMockRecorder) DiskUsage() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DiskUsage", reflect.TypeOf((*MockUser)(nil).DiskUsage)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DiskUsage", reflect.TypeOf((*User)(nil).DiskUsage)) } diff --git a/vms/avm/block/builder/builder_test.go b/vms/avm/block/builder/builder_test.go index 36159598b706..92a2bb196dab 100644 --- a/vms/avm/block/builder/builder_test.go +++ b/vms/avm/block/builder/builder_test.go @@ -14,6 +14,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/codec" + "github.com/ava-labs/avalanchego/codec/codecmock" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/database/versiondb" "github.com/ava-labs/avalanchego/ids" @@ -25,11 +26,15 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/vms/avm/block" + "github.com/ava-labs/avalanchego/vms/avm/block/executor/executormock" "github.com/ava-labs/avalanchego/vms/avm/fxs" "github.com/ava-labs/avalanchego/vms/avm/metrics" "github.com/ava-labs/avalanchego/vms/avm/state" + "github.com/ava-labs/avalanchego/vms/avm/state/statemock" "github.com/ava-labs/avalanchego/vms/avm/txs" "github.com/ava-labs/avalanchego/vms/avm/txs/mempool" + "github.com/ava-labs/avalanchego/vms/avm/txs/mempool/mempoolmock" + "github.com/ava-labs/avalanchego/vms/avm/txs/txsmock" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -57,11 +62,11 @@ func TestBuilderBuildBlock(t *testing.T) { name: "can't get stateless block", builderFunc: func(ctrl *gomock.Controller) Builder { preferredID := ids.GenerateTestID() - manager := blkexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().Preferred().Return(preferredID) manager.EXPECT().GetStatelessBlock(preferredID).Return(nil, errTest) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().RequestBuildBlock() return New( @@ -87,12 +92,12 @@ func TestBuilderBuildBlock(t *testing.T) { preferredBlock.EXPECT().Height().Return(preferredHeight) preferredBlock.EXPECT().Timestamp().Return(preferredTimestamp) - manager := blkexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().Preferred().Return(preferredID) manager.EXPECT().GetStatelessBlock(preferredID).Return(preferredBlock, nil) manager.EXPECT().GetState(preferredID).Return(nil, false) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().RequestBuildBlock() return New( @@ -118,20 +123,20 @@ func TestBuilderBuildBlock(t *testing.T) { preferredBlock.EXPECT().Height().Return(preferredHeight) preferredBlock.EXPECT().Timestamp().Return(preferredTimestamp) - preferredState := state.NewMockChain(ctrl) + preferredState := statemock.NewChain(ctrl) preferredState.EXPECT().GetLastAccepted().Return(preferredID) preferredState.EXPECT().GetTimestamp().Return(preferredTimestamp) - manager := blkexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().Preferred().Return(preferredID) manager.EXPECT().GetStatelessBlock(preferredID).Return(preferredBlock, nil) manager.EXPECT().GetState(preferredID).Return(preferredState, true) - unsignedTx := txs.NewMockUnsignedTx(ctrl) + unsignedTx := txsmock.NewUnsignedTx(ctrl) unsignedTx.EXPECT().Visit(gomock.Any()).Return(errTest) // Fail semantic verification tx := &txs.Tx{Unsigned: unsignedTx} - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Peek().Return(tx, true) mempool.EXPECT().Remove([]*txs.Tx{tx}) mempool.EXPECT().MarkDropped(tx.ID(), errTest) @@ -162,21 +167,21 @@ func TestBuilderBuildBlock(t *testing.T) { preferredBlock.EXPECT().Height().Return(preferredHeight) preferredBlock.EXPECT().Timestamp().Return(preferredTimestamp) - preferredState := state.NewMockChain(ctrl) + preferredState := statemock.NewChain(ctrl) preferredState.EXPECT().GetLastAccepted().Return(preferredID) preferredState.EXPECT().GetTimestamp().Return(preferredTimestamp) - manager := blkexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().Preferred().Return(preferredID) manager.EXPECT().GetStatelessBlock(preferredID).Return(preferredBlock, nil) manager.EXPECT().GetState(preferredID).Return(preferredState, true) - unsignedTx := txs.NewMockUnsignedTx(ctrl) + unsignedTx := txsmock.NewUnsignedTx(ctrl) unsignedTx.EXPECT().Visit(gomock.Any()).Return(nil) // Pass semantic verification unsignedTx.EXPECT().Visit(gomock.Any()).Return(errTest) // Fail execution tx := &txs.Tx{Unsigned: unsignedTx} - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Peek().Return(tx, true) mempool.EXPECT().Remove([]*txs.Tx{tx}) mempool.EXPECT().MarkDropped(tx.ID(), errTest) @@ -207,22 +212,22 @@ func TestBuilderBuildBlock(t *testing.T) { preferredBlock.EXPECT().Height().Return(preferredHeight) preferredBlock.EXPECT().Timestamp().Return(preferredTimestamp) - preferredState := state.NewMockChain(ctrl) + preferredState := statemock.NewChain(ctrl) preferredState.EXPECT().GetLastAccepted().Return(preferredID) preferredState.EXPECT().GetTimestamp().Return(preferredTimestamp) - manager := blkexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().Preferred().Return(preferredID) manager.EXPECT().GetStatelessBlock(preferredID).Return(preferredBlock, nil) manager.EXPECT().GetState(preferredID).Return(preferredState, true) manager.EXPECT().VerifyUniqueInputs(preferredID, gomock.Any()).Return(errTest) - unsignedTx := txs.NewMockUnsignedTx(ctrl) + unsignedTx := txsmock.NewUnsignedTx(ctrl) unsignedTx.EXPECT().Visit(gomock.Any()).Return(nil) // Pass semantic verification unsignedTx.EXPECT().Visit(gomock.Any()).Return(nil) // Pass execution tx := &txs.Tx{Unsigned: unsignedTx} - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Peek().Return(tx, true) mempool.EXPECT().Remove([]*txs.Tx{tx}) mempool.EXPECT().MarkDropped(tx.ID(), errTest) @@ -253,14 +258,14 @@ func TestBuilderBuildBlock(t *testing.T) { preferredBlock.EXPECT().Height().Return(preferredHeight) preferredBlock.EXPECT().Timestamp().Return(preferredTimestamp) - preferredState := state.NewMockChain(ctrl) + preferredState := statemock.NewChain(ctrl) preferredState.EXPECT().GetLastAccepted().Return(preferredID) preferredState.EXPECT().GetTimestamp().Return(preferredTimestamp) // tx1 and tx2 both consume [inputID]. // tx1 is added to the block first, so tx2 should be dropped. inputID := ids.GenerateTestID() - unsignedTx1 := txs.NewMockUnsignedTx(ctrl) + unsignedTx1 := txsmock.NewUnsignedTx(ctrl) unsignedTx1.EXPECT().Visit(gomock.Any()).Return(nil) // Pass semantic verification unsignedTx1.EXPECT().Visit(gomock.Any()).DoAndReturn( // Pass execution func(visitor txs.Visitor) error { @@ -277,7 +282,7 @@ func TestBuilderBuildBlock(t *testing.T) { tx1Bytes := []byte{1, 2, 3} tx1.SetBytes(nil, tx1Bytes) - unsignedTx2 := txs.NewMockUnsignedTx(ctrl) + unsignedTx2 := txsmock.NewUnsignedTx(ctrl) unsignedTx2.EXPECT().Visit(gomock.Any()).Return(nil) // Pass semantic verification unsignedTx2.EXPECT().Visit(gomock.Any()).DoAndReturn( // Pass execution func(visitor txs.Visitor) error { @@ -289,7 +294,7 @@ func TestBuilderBuildBlock(t *testing.T) { ) tx2 := &txs.Tx{Unsigned: unsignedTx2} - manager := blkexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().Preferred().Return(preferredID) manager.EXPECT().GetStatelessBlock(preferredID).Return(preferredBlock, nil) manager.EXPECT().GetState(preferredID).Return(preferredState, true) @@ -306,7 +311,7 @@ func TestBuilderBuildBlock(t *testing.T) { }, ) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Peek().Return(tx1, true) mempool.EXPECT().Remove([]*txs.Tx{tx1}) // Second loop iteration @@ -318,7 +323,7 @@ func TestBuilderBuildBlock(t *testing.T) { mempool.EXPECT().RequestBuildBlock() // To marshal the tx/block - codec := codec.NewMockManager(ctrl) + codec := codecmock.NewManager(ctrl) codec.EXPECT().Marshal(gomock.Any(), gomock.Any()).Return([]byte{1, 2, 3}, nil).AnyTimes() codec.EXPECT().Size(gomock.Any(), gomock.Any()).Return(2, nil).AnyTimes() @@ -351,11 +356,11 @@ func TestBuilderBuildBlock(t *testing.T) { clock := &mockable.Clock{} clock.Set(preferredTimestamp.Add(-2 * time.Second)) - preferredState := state.NewMockChain(ctrl) + preferredState := statemock.NewChain(ctrl) preferredState.EXPECT().GetLastAccepted().Return(preferredID) preferredState.EXPECT().GetTimestamp().Return(preferredTimestamp) - manager := blkexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().Preferred().Return(preferredID) manager.EXPECT().GetStatelessBlock(preferredID).Return(preferredBlock, nil) manager.EXPECT().GetState(preferredID).Return(preferredState, true) @@ -369,7 +374,7 @@ func TestBuilderBuildBlock(t *testing.T) { ) inputID := ids.GenerateTestID() - unsignedTx := txs.NewMockUnsignedTx(ctrl) + unsignedTx := txsmock.NewUnsignedTx(ctrl) unsignedTx.EXPECT().Visit(gomock.Any()).Return(nil) // Pass semantic verification unsignedTx.EXPECT().Visit(gomock.Any()).DoAndReturn( // Pass execution func(visitor txs.Visitor) error { @@ -382,7 +387,7 @@ func TestBuilderBuildBlock(t *testing.T) { unsignedTx.EXPECT().SetBytes(gomock.Any()).AnyTimes() tx := &txs.Tx{Unsigned: unsignedTx} - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Peek().Return(tx, true) mempool.EXPECT().Remove([]*txs.Tx{tx}) // Second loop iteration @@ -390,7 +395,7 @@ func TestBuilderBuildBlock(t *testing.T) { mempool.EXPECT().RequestBuildBlock() // To marshal the tx/block - codec := codec.NewMockManager(ctrl) + codec := codecmock.NewManager(ctrl) codec.EXPECT().Marshal(gomock.Any(), gomock.Any()).Return([]byte{1, 2, 3}, nil).AnyTimes() codec.EXPECT().Size(gomock.Any(), gomock.Any()).Return(2, nil).AnyTimes() @@ -425,11 +430,11 @@ func TestBuilderBuildBlock(t *testing.T) { clock := &mockable.Clock{} clock.Set(now) - preferredState := state.NewMockChain(ctrl) + preferredState := statemock.NewChain(ctrl) preferredState.EXPECT().GetLastAccepted().Return(preferredID) preferredState.EXPECT().GetTimestamp().Return(preferredTimestamp) - manager := blkexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().Preferred().Return(preferredID) manager.EXPECT().GetStatelessBlock(preferredID).Return(preferredBlock, nil) manager.EXPECT().GetState(preferredID).Return(preferredState, true) @@ -443,7 +448,7 @@ func TestBuilderBuildBlock(t *testing.T) { ) inputID := ids.GenerateTestID() - unsignedTx := txs.NewMockUnsignedTx(ctrl) + unsignedTx := txsmock.NewUnsignedTx(ctrl) unsignedTx.EXPECT().Visit(gomock.Any()).Return(nil) // Pass semantic verification unsignedTx.EXPECT().Visit(gomock.Any()).DoAndReturn( // Pass execution func(visitor txs.Visitor) error { @@ -456,7 +461,7 @@ func TestBuilderBuildBlock(t *testing.T) { unsignedTx.EXPECT().SetBytes(gomock.Any()).AnyTimes() tx := &txs.Tx{Unsigned: unsignedTx} - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Peek().Return(tx, true) mempool.EXPECT().Remove([]*txs.Tx{tx}) // Second loop iteration @@ -464,7 +469,7 @@ func TestBuilderBuildBlock(t *testing.T) { mempool.EXPECT().RequestBuildBlock() // To marshal the tx/block - codec := codec.NewMockManager(ctrl) + codec := codecmock.NewManager(ctrl) codec.EXPECT().Marshal(gomock.Any(), gomock.Any()).Return([]byte{1, 2, 3}, nil).AnyTimes() codec.EXPECT().Size(gomock.Any(), gomock.Any()).Return(2, nil).AnyTimes() diff --git a/vms/avm/block/executor/block_test.go b/vms/avm/block/executor/block_test.go index 0a3e8e42059a..5b8d17b66e7f 100644 --- a/vms/avm/block/executor/block_test.go +++ b/vms/avm/block/executor/block_test.go @@ -13,6 +13,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/chains/atomic" + "github.com/ava-labs/avalanchego/chains/atomic/atomicmock" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/upgrade/upgradetest" @@ -22,11 +23,12 @@ import ( "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/vms/avm/block" "github.com/ava-labs/avalanchego/vms/avm/config" - "github.com/ava-labs/avalanchego/vms/avm/metrics" - "github.com/ava-labs/avalanchego/vms/avm/state" + "github.com/ava-labs/avalanchego/vms/avm/metrics/metricsmock" + "github.com/ava-labs/avalanchego/vms/avm/state/statemock" "github.com/ava-labs/avalanchego/vms/avm/txs" "github.com/ava-labs/avalanchego/vms/avm/txs/executor" - "github.com/ava-labs/avalanchego/vms/avm/txs/mempool" + "github.com/ava-labs/avalanchego/vms/avm/txs/mempool/mempoolmock" + "github.com/ava-labs/avalanchego/vms/avm/txs/txsmock" ) func TestBlockVerify(t *testing.T) { @@ -118,21 +120,21 @@ func TestBlockVerify(t *testing.T) { mockBlock.EXPECT().ID().Return(ids.Empty).AnyTimes() mockBlock.EXPECT().MerkleRoot().Return(ids.Empty).AnyTimes() mockBlock.EXPECT().Timestamp().Return(time.Now()).AnyTimes() - mockUnsignedTx := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(errTest) errTx := &txs.Tx{ Unsigned: mockUnsignedTx, } mockBlock.EXPECT().Txs().Return([]*txs.Tx{errTx}).AnyTimes() - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().MarkDropped(errTx.ID(), errTest).Times(1) return &Block{ Block: mockBlock, manager: &manager{ backend: defaultTestBackend(false, nil), mempool: mempool, - metrics: metrics.NewMockMetrics(ctrl), + metrics: metricsmock.NewMetrics(ctrl), blkIDToState: map[ids.ID]*blockState{}, clk: &mockable.Clock{}, }, @@ -148,7 +150,7 @@ func TestBlockVerify(t *testing.T) { mockBlock.EXPECT().MerkleRoot().Return(ids.Empty).AnyTimes() mockBlock.EXPECT().Timestamp().Return(time.Now()).AnyTimes() - mockUnsignedTx := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil) tx := &txs.Tx{ Unsigned: mockUnsignedTx, @@ -158,7 +160,7 @@ func TestBlockVerify(t *testing.T) { parentID := ids.GenerateTestID() mockBlock.EXPECT().Parent().Return(parentID).AnyTimes() - mockState := state.NewMockState(ctrl) + mockState := statemock.NewState(ctrl) mockState.EXPECT().GetBlock(parentID).Return(nil, errTest) return &Block{ Block: mockBlock, @@ -182,7 +184,7 @@ func TestBlockVerify(t *testing.T) { blockHeight := uint64(1337) mockBlock.EXPECT().Height().Return(blockHeight).AnyTimes() - mockUnsignedTx := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil) tx := &txs.Tx{ Unsigned: mockUnsignedTx, @@ -192,7 +194,7 @@ func TestBlockVerify(t *testing.T) { parentID := ids.GenerateTestID() mockBlock.EXPECT().Parent().Return(parentID).AnyTimes() - mockState := state.NewMockState(ctrl) + mockState := statemock.NewState(ctrl) mockParentBlock := block.NewMockBlock(ctrl) mockParentBlock.EXPECT().Height().Return(blockHeight) // Should be blockHeight - 1 mockState.EXPECT().GetBlock(parentID).Return(mockParentBlock, nil) @@ -220,7 +222,7 @@ func TestBlockVerify(t *testing.T) { blockHeight := uint64(1337) mockBlock.EXPECT().Height().Return(blockHeight).AnyTimes() - mockUnsignedTx := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil) tx := &txs.Tx{ Unsigned: mockUnsignedTx, @@ -233,7 +235,7 @@ func TestBlockVerify(t *testing.T) { mockParentBlock := block.NewMockBlock(ctrl) mockParentBlock.EXPECT().Height().Return(blockHeight - 1) - mockParentState := state.NewMockDiff(ctrl) + mockParentState := statemock.NewDiff(ctrl) mockParentState.EXPECT().GetLastAccepted().Return(parentID) mockParentState.EXPECT().GetTimestamp().Return(blockTimestamp.Add(1)) @@ -265,7 +267,7 @@ func TestBlockVerify(t *testing.T) { blockHeight := uint64(1337) mockBlock.EXPECT().Height().Return(blockHeight).AnyTimes() - mockUnsignedTx := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Syntactic verification passes mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(errTest).Times(1) // Semantic verification fails tx := &txs.Tx{ @@ -279,18 +281,18 @@ func TestBlockVerify(t *testing.T) { mockParentBlock := block.NewMockBlock(ctrl) mockParentBlock.EXPECT().Height().Return(blockHeight - 1) - mockParentState := state.NewMockDiff(ctrl) + mockParentState := statemock.NewDiff(ctrl) mockParentState.EXPECT().GetLastAccepted().Return(parentID) mockParentState.EXPECT().GetTimestamp().Return(blockTimestamp) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().MarkDropped(tx.ID(), errTest).Times(1) return &Block{ Block: mockBlock, manager: &manager{ backend: defaultTestBackend(false, nil), mempool: mempool, - metrics: metrics.NewMockMetrics(ctrl), + metrics: metricsmock.NewMetrics(ctrl), blkIDToState: map[ids.ID]*blockState{ parentID: { onAcceptState: mockParentState, @@ -315,7 +317,7 @@ func TestBlockVerify(t *testing.T) { blockHeight := uint64(1337) mockBlock.EXPECT().Height().Return(blockHeight).AnyTimes() - mockUnsignedTx := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Syntactic verification passes mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Semantic verification fails mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(errTest).Times(1) // Execution fails @@ -330,17 +332,17 @@ func TestBlockVerify(t *testing.T) { mockParentBlock := block.NewMockBlock(ctrl) mockParentBlock.EXPECT().Height().Return(blockHeight - 1) - mockParentState := state.NewMockDiff(ctrl) + mockParentState := statemock.NewDiff(ctrl) mockParentState.EXPECT().GetLastAccepted().Return(parentID) mockParentState.EXPECT().GetTimestamp().Return(blockTimestamp) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().MarkDropped(tx.ID(), errTest).Times(1) return &Block{ Block: mockBlock, manager: &manager{ mempool: mempool, - metrics: metrics.NewMockMetrics(ctrl), + metrics: metricsmock.NewMetrics(ctrl), backend: defaultTestBackend(false, nil), blkIDToState: map[ids.ID]*blockState{ parentID: { @@ -368,7 +370,7 @@ func TestBlockVerify(t *testing.T) { // tx1 and tx2 both consume imported input [inputID] inputID := ids.GenerateTestID() - mockUnsignedTx1 := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx1 := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx1.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Syntactic verification passes mockUnsignedTx1.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Semantic verification fails mockUnsignedTx1.EXPECT().Visit(gomock.Any()).DoAndReturn( @@ -381,7 +383,7 @@ func TestBlockVerify(t *testing.T) { return nil }, ).Times(1) - mockUnsignedTx2 := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx2 := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx2.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Syntactic verification passes mockUnsignedTx2.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Semantic verification fails mockUnsignedTx2.EXPECT().Visit(gomock.Any()).DoAndReturn( @@ -408,17 +410,17 @@ func TestBlockVerify(t *testing.T) { mockParentBlock := block.NewMockBlock(ctrl) mockParentBlock.EXPECT().Height().Return(blockHeight - 1) - mockParentState := state.NewMockDiff(ctrl) + mockParentState := statemock.NewDiff(ctrl) mockParentState.EXPECT().GetLastAccepted().Return(parentID) mockParentState.EXPECT().GetTimestamp().Return(blockTimestamp) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().MarkDropped(tx2.ID(), ErrConflictingBlockTxs).Times(1) return &Block{ Block: mockBlock, manager: &manager{ mempool: mempool, - metrics: metrics.NewMockMetrics(ctrl), + metrics: metricsmock.NewMetrics(ctrl), backend: defaultTestBackend(false, nil), blkIDToState: map[ids.ID]*blockState{ parentID: { @@ -446,7 +448,7 @@ func TestBlockVerify(t *testing.T) { // tx1 and parent block both consume [inputID] inputID := ids.GenerateTestID() - mockUnsignedTx := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Syntactic verification passes mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Semantic verification fails mockUnsignedTx.EXPECT().Visit(gomock.Any()).DoAndReturn( @@ -470,7 +472,7 @@ func TestBlockVerify(t *testing.T) { mockParentBlock := block.NewMockBlock(ctrl) mockParentBlock.EXPECT().Height().Return(blockHeight - 1) - mockParentState := state.NewMockDiff(ctrl) + mockParentState := statemock.NewDiff(ctrl) mockParentState.EXPECT().GetLastAccepted().Return(parentID) mockParentState.EXPECT().GetTimestamp().Return(blockTimestamp) @@ -503,7 +505,7 @@ func TestBlockVerify(t *testing.T) { blockHeight := uint64(1337) mockBlock.EXPECT().Height().Return(blockHeight).AnyTimes() - mockUnsignedTx := txs.NewMockUnsignedTx(ctrl) + mockUnsignedTx := txsmock.NewUnsignedTx(ctrl) mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Syntactic verification passes mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Semantic verification fails mockUnsignedTx.EXPECT().Visit(gomock.Any()).Return(nil).Times(1) // Execution passes @@ -518,17 +520,17 @@ func TestBlockVerify(t *testing.T) { mockParentBlock := block.NewMockBlock(ctrl) mockParentBlock.EXPECT().Height().Return(blockHeight - 1) - mockParentState := state.NewMockDiff(ctrl) + mockParentState := statemock.NewDiff(ctrl) mockParentState.EXPECT().GetLastAccepted().Return(parentID) mockParentState.EXPECT().GetTimestamp().Return(blockTimestamp) - mockMempool := mempool.NewMockMempool(ctrl) + mockMempool := mempoolmock.NewMempool(ctrl) mockMempool.EXPECT().Remove([]*txs.Tx{tx}) return &Block{ Block: mockBlock, manager: &manager{ mempool: mockMempool, - metrics: metrics.NewMockMetrics(ctrl), + metrics: metricsmock.NewMetrics(ctrl), backend: defaultTestBackend(false, nil), blkIDToState: map[ids.ID]*blockState{ parentID: { @@ -595,14 +597,14 @@ func TestBlockAccept(t *testing.T) { mockBlock.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() mockBlock.EXPECT().Txs().Return([]*txs.Tx{}).AnyTimes() - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Remove(gomock.Any()).AnyTimes() return &Block{ Block: mockBlock, manager: &manager{ mempool: mempool, - metrics: metrics.NewMockMetrics(ctrl), + metrics: metricsmock.NewMetrics(ctrl), backend: defaultTestBackend(false, nil), blkIDToState: map[ids.ID]*blockState{}, }, @@ -618,14 +620,14 @@ func TestBlockAccept(t *testing.T) { mockBlock.EXPECT().ID().Return(blockID).AnyTimes() mockBlock.EXPECT().Txs().Return([]*txs.Tx{}).AnyTimes() - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Remove(gomock.Any()).AnyTimes() - mockManagerState := state.NewMockState(ctrl) + mockManagerState := statemock.NewState(ctrl) mockManagerState.EXPECT().CommitBatch().Return(nil, errTest) mockManagerState.EXPECT().Abort() - mockOnAcceptState := state.NewMockDiff(ctrl) + mockOnAcceptState := statemock.NewDiff(ctrl) mockOnAcceptState.EXPECT().Apply(mockManagerState) return &Block{ @@ -652,19 +654,19 @@ func TestBlockAccept(t *testing.T) { mockBlock.EXPECT().ID().Return(blockID).AnyTimes() mockBlock.EXPECT().Txs().Return([]*txs.Tx{}).AnyTimes() - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Remove(gomock.Any()).AnyTimes() - mockManagerState := state.NewMockState(ctrl) + mockManagerState := statemock.NewState(ctrl) // Note the returned batch is nil but not used // because we mock the call to shared memory mockManagerState.EXPECT().CommitBatch().Return(nil, nil) mockManagerState.EXPECT().Abort() - mockSharedMemory := atomic.NewMockSharedMemory(ctrl) + mockSharedMemory := atomicmock.NewSharedMemory(ctrl) mockSharedMemory.EXPECT().Apply(gomock.Any(), gomock.Any()).Return(errTest) - mockOnAcceptState := state.NewMockDiff(ctrl) + mockOnAcceptState := statemock.NewDiff(ctrl) mockOnAcceptState.EXPECT().Apply(mockManagerState) return &Block{ @@ -691,22 +693,22 @@ func TestBlockAccept(t *testing.T) { mockBlock.EXPECT().ID().Return(blockID).AnyTimes() mockBlock.EXPECT().Txs().Return([]*txs.Tx{}).AnyTimes() - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Remove(gomock.Any()).AnyTimes() - mockManagerState := state.NewMockState(ctrl) + mockManagerState := statemock.NewState(ctrl) // Note the returned batch is nil but not used // because we mock the call to shared memory mockManagerState.EXPECT().CommitBatch().Return(nil, nil) mockManagerState.EXPECT().Abort() - mockSharedMemory := atomic.NewMockSharedMemory(ctrl) + mockSharedMemory := atomicmock.NewSharedMemory(ctrl) mockSharedMemory.EXPECT().Apply(gomock.Any(), gomock.Any()).Return(nil) - mockOnAcceptState := state.NewMockDiff(ctrl) + mockOnAcceptState := statemock.NewDiff(ctrl) mockOnAcceptState.EXPECT().Apply(mockManagerState) - metrics := metrics.NewMockMetrics(ctrl) + metrics := metricsmock.NewMetrics(ctrl) metrics.EXPECT().MarkBlockAccepted(gomock.Any()).Return(errTest) return &Block{ @@ -736,23 +738,23 @@ func TestBlockAccept(t *testing.T) { mockBlock.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() mockBlock.EXPECT().Txs().Return([]*txs.Tx{}).AnyTimes() - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Remove(gomock.Any()).AnyTimes() - mockManagerState := state.NewMockState(ctrl) + mockManagerState := statemock.NewState(ctrl) // Note the returned batch is nil but not used // because we mock the call to shared memory mockManagerState.EXPECT().CommitBatch().Return(nil, nil) mockManagerState.EXPECT().Abort() mockManagerState.EXPECT().Checksums().Return(ids.Empty, ids.Empty) - mockSharedMemory := atomic.NewMockSharedMemory(ctrl) + mockSharedMemory := atomicmock.NewSharedMemory(ctrl) mockSharedMemory.EXPECT().Apply(gomock.Any(), gomock.Any()).Return(nil) - mockOnAcceptState := state.NewMockDiff(ctrl) + mockOnAcceptState := statemock.NewDiff(ctrl) mockOnAcceptState.EXPECT().Apply(mockManagerState) - metrics := metrics.NewMockMetrics(ctrl) + metrics := metricsmock.NewMetrics(ctrl) metrics.EXPECT().MarkBlockAccepted(gomock.Any()).Return(nil) return &Block{ @@ -805,20 +807,20 @@ func TestBlockReject(t *testing.T) { mockBlock.EXPECT().Height().Return(uint64(0)).AnyTimes() mockBlock.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() - unsignedValidTx := txs.NewMockUnsignedTx(ctrl) + unsignedValidTx := txsmock.NewUnsignedTx(ctrl) unsignedValidTx.EXPECT().SetBytes(gomock.Any()) unsignedValidTx.EXPECT().Visit(gomock.Any()).Return(nil).AnyTimes() // Passes verification and execution - unsignedSyntacticallyInvalidTx := txs.NewMockUnsignedTx(ctrl) + unsignedSyntacticallyInvalidTx := txsmock.NewUnsignedTx(ctrl) unsignedSyntacticallyInvalidTx.EXPECT().SetBytes(gomock.Any()) unsignedSyntacticallyInvalidTx.EXPECT().Visit(gomock.Any()).Return(errTest) // Fails syntactic verification - unsignedSemanticallyInvalidTx := txs.NewMockUnsignedTx(ctrl) + unsignedSemanticallyInvalidTx := txsmock.NewUnsignedTx(ctrl) unsignedSemanticallyInvalidTx.EXPECT().SetBytes(gomock.Any()) unsignedSemanticallyInvalidTx.EXPECT().Visit(gomock.Any()).Return(nil) // Passes syntactic verification unsignedSemanticallyInvalidTx.EXPECT().Visit(gomock.Any()).Return(errTest) // Fails semantic verification - unsignedExecutionFailsTx := txs.NewMockUnsignedTx(ctrl) + unsignedExecutionFailsTx := txsmock.NewUnsignedTx(ctrl) unsignedExecutionFailsTx.EXPECT().SetBytes(gomock.Any()) unsignedExecutionFailsTx.EXPECT().Visit(gomock.Any()).Return(nil) // Passes syntactic verification unsignedExecutionFailsTx.EXPECT().Visit(gomock.Any()).Return(nil) // Passes semantic verification @@ -841,12 +843,12 @@ func TestBlockReject(t *testing.T) { executionFailsTx, }) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Add(validTx).Return(nil) // Only add the one that passes verification mempool.EXPECT().RequestBuildBlock() lastAcceptedID := ids.GenerateTestID() - mockState := state.NewMockState(ctrl) + mockState := statemock.NewState(ctrl) mockState.EXPECT().GetLastAccepted().Return(lastAcceptedID).AnyTimes() mockState.EXPECT().GetTimestamp().Return(time.Now()).AnyTimes() @@ -855,7 +857,7 @@ func TestBlockReject(t *testing.T) { manager: &manager{ lastAccepted: lastAcceptedID, mempool: mempool, - metrics: metrics.NewMockMetrics(ctrl), + metrics: metricsmock.NewMetrics(ctrl), backend: defaultTestBackend(true, nil), state: mockState, blkIDToState: map[ids.ID]*blockState{ @@ -874,11 +876,11 @@ func TestBlockReject(t *testing.T) { mockBlock.EXPECT().Height().Return(uint64(0)).AnyTimes() mockBlock.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() - unsignedTx1 := txs.NewMockUnsignedTx(ctrl) + unsignedTx1 := txsmock.NewUnsignedTx(ctrl) unsignedTx1.EXPECT().SetBytes(gomock.Any()) unsignedTx1.EXPECT().Visit(gomock.Any()).Return(nil).AnyTimes() // Passes verification and execution - unsignedTx2 := txs.NewMockUnsignedTx(ctrl) + unsignedTx2 := txsmock.NewUnsignedTx(ctrl) unsignedTx2.EXPECT().SetBytes(gomock.Any()) unsignedTx2.EXPECT().Visit(gomock.Any()).Return(nil).AnyTimes() // Passes verification and execution @@ -893,13 +895,13 @@ func TestBlockReject(t *testing.T) { tx2, }) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Add(tx1).Return(nil) mempool.EXPECT().Add(tx2).Return(nil) mempool.EXPECT().RequestBuildBlock() lastAcceptedID := ids.GenerateTestID() - mockState := state.NewMockState(ctrl) + mockState := statemock.NewState(ctrl) mockState.EXPECT().GetLastAccepted().Return(lastAcceptedID).AnyTimes() mockState.EXPECT().GetTimestamp().Return(time.Now()).AnyTimes() @@ -908,7 +910,7 @@ func TestBlockReject(t *testing.T) { manager: &manager{ lastAccepted: lastAcceptedID, mempool: mempool, - metrics: metrics.NewMockMetrics(ctrl), + metrics: metricsmock.NewMetrics(ctrl), backend: defaultTestBackend(true, nil), state: mockState, blkIDToState: map[ids.ID]*blockState{ diff --git a/vms/avm/block/executor/mock_manager.go b/vms/avm/block/executor/executormock/manager.go similarity index 59% rename from vms/avm/block/executor/mock_manager.go rename to vms/avm/block/executor/executormock/manager.go index a882ec519fba..73633b34e2bf 100644 --- a/vms/avm/block/executor/mock_manager.go +++ b/vms/avm/block/executor/executormock/manager.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -source=vms/avm/block/executor/manager.go -destination=vms/avm/block/executor/mock_manager.go -package=executor -exclude_interfaces= +// mockgen -source=vms/avm/block/executor/manager.go -destination=vms/avm/block/executor/executormock/manager.go -package=executormock -exclude_interfaces= -mock_names=Manager=Manager // -// Package executor is a generated GoMock package. -package executor +// Package executormock is a generated GoMock package. +package executormock import ( reflect "reflect" @@ -21,31 +21,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockManager is a mock of Manager interface. -type MockManager struct { +// Manager is a mock of Manager interface. +type Manager struct { ctrl *gomock.Controller - recorder *MockManagerMockRecorder + recorder *ManagerMockRecorder } -// MockManagerMockRecorder is the mock recorder for MockManager. -type MockManagerMockRecorder struct { - mock *MockManager +// ManagerMockRecorder is the mock recorder for Manager. +type ManagerMockRecorder struct { + mock *Manager } -// NewMockManager creates a new mock instance. -func NewMockManager(ctrl *gomock.Controller) *MockManager { - mock := &MockManager{ctrl: ctrl} - mock.recorder = &MockManagerMockRecorder{mock} +// NewManager creates a new mock instance. +func NewManager(ctrl *gomock.Controller) *Manager { + mock := &Manager{ctrl: ctrl} + mock.recorder = &ManagerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockManager) EXPECT() *MockManagerMockRecorder { +func (m *Manager) EXPECT() *ManagerMockRecorder { return m.recorder } // GetBlock mocks base method. -func (m *MockManager) GetBlock(blkID ids.ID) (snowman.Block, error) { +func (m *Manager) GetBlock(blkID ids.ID) (snowman.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBlock", blkID) ret0, _ := ret[0].(snowman.Block) @@ -54,13 +54,13 @@ func (m *MockManager) GetBlock(blkID ids.ID) (snowman.Block, error) { } // GetBlock indicates an expected call of GetBlock. -func (mr *MockManagerMockRecorder) GetBlock(blkID any) *gomock.Call { +func (mr *ManagerMockRecorder) GetBlock(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*MockManager)(nil).GetBlock), blkID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*Manager)(nil).GetBlock), blkID) } // GetState mocks base method. -func (m *MockManager) GetState(blkID ids.ID) (state.Chain, bool) { +func (m *Manager) GetState(blkID ids.ID) (state.Chain, bool) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetState", blkID) ret0, _ := ret[0].(state.Chain) @@ -69,13 +69,13 @@ func (m *MockManager) GetState(blkID ids.ID) (state.Chain, bool) { } // GetState indicates an expected call of GetState. -func (mr *MockManagerMockRecorder) GetState(blkID any) *gomock.Call { +func (mr *ManagerMockRecorder) GetState(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetState", reflect.TypeOf((*MockManager)(nil).GetState), blkID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetState", reflect.TypeOf((*Manager)(nil).GetState), blkID) } // GetStatelessBlock mocks base method. -func (m *MockManager) GetStatelessBlock(blkID ids.ID) (block.Block, error) { +func (m *Manager) GetStatelessBlock(blkID ids.ID) (block.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStatelessBlock", blkID) ret0, _ := ret[0].(block.Block) @@ -84,13 +84,13 @@ func (m *MockManager) GetStatelessBlock(blkID ids.ID) (block.Block, error) { } // GetStatelessBlock indicates an expected call of GetStatelessBlock. -func (mr *MockManagerMockRecorder) GetStatelessBlock(blkID any) *gomock.Call { +func (mr *ManagerMockRecorder) GetStatelessBlock(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStatelessBlock", reflect.TypeOf((*MockManager)(nil).GetStatelessBlock), blkID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStatelessBlock", reflect.TypeOf((*Manager)(nil).GetStatelessBlock), blkID) } // LastAccepted mocks base method. -func (m *MockManager) LastAccepted() ids.ID { +func (m *Manager) LastAccepted() ids.ID { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LastAccepted") ret0, _ := ret[0].(ids.ID) @@ -98,13 +98,13 @@ func (m *MockManager) LastAccepted() ids.ID { } // LastAccepted indicates an expected call of LastAccepted. -func (mr *MockManagerMockRecorder) LastAccepted() *gomock.Call { +func (mr *ManagerMockRecorder) LastAccepted() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAccepted", reflect.TypeOf((*MockManager)(nil).LastAccepted)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAccepted", reflect.TypeOf((*Manager)(nil).LastAccepted)) } // NewBlock mocks base method. -func (m *MockManager) NewBlock(arg0 block.Block) snowman.Block { +func (m *Manager) NewBlock(arg0 block.Block) snowman.Block { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewBlock", arg0) ret0, _ := ret[0].(snowman.Block) @@ -112,13 +112,13 @@ func (m *MockManager) NewBlock(arg0 block.Block) snowman.Block { } // NewBlock indicates an expected call of NewBlock. -func (mr *MockManagerMockRecorder) NewBlock(arg0 any) *gomock.Call { +func (mr *ManagerMockRecorder) NewBlock(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewBlock", reflect.TypeOf((*MockManager)(nil).NewBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewBlock", reflect.TypeOf((*Manager)(nil).NewBlock), arg0) } // Preferred mocks base method. -func (m *MockManager) Preferred() ids.ID { +func (m *Manager) Preferred() ids.ID { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Preferred") ret0, _ := ret[0].(ids.ID) @@ -126,25 +126,25 @@ func (m *MockManager) Preferred() ids.ID { } // Preferred indicates an expected call of Preferred. -func (mr *MockManagerMockRecorder) Preferred() *gomock.Call { +func (mr *ManagerMockRecorder) Preferred() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Preferred", reflect.TypeOf((*MockManager)(nil).Preferred)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Preferred", reflect.TypeOf((*Manager)(nil).Preferred)) } // SetPreference mocks base method. -func (m *MockManager) SetPreference(blkID ids.ID) { +func (m *Manager) SetPreference(blkID ids.ID) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetPreference", blkID) } // SetPreference indicates an expected call of SetPreference. -func (mr *MockManagerMockRecorder) SetPreference(blkID any) *gomock.Call { +func (mr *ManagerMockRecorder) SetPreference(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPreference", reflect.TypeOf((*MockManager)(nil).SetPreference), blkID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPreference", reflect.TypeOf((*Manager)(nil).SetPreference), blkID) } // VerifyTx mocks base method. -func (m *MockManager) VerifyTx(tx *txs.Tx) error { +func (m *Manager) VerifyTx(tx *txs.Tx) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "VerifyTx", tx) ret0, _ := ret[0].(error) @@ -152,13 +152,13 @@ func (m *MockManager) VerifyTx(tx *txs.Tx) error { } // VerifyTx indicates an expected call of VerifyTx. -func (mr *MockManagerMockRecorder) VerifyTx(tx any) *gomock.Call { +func (mr *ManagerMockRecorder) VerifyTx(tx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyTx", reflect.TypeOf((*MockManager)(nil).VerifyTx), tx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyTx", reflect.TypeOf((*Manager)(nil).VerifyTx), tx) } // VerifyUniqueInputs mocks base method. -func (m *MockManager) VerifyUniqueInputs(blkID ids.ID, inputs set.Set[ids.ID]) error { +func (m *Manager) VerifyUniqueInputs(blkID ids.ID, inputs set.Set[ids.ID]) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "VerifyUniqueInputs", blkID, inputs) ret0, _ := ret[0].(error) @@ -166,7 +166,7 @@ func (m *MockManager) VerifyUniqueInputs(blkID ids.ID, inputs set.Set[ids.ID]) e } // VerifyUniqueInputs indicates an expected call of VerifyUniqueInputs. -func (mr *MockManagerMockRecorder) VerifyUniqueInputs(blkID, inputs any) *gomock.Call { +func (mr *ManagerMockRecorder) VerifyUniqueInputs(blkID, inputs any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyUniqueInputs", reflect.TypeOf((*MockManager)(nil).VerifyUniqueInputs), blkID, inputs) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyUniqueInputs", reflect.TypeOf((*Manager)(nil).VerifyUniqueInputs), blkID, inputs) } diff --git a/vms/avm/block/executor/manager_test.go b/vms/avm/block/executor/manager_test.go index 14484fcbb559..e6fc846bd8e4 100644 --- a/vms/avm/block/executor/manager_test.go +++ b/vms/avm/block/executor/manager_test.go @@ -14,8 +14,9 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/avm/block" - "github.com/ava-labs/avalanchego/vms/avm/state" + "github.com/ava-labs/avalanchego/vms/avm/state/statemock" "github.com/ava-labs/avalanchego/vms/avm/txs" + "github.com/ava-labs/avalanchego/vms/avm/txs/txsmock" ) var ( @@ -29,7 +30,7 @@ func TestManagerGetStatelessBlock(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) m := &manager{ state: state, blkIDToState: map[ids.ID]*blockState{}, @@ -71,7 +72,7 @@ func TestManagerGetState(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - s := state.NewMockState(ctrl) + s := statemock.NewState(ctrl) m := &manager{ state: s, blkIDToState: map[ids.ID]*blockState{}, @@ -80,7 +81,7 @@ func TestManagerGetState(t *testing.T) { // Case: Block is in memory { - diff := state.NewMockDiff(ctrl) + diff := statemock.NewDiff(ctrl) blkID := ids.GenerateTestID() m.blkIDToState[blkID] = &blockState{ onAcceptState: diff, @@ -130,7 +131,7 @@ func TestManagerVerifyTx(t *testing.T) { { name: "fails syntactic verification", txF: func(ctrl *gomock.Controller) *txs.Tx { - unsigned := txs.NewMockUnsignedTx(ctrl) + unsigned := txsmock.NewUnsignedTx(ctrl) unsigned.EXPECT().Visit(gomock.Any()).Return(errTestSyntacticVerifyFail) return &txs.Tx{ Unsigned: unsigned, @@ -146,7 +147,7 @@ func TestManagerVerifyTx(t *testing.T) { { name: "fails semantic verification", txF: func(ctrl *gomock.Controller) *txs.Tx { - unsigned := txs.NewMockUnsignedTx(ctrl) + unsigned := txsmock.NewUnsignedTx(ctrl) // Syntactic verification passes unsigned.EXPECT().Visit(gomock.Any()).Return(nil) // Semantic verification fails @@ -159,7 +160,7 @@ func TestManagerVerifyTx(t *testing.T) { lastAcceptedID := ids.GenerateTestID() // These values don't matter for this test - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetLastAccepted().Return(lastAcceptedID) state.EXPECT().GetTimestamp().Return(time.Time{}) @@ -174,7 +175,7 @@ func TestManagerVerifyTx(t *testing.T) { { name: "fails execution", txF: func(ctrl *gomock.Controller) *txs.Tx { - unsigned := txs.NewMockUnsignedTx(ctrl) + unsigned := txsmock.NewUnsignedTx(ctrl) // Syntactic verification passes unsigned.EXPECT().Visit(gomock.Any()).Return(nil) // Semantic verification passes @@ -189,7 +190,7 @@ func TestManagerVerifyTx(t *testing.T) { lastAcceptedID := ids.GenerateTestID() // These values don't matter for this test - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetLastAccepted().Return(lastAcceptedID) state.EXPECT().GetTimestamp().Return(time.Time{}) @@ -204,7 +205,7 @@ func TestManagerVerifyTx(t *testing.T) { { name: "happy path", txF: func(ctrl *gomock.Controller) *txs.Tx { - unsigned := txs.NewMockUnsignedTx(ctrl) + unsigned := txsmock.NewUnsignedTx(ctrl) // Syntactic verification passes unsigned.EXPECT().Visit(gomock.Any()).Return(nil) // Semantic verification passes @@ -219,7 +220,7 @@ func TestManagerVerifyTx(t *testing.T) { lastAcceptedID := ids.GenerateTestID() // These values don't matter for this test - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetLastAccepted().Return(lastAcceptedID) state.EXPECT().GetTimestamp().Return(time.Time{}) diff --git a/vms/avm/block/mock_block.go b/vms/avm/block/mock_block.go index bc332e88590c..d62403641a2f 100644 --- a/vms/avm/block/mock_block.go +++ b/vms/avm/block/mock_block.go @@ -1,9 +1,9 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/avm/block (interfaces: Block) +// Source: vms/avm/block/block.go // // Generated by this command: // -// mockgen -package=block -destination=vms/avm/block/mock_block.go github.com/ava-labs/avalanchego/vms/avm/block Block +// mockgen -source=vms/avm/block/block.go -destination=vms/avm/block/mock_block.go -package=block -exclude_interfaces= -mock_names=MockBlock=MockBlock // // Package block is a generated GoMock package. @@ -86,15 +86,15 @@ func (mr *MockBlockMockRecorder) ID() *gomock.Call { } // InitCtx mocks base method. -func (m *MockBlock) InitCtx(arg0 *snow.Context) { +func (m *MockBlock) InitCtx(ctx *snow.Context) { m.ctrl.T.Helper() - m.ctrl.Call(m, "InitCtx", arg0) + m.ctrl.Call(m, "InitCtx", ctx) } // InitCtx indicates an expected call of InitCtx. -func (mr *MockBlockMockRecorder) InitCtx(arg0 any) *gomock.Call { +func (mr *MockBlockMockRecorder) InitCtx(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockBlock)(nil).InitCtx), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockBlock)(nil).InitCtx), ctx) } // MerkleRoot mocks base method. @@ -154,15 +154,15 @@ func (mr *MockBlockMockRecorder) Txs() *gomock.Call { } // initialize mocks base method. -func (m *MockBlock) initialize(arg0 []byte, arg1 codec.Manager) error { +func (m *MockBlock) initialize(bytes []byte, cm codec.Manager) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "initialize", arg0, arg1) + ret := m.ctrl.Call(m, "initialize", bytes, cm) ret0, _ := ret[0].(error) return ret0 } // initialize indicates an expected call of initialize. -func (mr *MockBlockMockRecorder) initialize(arg0, arg1 any) *gomock.Call { +func (mr *MockBlockMockRecorder) initialize(bytes, cm any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "initialize", reflect.TypeOf((*MockBlock)(nil).initialize), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "initialize", reflect.TypeOf((*MockBlock)(nil).initialize), bytes, cm) } diff --git a/vms/avm/metrics/mock_metrics.go b/vms/avm/metrics/metricsmock/metrics.go similarity index 55% rename from vms/avm/metrics/mock_metrics.go rename to vms/avm/metrics/metricsmock/metrics.go index 2ae4a0786bf0..ceaea8c73056 100644 --- a/vms/avm/metrics/mock_metrics.go +++ b/vms/avm/metrics/metricsmock/metrics.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=metrics -destination=vms/avm/metrics/mock_metrics.go github.com/ava-labs/avalanchego/vms/avm/metrics Metrics +// mockgen -package=metricsmock -destination=vms/avm/metrics/metricsmock/metrics.go -mock_names=Metrics=Metrics github.com/ava-labs/avalanchego/vms/avm/metrics Metrics // -// Package metrics is a generated GoMock package. -package metrics +// Package metricsmock is a generated GoMock package. +package metricsmock import ( http "net/http" @@ -19,79 +19,79 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockMetrics is a mock of Metrics interface. -type MockMetrics struct { +// Metrics is a mock of Metrics interface. +type Metrics struct { ctrl *gomock.Controller - recorder *MockMetricsMockRecorder + recorder *MetricsMockRecorder } -// MockMetricsMockRecorder is the mock recorder for MockMetrics. -type MockMetricsMockRecorder struct { - mock *MockMetrics +// MetricsMockRecorder is the mock recorder for Metrics. +type MetricsMockRecorder struct { + mock *Metrics } -// NewMockMetrics creates a new mock instance. -func NewMockMetrics(ctrl *gomock.Controller) *MockMetrics { - mock := &MockMetrics{ctrl: ctrl} - mock.recorder = &MockMetricsMockRecorder{mock} +// NewMetrics creates a new mock instance. +func NewMetrics(ctrl *gomock.Controller) *Metrics { + mock := &Metrics{ctrl: ctrl} + mock.recorder = &MetricsMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockMetrics) EXPECT() *MockMetricsMockRecorder { +func (m *Metrics) EXPECT() *MetricsMockRecorder { return m.recorder } // AfterRequest mocks base method. -func (m *MockMetrics) AfterRequest(arg0 *rpc.RequestInfo) { +func (m *Metrics) AfterRequest(arg0 *rpc.RequestInfo) { m.ctrl.T.Helper() m.ctrl.Call(m, "AfterRequest", arg0) } // AfterRequest indicates an expected call of AfterRequest. -func (mr *MockMetricsMockRecorder) AfterRequest(arg0 any) *gomock.Call { +func (mr *MetricsMockRecorder) AfterRequest(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AfterRequest", reflect.TypeOf((*MockMetrics)(nil).AfterRequest), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AfterRequest", reflect.TypeOf((*Metrics)(nil).AfterRequest), arg0) } // IncTxRefreshHits mocks base method. -func (m *MockMetrics) IncTxRefreshHits() { +func (m *Metrics) IncTxRefreshHits() { m.ctrl.T.Helper() m.ctrl.Call(m, "IncTxRefreshHits") } // IncTxRefreshHits indicates an expected call of IncTxRefreshHits. -func (mr *MockMetricsMockRecorder) IncTxRefreshHits() *gomock.Call { +func (mr *MetricsMockRecorder) IncTxRefreshHits() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IncTxRefreshHits", reflect.TypeOf((*MockMetrics)(nil).IncTxRefreshHits)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IncTxRefreshHits", reflect.TypeOf((*Metrics)(nil).IncTxRefreshHits)) } // IncTxRefreshMisses mocks base method. -func (m *MockMetrics) IncTxRefreshMisses() { +func (m *Metrics) IncTxRefreshMisses() { m.ctrl.T.Helper() m.ctrl.Call(m, "IncTxRefreshMisses") } // IncTxRefreshMisses indicates an expected call of IncTxRefreshMisses. -func (mr *MockMetricsMockRecorder) IncTxRefreshMisses() *gomock.Call { +func (mr *MetricsMockRecorder) IncTxRefreshMisses() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IncTxRefreshMisses", reflect.TypeOf((*MockMetrics)(nil).IncTxRefreshMisses)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IncTxRefreshMisses", reflect.TypeOf((*Metrics)(nil).IncTxRefreshMisses)) } // IncTxRefreshes mocks base method. -func (m *MockMetrics) IncTxRefreshes() { +func (m *Metrics) IncTxRefreshes() { m.ctrl.T.Helper() m.ctrl.Call(m, "IncTxRefreshes") } // IncTxRefreshes indicates an expected call of IncTxRefreshes. -func (mr *MockMetricsMockRecorder) IncTxRefreshes() *gomock.Call { +func (mr *MetricsMockRecorder) IncTxRefreshes() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IncTxRefreshes", reflect.TypeOf((*MockMetrics)(nil).IncTxRefreshes)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IncTxRefreshes", reflect.TypeOf((*Metrics)(nil).IncTxRefreshes)) } // InterceptRequest mocks base method. -func (m *MockMetrics) InterceptRequest(arg0 *rpc.RequestInfo) *http.Request { +func (m *Metrics) InterceptRequest(arg0 *rpc.RequestInfo) *http.Request { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InterceptRequest", arg0) ret0, _ := ret[0].(*http.Request) @@ -99,13 +99,13 @@ func (m *MockMetrics) InterceptRequest(arg0 *rpc.RequestInfo) *http.Request { } // InterceptRequest indicates an expected call of InterceptRequest. -func (mr *MockMetricsMockRecorder) InterceptRequest(arg0 any) *gomock.Call { +func (mr *MetricsMockRecorder) InterceptRequest(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InterceptRequest", reflect.TypeOf((*MockMetrics)(nil).InterceptRequest), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InterceptRequest", reflect.TypeOf((*Metrics)(nil).InterceptRequest), arg0) } // MarkBlockAccepted mocks base method. -func (m *MockMetrics) MarkBlockAccepted(arg0 block.Block) error { +func (m *Metrics) MarkBlockAccepted(arg0 block.Block) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "MarkBlockAccepted", arg0) ret0, _ := ret[0].(error) @@ -113,13 +113,13 @@ func (m *MockMetrics) MarkBlockAccepted(arg0 block.Block) error { } // MarkBlockAccepted indicates an expected call of MarkBlockAccepted. -func (mr *MockMetricsMockRecorder) MarkBlockAccepted(arg0 any) *gomock.Call { +func (mr *MetricsMockRecorder) MarkBlockAccepted(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkBlockAccepted", reflect.TypeOf((*MockMetrics)(nil).MarkBlockAccepted), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkBlockAccepted", reflect.TypeOf((*Metrics)(nil).MarkBlockAccepted), arg0) } // MarkTxAccepted mocks base method. -func (m *MockMetrics) MarkTxAccepted(arg0 *txs.Tx) error { +func (m *Metrics) MarkTxAccepted(arg0 *txs.Tx) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "MarkTxAccepted", arg0) ret0, _ := ret[0].(error) @@ -127,7 +127,7 @@ func (m *MockMetrics) MarkTxAccepted(arg0 *txs.Tx) error { } // MarkTxAccepted indicates an expected call of MarkTxAccepted. -func (mr *MockMetricsMockRecorder) MarkTxAccepted(arg0 any) *gomock.Call { +func (mr *MetricsMockRecorder) MarkTxAccepted(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkTxAccepted", reflect.TypeOf((*MockMetrics)(nil).MarkTxAccepted), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkTxAccepted", reflect.TypeOf((*Metrics)(nil).MarkTxAccepted), arg0) } diff --git a/vms/avm/network/network_test.go b/vms/avm/network/network_test.go index 4d9b68f71f22..1e1065b1676f 100644 --- a/vms/avm/network/network_test.go +++ b/vms/avm/network/network_test.go @@ -15,12 +15,14 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/common/commonmock" "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/utils/logging" - "github.com/ava-labs/avalanchego/vms/avm/block/executor" + "github.com/ava-labs/avalanchego/vms/avm/block/executor/executormock" "github.com/ava-labs/avalanchego/vms/avm/fxs" "github.com/ava-labs/avalanchego/vms/avm/txs" + "github.com/ava-labs/avalanchego/vms/avm/txs/mempool/mempoolmock" "github.com/ava-labs/avalanchego/vms/nftfx" "github.com/ava-labs/avalanchego/vms/propertyfx" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -65,7 +67,7 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { { name: "mempool has transaction", mempoolFunc: func(ctrl *gomock.Controller) xmempool.Mempool { - mempool := xmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, true) return mempool }, @@ -74,7 +76,7 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { { name: "transaction marked as dropped in mempool", mempoolFunc: func(ctrl *gomock.Controller) xmempool.Mempool { - mempool := xmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, false) mempool.EXPECT().GetDropReason(gomock.Any()).Return(errTest) return mempool @@ -84,14 +86,14 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { { name: "transaction invalid", mempoolFunc: func(ctrl *gomock.Controller) xmempool.Mempool { - mempool := xmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, false) mempool.EXPECT().GetDropReason(gomock.Any()).Return(nil) mempool.EXPECT().MarkDropped(gomock.Any(), gomock.Any()) return mempool }, txVerifierFunc: func(ctrl *gomock.Controller) TxVerifier { - txVerifier := executor.NewMockManager(ctrl) + txVerifier := executormock.NewManager(ctrl) txVerifier.EXPECT().VerifyTx(gomock.Any()).Return(errTest) return txVerifier }, @@ -100,7 +102,7 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { { name: "can't add transaction to mempool", mempoolFunc: func(ctrl *gomock.Controller) xmempool.Mempool { - mempool := xmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, false) mempool.EXPECT().GetDropReason(gomock.Any()).Return(nil) mempool.EXPECT().Add(gomock.Any()).Return(errTest) @@ -108,7 +110,7 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { return mempool }, txVerifierFunc: func(ctrl *gomock.Controller) TxVerifier { - txVerifier := executor.NewMockManager(ctrl) + txVerifier := executormock.NewManager(ctrl) txVerifier.EXPECT().VerifyTx(gomock.Any()).Return(nil) return txVerifier }, @@ -117,7 +119,7 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { { name: "happy path", mempoolFunc: func(ctrl *gomock.Controller) xmempool.Mempool { - mempool := xmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, false) mempool.EXPECT().GetDropReason(gomock.Any()).Return(nil) mempool.EXPECT().Add(gomock.Any()).Return(nil) @@ -127,12 +129,12 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { return mempool }, txVerifierFunc: func(ctrl *gomock.Controller) TxVerifier { - txVerifier := executor.NewMockManager(ctrl) + txVerifier := executormock.NewManager(ctrl) txVerifier.EXPECT().VerifyTx(gomock.Any()).Return(nil) return txVerifier }, appSenderFunc: func(ctrl *gomock.Controller) common.AppSender { - appSender := common.NewMockSender(ctrl) + appSender := commonmock.NewSender(ctrl) appSender.EXPECT().SendAppGossip(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) return appSender }, @@ -155,21 +157,21 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { require.NoError(err) mempoolFunc := func(ctrl *gomock.Controller) xmempool.Mempool { - return xmempool.NewMockMempool(ctrl) + return mempoolmock.NewMempool(ctrl) } if tt.mempoolFunc != nil { mempoolFunc = tt.mempoolFunc } txVerifierFunc := func(ctrl *gomock.Controller) TxVerifier { - return executor.NewMockManager(ctrl) + return executormock.NewManager(ctrl) } if tt.txVerifierFunc != nil { txVerifierFunc = tt.txVerifierFunc } appSenderFunc := func(ctrl *gomock.Controller) common.AppSender { - return common.NewMockSender(ctrl) + return commonmock.NewSender(ctrl) } if tt.appSenderFunc != nil { appSenderFunc = tt.appSenderFunc @@ -215,7 +217,7 @@ func TestNetworkIssueTxFromRPCWithoutVerification(t *testing.T) { { name: "can't add transaction to mempool", mempoolFunc: func(ctrl *gomock.Controller) xmempool.Mempool { - mempool := xmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Add(gomock.Any()).Return(errTest) mempool.EXPECT().MarkDropped(gomock.Any(), gomock.Any()) return mempool @@ -225,7 +227,7 @@ func TestNetworkIssueTxFromRPCWithoutVerification(t *testing.T) { { name: "happy path", mempoolFunc: func(ctrl *gomock.Controller) xmempool.Mempool { - mempool := xmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, true).Times(2) mempool.EXPECT().Add(gomock.Any()).Return(nil) mempool.EXPECT().Len().Return(0) @@ -233,7 +235,7 @@ func TestNetworkIssueTxFromRPCWithoutVerification(t *testing.T) { return mempool }, appSenderFunc: func(ctrl *gomock.Controller) common.AppSender { - appSender := common.NewMockSender(ctrl) + appSender := commonmock.NewSender(ctrl) appSender.EXPECT().SendAppGossip(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) return appSender }, @@ -256,14 +258,14 @@ func TestNetworkIssueTxFromRPCWithoutVerification(t *testing.T) { require.NoError(err) mempoolFunc := func(ctrl *gomock.Controller) xmempool.Mempool { - return xmempool.NewMockMempool(ctrl) + return mempoolmock.NewMempool(ctrl) } if tt.mempoolFunc != nil { mempoolFunc = tt.mempoolFunc } appSenderFunc := func(ctrl *gomock.Controller) common.AppSender { - return common.NewMockSender(ctrl) + return commonmock.NewSender(ctrl) } if tt.appSenderFunc != nil { appSenderFunc = tt.appSenderFunc @@ -282,7 +284,7 @@ func TestNetworkIssueTxFromRPCWithoutVerification(t *testing.T) { }, }, parser, - executor.NewMockManager(ctrl), // Should never verify a tx + executormock.NewManager(ctrl), // Should never verify a tx mempoolFunc(ctrl), appSenderFunc(ctrl), prometheus.NewRegistry(), diff --git a/vms/avm/service_test.go b/vms/avm/service_test.go index b052552e4a13..6f44e469a75e 100644 --- a/vms/avm/service_test.go +++ b/vms/avm/service_test.go @@ -30,9 +30,9 @@ import ( "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/avm/block" - "github.com/ava-labs/avalanchego/vms/avm/block/executor" + "github.com/ava-labs/avalanchego/vms/avm/block/executor/executormock" "github.com/ava-labs/avalanchego/vms/avm/config" - "github.com/ava-labs/avalanchego/vms/avm/state" + "github.com/ava-labs/avalanchego/vms/avm/state/statemock" "github.com/ava-labs/avalanchego/vms/avm/txs" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/index" @@ -2899,7 +2899,7 @@ func TestServiceGetBlock(t *testing.T) { { name: "block not found", serviceAndExpectedBlockFunc: func(_ *testing.T, ctrl *gomock.Controller) (*Service, interface{}) { - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(nil, database.ErrNotFound) return &Service{ vm: &VM{ @@ -2920,7 +2920,7 @@ func TestServiceGetBlock(t *testing.T) { block.EXPECT().InitCtx(gomock.Any()) block.EXPECT().Txs().Return(nil) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -2944,7 +2944,7 @@ func TestServiceGetBlock(t *testing.T) { expected, err := formatting.Encode(formatting.Hex, blockBytes) require.NoError(t, err) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -2968,7 +2968,7 @@ func TestServiceGetBlock(t *testing.T) { expected, err := formatting.Encode(formatting.HexC, blockBytes) require.NoError(t, err) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -2992,7 +2992,7 @@ func TestServiceGetBlock(t *testing.T) { expected, err := formatting.Encode(formatting.HexNC, blockBytes) require.NoError(t, err) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -3065,10 +3065,10 @@ func TestServiceGetBlockByHeight(t *testing.T) { { name: "block height not found", serviceAndExpectedBlockFunc: func(_ *testing.T, ctrl *gomock.Controller) (*Service, interface{}) { - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(ids.Empty, database.ErrNotFound) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) return &Service{ vm: &VM{ state: state, @@ -3085,10 +3085,10 @@ func TestServiceGetBlockByHeight(t *testing.T) { { name: "block not found", serviceAndExpectedBlockFunc: func(_ *testing.T, ctrl *gomock.Controller) (*Service, interface{}) { - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(blockID, nil) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(nil, database.ErrNotFound) return &Service{ vm: &VM{ @@ -3110,10 +3110,10 @@ func TestServiceGetBlockByHeight(t *testing.T) { block.EXPECT().InitCtx(gomock.Any()) block.EXPECT().Txs().Return(nil) - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(blockID, nil) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -3135,13 +3135,13 @@ func TestServiceGetBlockByHeight(t *testing.T) { blockBytes := []byte("hi mom") block.EXPECT().Bytes().Return(blockBytes) - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(blockID, nil) expected, err := formatting.Encode(formatting.Hex, blockBytes) require.NoError(t, err) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -3163,13 +3163,13 @@ func TestServiceGetBlockByHeight(t *testing.T) { blockBytes := []byte("hi mom") block.EXPECT().Bytes().Return(blockBytes) - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(blockID, nil) expected, err := formatting.Encode(formatting.HexC, blockBytes) require.NoError(t, err) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -3191,13 +3191,13 @@ func TestServiceGetBlockByHeight(t *testing.T) { blockBytes := []byte("hi mom") block.EXPECT().Bytes().Return(blockBytes) - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(blockID, nil) expected, err := formatting.Encode(formatting.HexNC, blockBytes) require.NoError(t, err) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -3269,10 +3269,10 @@ func TestServiceGetHeight(t *testing.T) { { name: "block not found", serviceFunc: func(ctrl *gomock.Controller) *Service { - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetLastAccepted().Return(blockID) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(nil, database.ErrNotFound) return &Service{ vm: &VM{ @@ -3289,13 +3289,13 @@ func TestServiceGetHeight(t *testing.T) { { name: "happy path", serviceFunc: func(ctrl *gomock.Controller) *Service { - state := state.NewMockState(ctrl) + state := statemock.NewState(ctrl) state.EXPECT().GetLastAccepted().Return(blockID) block := block.NewMockBlock(ctrl) block.EXPECT().Height().Return(blockHeight) - manager := executor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ diff --git a/vms/avm/state/mock_state.go b/vms/avm/state/mock_state.go deleted file mode 100644 index 13ede9805d0b..000000000000 --- a/vms/avm/state/mock_state.go +++ /dev/null @@ -1,711 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/avm/state (interfaces: Chain,State,Diff) -// -// Generated by this command: -// -// mockgen -package=state -destination=vms/avm/state/mock_state.go github.com/ava-labs/avalanchego/vms/avm/state Chain,State,Diff -// - -// Package state is a generated GoMock package. -package state - -import ( - reflect "reflect" - time "time" - - database "github.com/ava-labs/avalanchego/database" - ids "github.com/ava-labs/avalanchego/ids" - block "github.com/ava-labs/avalanchego/vms/avm/block" - txs "github.com/ava-labs/avalanchego/vms/avm/txs" - avax "github.com/ava-labs/avalanchego/vms/components/avax" - gomock "go.uber.org/mock/gomock" -) - -// MockChain is a mock of Chain interface. -type MockChain struct { - ctrl *gomock.Controller - recorder *MockChainMockRecorder -} - -// MockChainMockRecorder is the mock recorder for MockChain. -type MockChainMockRecorder struct { - mock *MockChain -} - -// NewMockChain creates a new mock instance. -func NewMockChain(ctrl *gomock.Controller) *MockChain { - mock := &MockChain{ctrl: ctrl} - mock.recorder = &MockChainMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockChain) EXPECT() *MockChainMockRecorder { - return m.recorder -} - -// AddBlock mocks base method. -func (m *MockChain) AddBlock(arg0 block.Block) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddBlock", arg0) -} - -// AddBlock indicates an expected call of AddBlock. -func (mr *MockChainMockRecorder) AddBlock(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddBlock", reflect.TypeOf((*MockChain)(nil).AddBlock), arg0) -} - -// AddTx mocks base method. -func (m *MockChain) AddTx(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddTx", arg0) -} - -// AddTx indicates an expected call of AddTx. -func (mr *MockChainMockRecorder) AddTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockChain)(nil).AddTx), arg0) -} - -// AddUTXO mocks base method. -func (m *MockChain) AddUTXO(arg0 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddUTXO", arg0) -} - -// AddUTXO indicates an expected call of AddUTXO. -func (mr *MockChainMockRecorder) AddUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockChain)(nil).AddUTXO), arg0) -} - -// DeleteUTXO mocks base method. -func (m *MockChain) DeleteUTXO(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteUTXO", arg0) -} - -// DeleteUTXO indicates an expected call of DeleteUTXO. -func (mr *MockChainMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockChain)(nil).DeleteUTXO), arg0) -} - -// GetBlock mocks base method. -func (m *MockChain) GetBlock(arg0 ids.ID) (block.Block, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBlock", arg0) - ret0, _ := ret[0].(block.Block) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetBlock indicates an expected call of GetBlock. -func (mr *MockChainMockRecorder) GetBlock(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*MockChain)(nil).GetBlock), arg0) -} - -// GetBlockIDAtHeight mocks base method. -func (m *MockChain) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0) - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. -func (mr *MockChainMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*MockChain)(nil).GetBlockIDAtHeight), arg0) -} - -// GetLastAccepted mocks base method. -func (m *MockChain) GetLastAccepted() ids.ID { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetLastAccepted") - ret0, _ := ret[0].(ids.ID) - return ret0 -} - -// GetLastAccepted indicates an expected call of GetLastAccepted. -func (mr *MockChainMockRecorder) GetLastAccepted() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastAccepted", reflect.TypeOf((*MockChain)(nil).GetLastAccepted)) -} - -// GetTimestamp mocks base method. -func (m *MockChain) GetTimestamp() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTimestamp") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// GetTimestamp indicates an expected call of GetTimestamp. -func (mr *MockChainMockRecorder) GetTimestamp() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*MockChain)(nil).GetTimestamp)) -} - -// GetTx mocks base method. -func (m *MockChain) GetTx(arg0 ids.ID) (*txs.Tx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTx", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetTx indicates an expected call of GetTx. -func (mr *MockChainMockRecorder) GetTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockChain)(nil).GetTx), arg0) -} - -// GetUTXO mocks base method. -func (m *MockChain) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUTXO", arg0) - ret0, _ := ret[0].(*avax.UTXO) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUTXO indicates an expected call of GetUTXO. -func (mr *MockChainMockRecorder) GetUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockChain)(nil).GetUTXO), arg0) -} - -// SetLastAccepted mocks base method. -func (m *MockChain) SetLastAccepted(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetLastAccepted", arg0) -} - -// SetLastAccepted indicates an expected call of SetLastAccepted. -func (mr *MockChainMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*MockChain)(nil).SetLastAccepted), arg0) -} - -// SetTimestamp mocks base method. -func (m *MockChain) SetTimestamp(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimestamp", arg0) -} - -// SetTimestamp indicates an expected call of SetTimestamp. -func (mr *MockChainMockRecorder) SetTimestamp(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockChain)(nil).SetTimestamp), arg0) -} - -// MockState is a mock of State interface. -type MockState struct { - ctrl *gomock.Controller - recorder *MockStateMockRecorder -} - -// MockStateMockRecorder is the mock recorder for MockState. -type MockStateMockRecorder struct { - mock *MockState -} - -// NewMockState creates a new mock instance. -func NewMockState(ctrl *gomock.Controller) *MockState { - mock := &MockState{ctrl: ctrl} - mock.recorder = &MockStateMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockState) EXPECT() *MockStateMockRecorder { - return m.recorder -} - -// Abort mocks base method. -func (m *MockState) Abort() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "Abort") -} - -// Abort indicates an expected call of Abort. -func (mr *MockStateMockRecorder) Abort() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Abort", reflect.TypeOf((*MockState)(nil).Abort)) -} - -// AddBlock mocks base method. -func (m *MockState) AddBlock(arg0 block.Block) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddBlock", arg0) -} - -// AddBlock indicates an expected call of AddBlock. -func (mr *MockStateMockRecorder) AddBlock(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddBlock", reflect.TypeOf((*MockState)(nil).AddBlock), arg0) -} - -// AddTx mocks base method. -func (m *MockState) AddTx(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddTx", arg0) -} - -// AddTx indicates an expected call of AddTx. -func (mr *MockStateMockRecorder) AddTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockState)(nil).AddTx), arg0) -} - -// AddUTXO mocks base method. -func (m *MockState) AddUTXO(arg0 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddUTXO", arg0) -} - -// AddUTXO indicates an expected call of AddUTXO. -func (mr *MockStateMockRecorder) AddUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockState)(nil).AddUTXO), arg0) -} - -// Checksums mocks base method. -func (m *MockState) Checksums() (ids.ID, ids.ID) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Checksums") - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].(ids.ID) - return ret0, ret1 -} - -// Checksums indicates an expected call of Checksums. -func (mr *MockStateMockRecorder) Checksums() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Checksums", reflect.TypeOf((*MockState)(nil).Checksums)) -} - -// Close mocks base method. -func (m *MockState) Close() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Close") - ret0, _ := ret[0].(error) - return ret0 -} - -// Close indicates an expected call of Close. -func (mr *MockStateMockRecorder) Close() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockState)(nil).Close)) -} - -// Commit mocks base method. -func (m *MockState) Commit() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Commit") - ret0, _ := ret[0].(error) - return ret0 -} - -// Commit indicates an expected call of Commit. -func (mr *MockStateMockRecorder) Commit() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*MockState)(nil).Commit)) -} - -// CommitBatch mocks base method. -func (m *MockState) CommitBatch() (database.Batch, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CommitBatch") - ret0, _ := ret[0].(database.Batch) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CommitBatch indicates an expected call of CommitBatch. -func (mr *MockStateMockRecorder) CommitBatch() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitBatch", reflect.TypeOf((*MockState)(nil).CommitBatch)) -} - -// DeleteUTXO mocks base method. -func (m *MockState) DeleteUTXO(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteUTXO", arg0) -} - -// DeleteUTXO indicates an expected call of DeleteUTXO. -func (mr *MockStateMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockState)(nil).DeleteUTXO), arg0) -} - -// GetBlock mocks base method. -func (m *MockState) GetBlock(arg0 ids.ID) (block.Block, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBlock", arg0) - ret0, _ := ret[0].(block.Block) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetBlock indicates an expected call of GetBlock. -func (mr *MockStateMockRecorder) GetBlock(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*MockState)(nil).GetBlock), arg0) -} - -// GetBlockIDAtHeight mocks base method. -func (m *MockState) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0) - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. -func (mr *MockStateMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*MockState)(nil).GetBlockIDAtHeight), arg0) -} - -// GetLastAccepted mocks base method. -func (m *MockState) GetLastAccepted() ids.ID { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetLastAccepted") - ret0, _ := ret[0].(ids.ID) - return ret0 -} - -// GetLastAccepted indicates an expected call of GetLastAccepted. -func (mr *MockStateMockRecorder) GetLastAccepted() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastAccepted", reflect.TypeOf((*MockState)(nil).GetLastAccepted)) -} - -// GetTimestamp mocks base method. -func (m *MockState) GetTimestamp() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTimestamp") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// GetTimestamp indicates an expected call of GetTimestamp. -func (mr *MockStateMockRecorder) GetTimestamp() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*MockState)(nil).GetTimestamp)) -} - -// GetTx mocks base method. -func (m *MockState) GetTx(arg0 ids.ID) (*txs.Tx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTx", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetTx indicates an expected call of GetTx. -func (mr *MockStateMockRecorder) GetTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockState)(nil).GetTx), arg0) -} - -// GetUTXO mocks base method. -func (m *MockState) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUTXO", arg0) - ret0, _ := ret[0].(*avax.UTXO) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUTXO indicates an expected call of GetUTXO. -func (mr *MockStateMockRecorder) GetUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockState)(nil).GetUTXO), arg0) -} - -// InitializeChainState mocks base method. -func (m *MockState) InitializeChainState(arg0 ids.ID, arg1 time.Time) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "InitializeChainState", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// InitializeChainState indicates an expected call of InitializeChainState. -func (mr *MockStateMockRecorder) InitializeChainState(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitializeChainState", reflect.TypeOf((*MockState)(nil).InitializeChainState), arg0, arg1) -} - -// IsInitialized mocks base method. -func (m *MockState) IsInitialized() (bool, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "IsInitialized") - ret0, _ := ret[0].(bool) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// IsInitialized indicates an expected call of IsInitialized. -func (mr *MockStateMockRecorder) IsInitialized() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsInitialized", reflect.TypeOf((*MockState)(nil).IsInitialized)) -} - -// SetInitialized mocks base method. -func (m *MockState) SetInitialized() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetInitialized") - ret0, _ := ret[0].(error) - return ret0 -} - -// SetInitialized indicates an expected call of SetInitialized. -func (mr *MockStateMockRecorder) SetInitialized() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetInitialized", reflect.TypeOf((*MockState)(nil).SetInitialized)) -} - -// SetLastAccepted mocks base method. -func (m *MockState) SetLastAccepted(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetLastAccepted", arg0) -} - -// SetLastAccepted indicates an expected call of SetLastAccepted. -func (mr *MockStateMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*MockState)(nil).SetLastAccepted), arg0) -} - -// SetTimestamp mocks base method. -func (m *MockState) SetTimestamp(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimestamp", arg0) -} - -// SetTimestamp indicates an expected call of SetTimestamp. -func (mr *MockStateMockRecorder) SetTimestamp(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockState)(nil).SetTimestamp), arg0) -} - -// UTXOIDs mocks base method. -func (m *MockState) UTXOIDs(arg0 []byte, arg1 ids.ID, arg2 int) ([]ids.ID, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UTXOIDs", arg0, arg1, arg2) - ret0, _ := ret[0].([]ids.ID) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// UTXOIDs indicates an expected call of UTXOIDs. -func (mr *MockStateMockRecorder) UTXOIDs(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UTXOIDs", reflect.TypeOf((*MockState)(nil).UTXOIDs), arg0, arg1, arg2) -} - -// MockDiff is a mock of Diff interface. -type MockDiff struct { - ctrl *gomock.Controller - recorder *MockDiffMockRecorder -} - -// MockDiffMockRecorder is the mock recorder for MockDiff. -type MockDiffMockRecorder struct { - mock *MockDiff -} - -// NewMockDiff creates a new mock instance. -func NewMockDiff(ctrl *gomock.Controller) *MockDiff { - mock := &MockDiff{ctrl: ctrl} - mock.recorder = &MockDiffMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDiff) EXPECT() *MockDiffMockRecorder { - return m.recorder -} - -// AddBlock mocks base method. -func (m *MockDiff) AddBlock(arg0 block.Block) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddBlock", arg0) -} - -// AddBlock indicates an expected call of AddBlock. -func (mr *MockDiffMockRecorder) AddBlock(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddBlock", reflect.TypeOf((*MockDiff)(nil).AddBlock), arg0) -} - -// AddTx mocks base method. -func (m *MockDiff) AddTx(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddTx", arg0) -} - -// AddTx indicates an expected call of AddTx. -func (mr *MockDiffMockRecorder) AddTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockDiff)(nil).AddTx), arg0) -} - -// AddUTXO mocks base method. -func (m *MockDiff) AddUTXO(arg0 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddUTXO", arg0) -} - -// AddUTXO indicates an expected call of AddUTXO. -func (mr *MockDiffMockRecorder) AddUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockDiff)(nil).AddUTXO), arg0) -} - -// Apply mocks base method. -func (m *MockDiff) Apply(arg0 Chain) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "Apply", arg0) -} - -// Apply indicates an expected call of Apply. -func (mr *MockDiffMockRecorder) Apply(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockDiff)(nil).Apply), arg0) -} - -// DeleteUTXO mocks base method. -func (m *MockDiff) DeleteUTXO(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteUTXO", arg0) -} - -// DeleteUTXO indicates an expected call of DeleteUTXO. -func (mr *MockDiffMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockDiff)(nil).DeleteUTXO), arg0) -} - -// GetBlock mocks base method. -func (m *MockDiff) GetBlock(arg0 ids.ID) (block.Block, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBlock", arg0) - ret0, _ := ret[0].(block.Block) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetBlock indicates an expected call of GetBlock. -func (mr *MockDiffMockRecorder) GetBlock(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*MockDiff)(nil).GetBlock), arg0) -} - -// GetBlockIDAtHeight mocks base method. -func (m *MockDiff) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0) - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. -func (mr *MockDiffMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*MockDiff)(nil).GetBlockIDAtHeight), arg0) -} - -// GetLastAccepted mocks base method. -func (m *MockDiff) GetLastAccepted() ids.ID { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetLastAccepted") - ret0, _ := ret[0].(ids.ID) - return ret0 -} - -// GetLastAccepted indicates an expected call of GetLastAccepted. -func (mr *MockDiffMockRecorder) GetLastAccepted() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastAccepted", reflect.TypeOf((*MockDiff)(nil).GetLastAccepted)) -} - -// GetTimestamp mocks base method. -func (m *MockDiff) GetTimestamp() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTimestamp") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// GetTimestamp indicates an expected call of GetTimestamp. -func (mr *MockDiffMockRecorder) GetTimestamp() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*MockDiff)(nil).GetTimestamp)) -} - -// GetTx mocks base method. -func (m *MockDiff) GetTx(arg0 ids.ID) (*txs.Tx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTx", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetTx indicates an expected call of GetTx. -func (mr *MockDiffMockRecorder) GetTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockDiff)(nil).GetTx), arg0) -} - -// GetUTXO mocks base method. -func (m *MockDiff) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUTXO", arg0) - ret0, _ := ret[0].(*avax.UTXO) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUTXO indicates an expected call of GetUTXO. -func (mr *MockDiffMockRecorder) GetUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockDiff)(nil).GetUTXO), arg0) -} - -// SetLastAccepted mocks base method. -func (m *MockDiff) SetLastAccepted(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetLastAccepted", arg0) -} - -// SetLastAccepted indicates an expected call of SetLastAccepted. -func (mr *MockDiffMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*MockDiff)(nil).SetLastAccepted), arg0) -} - -// SetTimestamp mocks base method. -func (m *MockDiff) SetTimestamp(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimestamp", arg0) -} - -// SetTimestamp indicates an expected call of SetTimestamp. -func (mr *MockDiffMockRecorder) SetTimestamp(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockDiff)(nil).SetTimestamp), arg0) -} diff --git a/vms/avm/state/statemock/chain.go b/vms/avm/state/statemock/chain.go new file mode 100644 index 000000000000..3a802954d765 --- /dev/null +++ b/vms/avm/state/statemock/chain.go @@ -0,0 +1,204 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/avm/state (interfaces: Chain) +// +// Generated by this command: +// +// mockgen -package=statemock -destination=vms/avm/state/statemock/chain.go -mock_names=Chain=Chain github.com/ava-labs/avalanchego/vms/avm/state Chain +// + +// Package statemock is a generated GoMock package. +package statemock + +import ( + reflect "reflect" + time "time" + + ids "github.com/ava-labs/avalanchego/ids" + block "github.com/ava-labs/avalanchego/vms/avm/block" + txs "github.com/ava-labs/avalanchego/vms/avm/txs" + avax "github.com/ava-labs/avalanchego/vms/components/avax" + gomock "go.uber.org/mock/gomock" +) + +// Chain is a mock of Chain interface. +type Chain struct { + ctrl *gomock.Controller + recorder *ChainMockRecorder +} + +// ChainMockRecorder is the mock recorder for Chain. +type ChainMockRecorder struct { + mock *Chain +} + +// NewChain creates a new mock instance. +func NewChain(ctrl *gomock.Controller) *Chain { + mock := &Chain{ctrl: ctrl} + mock.recorder = &ChainMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Chain) EXPECT() *ChainMockRecorder { + return m.recorder +} + +// AddBlock mocks base method. +func (m *Chain) AddBlock(arg0 block.Block) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddBlock", arg0) +} + +// AddBlock indicates an expected call of AddBlock. +func (mr *ChainMockRecorder) AddBlock(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddBlock", reflect.TypeOf((*Chain)(nil).AddBlock), arg0) +} + +// AddTx mocks base method. +func (m *Chain) AddTx(arg0 *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddTx", arg0) +} + +// AddTx indicates an expected call of AddTx. +func (mr *ChainMockRecorder) AddTx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*Chain)(nil).AddTx), arg0) +} + +// AddUTXO mocks base method. +func (m *Chain) AddUTXO(arg0 *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddUTXO", arg0) +} + +// AddUTXO indicates an expected call of AddUTXO. +func (mr *ChainMockRecorder) AddUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*Chain)(nil).AddUTXO), arg0) +} + +// DeleteUTXO mocks base method. +func (m *Chain) DeleteUTXO(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteUTXO", arg0) +} + +// DeleteUTXO indicates an expected call of DeleteUTXO. +func (mr *ChainMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*Chain)(nil).DeleteUTXO), arg0) +} + +// GetBlock mocks base method. +func (m *Chain) GetBlock(arg0 ids.ID) (block.Block, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBlock", arg0) + ret0, _ := ret[0].(block.Block) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBlock indicates an expected call of GetBlock. +func (mr *ChainMockRecorder) GetBlock(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*Chain)(nil).GetBlock), arg0) +} + +// GetBlockIDAtHeight mocks base method. +func (m *Chain) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0) + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. +func (mr *ChainMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*Chain)(nil).GetBlockIDAtHeight), arg0) +} + +// GetLastAccepted mocks base method. +func (m *Chain) GetLastAccepted() ids.ID { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetLastAccepted") + ret0, _ := ret[0].(ids.ID) + return ret0 +} + +// GetLastAccepted indicates an expected call of GetLastAccepted. +func (mr *ChainMockRecorder) GetLastAccepted() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastAccepted", reflect.TypeOf((*Chain)(nil).GetLastAccepted)) +} + +// GetTimestamp mocks base method. +func (m *Chain) GetTimestamp() time.Time { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTimestamp") + ret0, _ := ret[0].(time.Time) + return ret0 +} + +// GetTimestamp indicates an expected call of GetTimestamp. +func (mr *ChainMockRecorder) GetTimestamp() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*Chain)(nil).GetTimestamp)) +} + +// GetTx mocks base method. +func (m *Chain) GetTx(arg0 ids.ID) (*txs.Tx, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTx", arg0) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetTx indicates an expected call of GetTx. +func (mr *ChainMockRecorder) GetTx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*Chain)(nil).GetTx), arg0) +} + +// GetUTXO mocks base method. +func (m *Chain) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUTXO", arg0) + ret0, _ := ret[0].(*avax.UTXO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUTXO indicates an expected call of GetUTXO. +func (mr *ChainMockRecorder) GetUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*Chain)(nil).GetUTXO), arg0) +} + +// SetLastAccepted mocks base method. +func (m *Chain) SetLastAccepted(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetLastAccepted", arg0) +} + +// SetLastAccepted indicates an expected call of SetLastAccepted. +func (mr *ChainMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*Chain)(nil).SetLastAccepted), arg0) +} + +// SetTimestamp mocks base method. +func (m *Chain) SetTimestamp(arg0 time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetTimestamp", arg0) +} + +// SetTimestamp indicates an expected call of SetTimestamp. +func (mr *ChainMockRecorder) SetTimestamp(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*Chain)(nil).SetTimestamp), arg0) +} diff --git a/vms/avm/state/statemock/diff.go b/vms/avm/state/statemock/diff.go new file mode 100644 index 000000000000..e41fc90825bb --- /dev/null +++ b/vms/avm/state/statemock/diff.go @@ -0,0 +1,217 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/avm/state (interfaces: Diff) +// +// Generated by this command: +// +// mockgen -package=statemock -destination=vms/avm/state/statemock/diff.go -mock_names=Diff=Diff github.com/ava-labs/avalanchego/vms/avm/state Diff +// + +// Package statemock is a generated GoMock package. +package statemock + +import ( + reflect "reflect" + time "time" + + ids "github.com/ava-labs/avalanchego/ids" + block "github.com/ava-labs/avalanchego/vms/avm/block" + state "github.com/ava-labs/avalanchego/vms/avm/state" + txs "github.com/ava-labs/avalanchego/vms/avm/txs" + avax "github.com/ava-labs/avalanchego/vms/components/avax" + gomock "go.uber.org/mock/gomock" +) + +// Diff is a mock of Diff interface. +type Diff struct { + ctrl *gomock.Controller + recorder *DiffMockRecorder +} + +// DiffMockRecorder is the mock recorder for Diff. +type DiffMockRecorder struct { + mock *Diff +} + +// NewDiff creates a new mock instance. +func NewDiff(ctrl *gomock.Controller) *Diff { + mock := &Diff{ctrl: ctrl} + mock.recorder = &DiffMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Diff) EXPECT() *DiffMockRecorder { + return m.recorder +} + +// AddBlock mocks base method. +func (m *Diff) AddBlock(arg0 block.Block) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddBlock", arg0) +} + +// AddBlock indicates an expected call of AddBlock. +func (mr *DiffMockRecorder) AddBlock(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddBlock", reflect.TypeOf((*Diff)(nil).AddBlock), arg0) +} + +// AddTx mocks base method. +func (m *Diff) AddTx(arg0 *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddTx", arg0) +} + +// AddTx indicates an expected call of AddTx. +func (mr *DiffMockRecorder) AddTx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*Diff)(nil).AddTx), arg0) +} + +// AddUTXO mocks base method. +func (m *Diff) AddUTXO(arg0 *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddUTXO", arg0) +} + +// AddUTXO indicates an expected call of AddUTXO. +func (mr *DiffMockRecorder) AddUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*Diff)(nil).AddUTXO), arg0) +} + +// Apply mocks base method. +func (m *Diff) Apply(arg0 state.Chain) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Apply", arg0) +} + +// Apply indicates an expected call of Apply. +func (mr *DiffMockRecorder) Apply(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*Diff)(nil).Apply), arg0) +} + +// DeleteUTXO mocks base method. +func (m *Diff) DeleteUTXO(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteUTXO", arg0) +} + +// DeleteUTXO indicates an expected call of DeleteUTXO. +func (mr *DiffMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*Diff)(nil).DeleteUTXO), arg0) +} + +// GetBlock mocks base method. +func (m *Diff) GetBlock(arg0 ids.ID) (block.Block, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBlock", arg0) + ret0, _ := ret[0].(block.Block) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBlock indicates an expected call of GetBlock. +func (mr *DiffMockRecorder) GetBlock(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*Diff)(nil).GetBlock), arg0) +} + +// GetBlockIDAtHeight mocks base method. +func (m *Diff) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0) + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. +func (mr *DiffMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*Diff)(nil).GetBlockIDAtHeight), arg0) +} + +// GetLastAccepted mocks base method. +func (m *Diff) GetLastAccepted() ids.ID { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetLastAccepted") + ret0, _ := ret[0].(ids.ID) + return ret0 +} + +// GetLastAccepted indicates an expected call of GetLastAccepted. +func (mr *DiffMockRecorder) GetLastAccepted() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastAccepted", reflect.TypeOf((*Diff)(nil).GetLastAccepted)) +} + +// GetTimestamp mocks base method. +func (m *Diff) GetTimestamp() time.Time { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTimestamp") + ret0, _ := ret[0].(time.Time) + return ret0 +} + +// GetTimestamp indicates an expected call of GetTimestamp. +func (mr *DiffMockRecorder) GetTimestamp() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*Diff)(nil).GetTimestamp)) +} + +// GetTx mocks base method. +func (m *Diff) GetTx(arg0 ids.ID) (*txs.Tx, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTx", arg0) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetTx indicates an expected call of GetTx. +func (mr *DiffMockRecorder) GetTx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*Diff)(nil).GetTx), arg0) +} + +// GetUTXO mocks base method. +func (m *Diff) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUTXO", arg0) + ret0, _ := ret[0].(*avax.UTXO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUTXO indicates an expected call of GetUTXO. +func (mr *DiffMockRecorder) GetUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*Diff)(nil).GetUTXO), arg0) +} + +// SetLastAccepted mocks base method. +func (m *Diff) SetLastAccepted(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetLastAccepted", arg0) +} + +// SetLastAccepted indicates an expected call of SetLastAccepted. +func (mr *DiffMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*Diff)(nil).SetLastAccepted), arg0) +} + +// SetTimestamp mocks base method. +func (m *Diff) SetTimestamp(arg0 time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetTimestamp", arg0) +} + +// SetTimestamp indicates an expected call of SetTimestamp. +func (mr *DiffMockRecorder) SetTimestamp(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*Diff)(nil).SetTimestamp), arg0) +} diff --git a/vms/avm/state/statemock/state.go b/vms/avm/state/statemock/state.go new file mode 100644 index 000000000000..1c78f8bda1ba --- /dev/null +++ b/vms/avm/state/statemock/state.go @@ -0,0 +1,333 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/avm/state (interfaces: State) +// +// Generated by this command: +// +// mockgen -package=statemock -destination=vms/avm/state/statemock/state.go -mock_names=State=State github.com/ava-labs/avalanchego/vms/avm/state State +// + +// Package statemock is a generated GoMock package. +package statemock + +import ( + reflect "reflect" + time "time" + + database "github.com/ava-labs/avalanchego/database" + ids "github.com/ava-labs/avalanchego/ids" + block "github.com/ava-labs/avalanchego/vms/avm/block" + txs "github.com/ava-labs/avalanchego/vms/avm/txs" + avax "github.com/ava-labs/avalanchego/vms/components/avax" + gomock "go.uber.org/mock/gomock" +) + +// State is a mock of State interface. +type State struct { + ctrl *gomock.Controller + recorder *StateMockRecorder +} + +// StateMockRecorder is the mock recorder for State. +type StateMockRecorder struct { + mock *State +} + +// NewState creates a new mock instance. +func NewState(ctrl *gomock.Controller) *State { + mock := &State{ctrl: ctrl} + mock.recorder = &StateMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *State) EXPECT() *StateMockRecorder { + return m.recorder +} + +// Abort mocks base method. +func (m *State) Abort() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Abort") +} + +// Abort indicates an expected call of Abort. +func (mr *StateMockRecorder) Abort() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Abort", reflect.TypeOf((*State)(nil).Abort)) +} + +// AddBlock mocks base method. +func (m *State) AddBlock(arg0 block.Block) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddBlock", arg0) +} + +// AddBlock indicates an expected call of AddBlock. +func (mr *StateMockRecorder) AddBlock(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddBlock", reflect.TypeOf((*State)(nil).AddBlock), arg0) +} + +// AddTx mocks base method. +func (m *State) AddTx(arg0 *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddTx", arg0) +} + +// AddTx indicates an expected call of AddTx. +func (mr *StateMockRecorder) AddTx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*State)(nil).AddTx), arg0) +} + +// AddUTXO mocks base method. +func (m *State) AddUTXO(arg0 *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddUTXO", arg0) +} + +// AddUTXO indicates an expected call of AddUTXO. +func (mr *StateMockRecorder) AddUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*State)(nil).AddUTXO), arg0) +} + +// Checksums mocks base method. +func (m *State) Checksums() (ids.ID, ids.ID) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Checksums") + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].(ids.ID) + return ret0, ret1 +} + +// Checksums indicates an expected call of Checksums. +func (mr *StateMockRecorder) Checksums() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Checksums", reflect.TypeOf((*State)(nil).Checksums)) +} + +// Close mocks base method. +func (m *State) Close() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Close") + ret0, _ := ret[0].(error) + return ret0 +} + +// Close indicates an expected call of Close. +func (mr *StateMockRecorder) Close() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*State)(nil).Close)) +} + +// Commit mocks base method. +func (m *State) Commit() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Commit") + ret0, _ := ret[0].(error) + return ret0 +} + +// Commit indicates an expected call of Commit. +func (mr *StateMockRecorder) Commit() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Commit", reflect.TypeOf((*State)(nil).Commit)) +} + +// CommitBatch mocks base method. +func (m *State) CommitBatch() (database.Batch, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CommitBatch") + ret0, _ := ret[0].(database.Batch) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CommitBatch indicates an expected call of CommitBatch. +func (mr *StateMockRecorder) CommitBatch() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CommitBatch", reflect.TypeOf((*State)(nil).CommitBatch)) +} + +// DeleteUTXO mocks base method. +func (m *State) DeleteUTXO(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteUTXO", arg0) +} + +// DeleteUTXO indicates an expected call of DeleteUTXO. +func (mr *StateMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*State)(nil).DeleteUTXO), arg0) +} + +// GetBlock mocks base method. +func (m *State) GetBlock(arg0 ids.ID) (block.Block, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBlock", arg0) + ret0, _ := ret[0].(block.Block) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBlock indicates an expected call of GetBlock. +func (mr *StateMockRecorder) GetBlock(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*State)(nil).GetBlock), arg0) +} + +// GetBlockIDAtHeight mocks base method. +func (m *State) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0) + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. +func (mr *StateMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*State)(nil).GetBlockIDAtHeight), arg0) +} + +// GetLastAccepted mocks base method. +func (m *State) GetLastAccepted() ids.ID { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetLastAccepted") + ret0, _ := ret[0].(ids.ID) + return ret0 +} + +// GetLastAccepted indicates an expected call of GetLastAccepted. +func (mr *StateMockRecorder) GetLastAccepted() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastAccepted", reflect.TypeOf((*State)(nil).GetLastAccepted)) +} + +// GetTimestamp mocks base method. +func (m *State) GetTimestamp() time.Time { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTimestamp") + ret0, _ := ret[0].(time.Time) + return ret0 +} + +// GetTimestamp indicates an expected call of GetTimestamp. +func (mr *StateMockRecorder) GetTimestamp() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*State)(nil).GetTimestamp)) +} + +// GetTx mocks base method. +func (m *State) GetTx(arg0 ids.ID) (*txs.Tx, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTx", arg0) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetTx indicates an expected call of GetTx. +func (mr *StateMockRecorder) GetTx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*State)(nil).GetTx), arg0) +} + +// GetUTXO mocks base method. +func (m *State) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUTXO", arg0) + ret0, _ := ret[0].(*avax.UTXO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUTXO indicates an expected call of GetUTXO. +func (mr *StateMockRecorder) GetUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*State)(nil).GetUTXO), arg0) +} + +// InitializeChainState mocks base method. +func (m *State) InitializeChainState(arg0 ids.ID, arg1 time.Time) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "InitializeChainState", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// InitializeChainState indicates an expected call of InitializeChainState. +func (mr *StateMockRecorder) InitializeChainState(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitializeChainState", reflect.TypeOf((*State)(nil).InitializeChainState), arg0, arg1) +} + +// IsInitialized mocks base method. +func (m *State) IsInitialized() (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsInitialized") + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// IsInitialized indicates an expected call of IsInitialized. +func (mr *StateMockRecorder) IsInitialized() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsInitialized", reflect.TypeOf((*State)(nil).IsInitialized)) +} + +// SetInitialized mocks base method. +func (m *State) SetInitialized() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetInitialized") + ret0, _ := ret[0].(error) + return ret0 +} + +// SetInitialized indicates an expected call of SetInitialized. +func (mr *StateMockRecorder) SetInitialized() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetInitialized", reflect.TypeOf((*State)(nil).SetInitialized)) +} + +// SetLastAccepted mocks base method. +func (m *State) SetLastAccepted(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetLastAccepted", arg0) +} + +// SetLastAccepted indicates an expected call of SetLastAccepted. +func (mr *StateMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*State)(nil).SetLastAccepted), arg0) +} + +// SetTimestamp mocks base method. +func (m *State) SetTimestamp(arg0 time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetTimestamp", arg0) +} + +// SetTimestamp indicates an expected call of SetTimestamp. +func (mr *StateMockRecorder) SetTimestamp(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*State)(nil).SetTimestamp), arg0) +} + +// UTXOIDs mocks base method. +func (m *State) UTXOIDs(arg0 []byte, arg1 ids.ID, arg2 int) ([]ids.ID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UTXOIDs", arg0, arg1, arg2) + ret0, _ := ret[0].([]ids.ID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UTXOIDs indicates an expected call of UTXOIDs. +func (mr *StateMockRecorder) UTXOIDs(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UTXOIDs", reflect.TypeOf((*State)(nil).UTXOIDs), arg0, arg1, arg2) +} diff --git a/vms/avm/txs/executor/semantic_verifier_test.go b/vms/avm/txs/executor/semantic_verifier_test.go index db89e1e5a5e9..e23fa50188da 100644 --- a/vms/avm/txs/executor/semantic_verifier_test.go +++ b/vms/avm/txs/executor/semantic_verifier_test.go @@ -16,13 +16,14 @@ import ( "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/snowtest" - "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/vms/avm/fxs" "github.com/ava-labs/avalanchego/vms/avm/state" + "github.com/ava-labs/avalanchego/vms/avm/state/statemock" "github.com/ava-labs/avalanchego/vms/avm/txs" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" @@ -124,7 +125,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "valid", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) @@ -148,7 +149,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "assetID mismatch", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) utxo := utxo utxo.Asset.ID = ids.GenerateTestID() @@ -174,7 +175,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "not allowed input feature extension", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil @@ -205,7 +206,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "invalid signature", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) @@ -229,7 +230,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "missing UTXO", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(nil, database.ErrNotFound) @@ -252,7 +253,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "invalid UTXO amount", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) output := output output.Amt-- @@ -282,7 +283,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "not allowed output feature extension", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil @@ -318,7 +319,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "unknown asset", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(nil, database.ErrNotFound) @@ -342,7 +343,7 @@ func TestSemanticVerifierBaseTx(t *testing.T) { { name: "not an asset", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) tx := txs.Tx{ Unsigned: &baseTx, @@ -485,7 +486,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "valid", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) @@ -509,7 +510,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "assetID mismatch", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) utxo := utxo utxo.Asset.ID = ids.GenerateTestID() @@ -535,7 +536,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "not allowed input feature extension", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil @@ -566,7 +567,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "invalid signature", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) @@ -590,7 +591,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "missing UTXO", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(nil, database.ErrNotFound) @@ -613,7 +614,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "invalid UTXO amount", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) output := output output.Amt-- @@ -643,7 +644,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "not allowed output feature extension", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil @@ -679,7 +680,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "unknown asset", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(nil, database.ErrNotFound) @@ -703,7 +704,7 @@ func TestSemanticVerifierExportTx(t *testing.T) { { name: "not an asset", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) tx := txs.Tx{ Unsigned: &baseTx, @@ -753,7 +754,7 @@ func TestSemanticVerifierExportTxDifferentSubnet(t *testing.T) { ctx := snowtest.Context(t, snowtest.XChainID) - validatorState := validators.NewMockState(ctrl) + validatorState := validatorsmock.NewState(ctrl) validatorState.EXPECT().GetSubnetID(gomock.Any(), ctx.CChainID).AnyTimes().Return(ids.GenerateTestID(), nil) ctx.ValidatorState = validatorState @@ -844,7 +845,7 @@ func TestSemanticVerifierExportTxDifferentSubnet(t *testing.T) { Unsigned: &unsignedCreateAssetTx, } - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil) state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil) @@ -995,7 +996,7 @@ func TestSemanticVerifierImportTx(t *testing.T) { { name: "valid", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil).AnyTimes() state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil).AnyTimes() return state @@ -1008,7 +1009,7 @@ func TestSemanticVerifierImportTx(t *testing.T) { { name: "not allowed input feature extension", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil createAssetTx := txs.Tx{ @@ -1026,7 +1027,7 @@ func TestSemanticVerifierImportTx(t *testing.T) { { name: "invalid signature", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil).AnyTimes() state.EXPECT().GetTx(asset.ID).Return(&createAssetTx, nil).AnyTimes() return state @@ -1048,7 +1049,7 @@ func TestSemanticVerifierImportTx(t *testing.T) { { name: "not allowed output feature extension", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) unsignedCreateAssetTx := unsignedCreateAssetTx unsignedCreateAssetTx.States = nil createAssetTx := txs.Tx{ @@ -1077,7 +1078,7 @@ func TestSemanticVerifierImportTx(t *testing.T) { { name: "unknown asset", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetUTXO(utxoID.InputID()).Return(&utxo, nil).AnyTimes() state.EXPECT().GetTx(asset.ID).Return(nil, database.ErrNotFound) return state @@ -1090,7 +1091,7 @@ func TestSemanticVerifierImportTx(t *testing.T) { { name: "not an asset", stateFunc: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) tx := txs.Tx{ Unsigned: &baseTx, } diff --git a/vms/avm/txs/mempool/mock_mempool.go b/vms/avm/txs/mempool/mempoolmock/mempool.go similarity index 57% rename from vms/avm/txs/mempool/mock_mempool.go rename to vms/avm/txs/mempool/mempoolmock/mempool.go index 69860c38d5d3..13bdf672db46 100644 --- a/vms/avm/txs/mempool/mock_mempool.go +++ b/vms/avm/txs/mempool/mempoolmock/mempool.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=mempool -destination=vms/avm/txs/mempool/mock_mempool.go github.com/ava-labs/avalanchego/vms/avm/txs/mempool Mempool +// mockgen -package=mempoolmock -destination=vms/avm/txs/mempool/mempoolmock/mempool.go -mock_names=Mempool=Mempool github.com/ava-labs/avalanchego/vms/avm/txs/mempool Mempool // -// Package mempool is a generated GoMock package. -package mempool +// Package mempoolmock is a generated GoMock package. +package mempoolmock import ( reflect "reflect" @@ -17,31 +17,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockMempool is a mock of Mempool interface. -type MockMempool struct { +// Mempool is a mock of Mempool interface. +type Mempool struct { ctrl *gomock.Controller - recorder *MockMempoolMockRecorder + recorder *MempoolMockRecorder } -// MockMempoolMockRecorder is the mock recorder for MockMempool. -type MockMempoolMockRecorder struct { - mock *MockMempool +// MempoolMockRecorder is the mock recorder for Mempool. +type MempoolMockRecorder struct { + mock *Mempool } -// NewMockMempool creates a new mock instance. -func NewMockMempool(ctrl *gomock.Controller) *MockMempool { - mock := &MockMempool{ctrl: ctrl} - mock.recorder = &MockMempoolMockRecorder{mock} +// NewMempool creates a new mock instance. +func NewMempool(ctrl *gomock.Controller) *Mempool { + mock := &Mempool{ctrl: ctrl} + mock.recorder = &MempoolMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockMempool) EXPECT() *MockMempoolMockRecorder { +func (m *Mempool) EXPECT() *MempoolMockRecorder { return m.recorder } // Add mocks base method. -func (m *MockMempool) Add(arg0 *txs.Tx) error { +func (m *Mempool) Add(arg0 *txs.Tx) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Add", arg0) ret0, _ := ret[0].(error) @@ -49,13 +49,13 @@ func (m *MockMempool) Add(arg0 *txs.Tx) error { } // Add indicates an expected call of Add. -func (mr *MockMempoolMockRecorder) Add(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) Add(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockMempool)(nil).Add), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*Mempool)(nil).Add), arg0) } // Get mocks base method. -func (m *MockMempool) Get(arg0 ids.ID) (*txs.Tx, bool) { +func (m *Mempool) Get(arg0 ids.ID) (*txs.Tx, bool) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", arg0) ret0, _ := ret[0].(*txs.Tx) @@ -64,13 +64,13 @@ func (m *MockMempool) Get(arg0 ids.ID) (*txs.Tx, bool) { } // Get indicates an expected call of Get. -func (mr *MockMempoolMockRecorder) Get(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) Get(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockMempool)(nil).Get), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*Mempool)(nil).Get), arg0) } // GetDropReason mocks base method. -func (m *MockMempool) GetDropReason(arg0 ids.ID) error { +func (m *Mempool) GetDropReason(arg0 ids.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetDropReason", arg0) ret0, _ := ret[0].(error) @@ -78,25 +78,25 @@ func (m *MockMempool) GetDropReason(arg0 ids.ID) error { } // GetDropReason indicates an expected call of GetDropReason. -func (mr *MockMempoolMockRecorder) GetDropReason(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) GetDropReason(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDropReason", reflect.TypeOf((*MockMempool)(nil).GetDropReason), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDropReason", reflect.TypeOf((*Mempool)(nil).GetDropReason), arg0) } // Iterate mocks base method. -func (m *MockMempool) Iterate(arg0 func(*txs.Tx) bool) { +func (m *Mempool) Iterate(arg0 func(*txs.Tx) bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "Iterate", arg0) } // Iterate indicates an expected call of Iterate. -func (mr *MockMempoolMockRecorder) Iterate(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) Iterate(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Iterate", reflect.TypeOf((*MockMempool)(nil).Iterate), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Iterate", reflect.TypeOf((*Mempool)(nil).Iterate), arg0) } // Len mocks base method. -func (m *MockMempool) Len() int { +func (m *Mempool) Len() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Len") ret0, _ := ret[0].(int) @@ -104,25 +104,25 @@ func (m *MockMempool) Len() int { } // Len indicates an expected call of Len. -func (mr *MockMempoolMockRecorder) Len() *gomock.Call { +func (mr *MempoolMockRecorder) Len() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Len", reflect.TypeOf((*MockMempool)(nil).Len)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Len", reflect.TypeOf((*Mempool)(nil).Len)) } // MarkDropped mocks base method. -func (m *MockMempool) MarkDropped(arg0 ids.ID, arg1 error) { +func (m *Mempool) MarkDropped(arg0 ids.ID, arg1 error) { m.ctrl.T.Helper() m.ctrl.Call(m, "MarkDropped", arg0, arg1) } // MarkDropped indicates an expected call of MarkDropped. -func (mr *MockMempoolMockRecorder) MarkDropped(arg0, arg1 any) *gomock.Call { +func (mr *MempoolMockRecorder) MarkDropped(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkDropped", reflect.TypeOf((*MockMempool)(nil).MarkDropped), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkDropped", reflect.TypeOf((*Mempool)(nil).MarkDropped), arg0, arg1) } // Peek mocks base method. -func (m *MockMempool) Peek() (*txs.Tx, bool) { +func (m *Mempool) Peek() (*txs.Tx, bool) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Peek") ret0, _ := ret[0].(*txs.Tx) @@ -131,13 +131,13 @@ func (m *MockMempool) Peek() (*txs.Tx, bool) { } // Peek indicates an expected call of Peek. -func (mr *MockMempoolMockRecorder) Peek() *gomock.Call { +func (mr *MempoolMockRecorder) Peek() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Peek", reflect.TypeOf((*MockMempool)(nil).Peek)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Peek", reflect.TypeOf((*Mempool)(nil).Peek)) } // Remove mocks base method. -func (m *MockMempool) Remove(arg0 ...*txs.Tx) { +func (m *Mempool) Remove(arg0 ...*txs.Tx) { m.ctrl.T.Helper() varargs := []any{} for _, a := range arg0 { @@ -147,19 +147,19 @@ func (m *MockMempool) Remove(arg0 ...*txs.Tx) { } // Remove indicates an expected call of Remove. -func (mr *MockMempoolMockRecorder) Remove(arg0 ...any) *gomock.Call { +func (mr *MempoolMockRecorder) Remove(arg0 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockMempool)(nil).Remove), arg0...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*Mempool)(nil).Remove), arg0...) } // RequestBuildBlock mocks base method. -func (m *MockMempool) RequestBuildBlock() { +func (m *Mempool) RequestBuildBlock() { m.ctrl.T.Helper() m.ctrl.Call(m, "RequestBuildBlock") } // RequestBuildBlock indicates an expected call of RequestBuildBlock. -func (mr *MockMempoolMockRecorder) RequestBuildBlock() *gomock.Call { +func (mr *MempoolMockRecorder) RequestBuildBlock() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RequestBuildBlock", reflect.TypeOf((*MockMempool)(nil).RequestBuildBlock)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RequestBuildBlock", reflect.TypeOf((*Mempool)(nil).RequestBuildBlock)) } diff --git a/vms/avm/txs/mock_unsigned_tx.go b/vms/avm/txs/txsmock/tx.go similarity index 55% rename from vms/avm/txs/mock_unsigned_tx.go rename to vms/avm/txs/txsmock/tx.go index 25bc9d501a16..73ec73472921 100644 --- a/vms/avm/txs/mock_unsigned_tx.go +++ b/vms/avm/txs/txsmock/tx.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -source=vms/avm/txs/tx.go -destination=vms/avm/txs/mock_unsigned_tx.go -package=txs -exclude_interfaces= +// mockgen -source=vms/avm/txs/tx.go -destination=vms/avm/txs/txsmock/tx.go -package=txsmock -exclude_interfaces= -mock_names=UnsignedTx=UnsignedTx // -// Package txs is a generated GoMock package. -package txs +// Package txsmock is a generated GoMock package. +package txsmock import ( reflect "reflect" @@ -15,35 +15,36 @@ import ( ids "github.com/ava-labs/avalanchego/ids" snow "github.com/ava-labs/avalanchego/snow" set "github.com/ava-labs/avalanchego/utils/set" + txs "github.com/ava-labs/avalanchego/vms/avm/txs" avax "github.com/ava-labs/avalanchego/vms/components/avax" gomock "go.uber.org/mock/gomock" ) -// MockUnsignedTx is a mock of UnsignedTx interface. -type MockUnsignedTx struct { +// UnsignedTx is a mock of UnsignedTx interface. +type UnsignedTx struct { ctrl *gomock.Controller - recorder *MockUnsignedTxMockRecorder + recorder *UnsignedTxMockRecorder } -// MockUnsignedTxMockRecorder is the mock recorder for MockUnsignedTx. -type MockUnsignedTxMockRecorder struct { - mock *MockUnsignedTx +// UnsignedTxMockRecorder is the mock recorder for UnsignedTx. +type UnsignedTxMockRecorder struct { + mock *UnsignedTx } -// NewMockUnsignedTx creates a new mock instance. -func NewMockUnsignedTx(ctrl *gomock.Controller) *MockUnsignedTx { - mock := &MockUnsignedTx{ctrl: ctrl} - mock.recorder = &MockUnsignedTxMockRecorder{mock} +// NewUnsignedTx creates a new mock instance. +func NewUnsignedTx(ctrl *gomock.Controller) *UnsignedTx { + mock := &UnsignedTx{ctrl: ctrl} + mock.recorder = &UnsignedTxMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockUnsignedTx) EXPECT() *MockUnsignedTxMockRecorder { +func (m *UnsignedTx) EXPECT() *UnsignedTxMockRecorder { return m.recorder } // Bytes mocks base method. -func (m *MockUnsignedTx) Bytes() []byte { +func (m *UnsignedTx) Bytes() []byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bytes") ret0, _ := ret[0].([]byte) @@ -51,25 +52,25 @@ func (m *MockUnsignedTx) Bytes() []byte { } // Bytes indicates an expected call of Bytes. -func (mr *MockUnsignedTxMockRecorder) Bytes() *gomock.Call { +func (mr *UnsignedTxMockRecorder) Bytes() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*MockUnsignedTx)(nil).Bytes)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*UnsignedTx)(nil).Bytes)) } // InitCtx mocks base method. -func (m *MockUnsignedTx) InitCtx(ctx *snow.Context) { +func (m *UnsignedTx) InitCtx(ctx *snow.Context) { m.ctrl.T.Helper() m.ctrl.Call(m, "InitCtx", ctx) } // InitCtx indicates an expected call of InitCtx. -func (mr *MockUnsignedTxMockRecorder) InitCtx(ctx any) *gomock.Call { +func (mr *UnsignedTxMockRecorder) InitCtx(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockUnsignedTx)(nil).InitCtx), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*UnsignedTx)(nil).InitCtx), ctx) } // InputIDs mocks base method. -func (m *MockUnsignedTx) InputIDs() set.Set[ids.ID] { +func (m *UnsignedTx) InputIDs() set.Set[ids.ID] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InputIDs") ret0, _ := ret[0].(set.Set[ids.ID]) @@ -77,13 +78,13 @@ func (m *MockUnsignedTx) InputIDs() set.Set[ids.ID] { } // InputIDs indicates an expected call of InputIDs. -func (mr *MockUnsignedTxMockRecorder) InputIDs() *gomock.Call { +func (mr *UnsignedTxMockRecorder) InputIDs() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InputIDs", reflect.TypeOf((*MockUnsignedTx)(nil).InputIDs)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InputIDs", reflect.TypeOf((*UnsignedTx)(nil).InputIDs)) } // InputUTXOs mocks base method. -func (m *MockUnsignedTx) InputUTXOs() []*avax.UTXOID { +func (m *UnsignedTx) InputUTXOs() []*avax.UTXOID { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InputUTXOs") ret0, _ := ret[0].([]*avax.UTXOID) @@ -91,13 +92,13 @@ func (m *MockUnsignedTx) InputUTXOs() []*avax.UTXOID { } // InputUTXOs indicates an expected call of InputUTXOs. -func (mr *MockUnsignedTxMockRecorder) InputUTXOs() *gomock.Call { +func (mr *UnsignedTxMockRecorder) InputUTXOs() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InputUTXOs", reflect.TypeOf((*MockUnsignedTx)(nil).InputUTXOs)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InputUTXOs", reflect.TypeOf((*UnsignedTx)(nil).InputUTXOs)) } // NumCredentials mocks base method. -func (m *MockUnsignedTx) NumCredentials() int { +func (m *UnsignedTx) NumCredentials() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NumCredentials") ret0, _ := ret[0].(int) @@ -105,25 +106,25 @@ func (m *MockUnsignedTx) NumCredentials() int { } // NumCredentials indicates an expected call of NumCredentials. -func (mr *MockUnsignedTxMockRecorder) NumCredentials() *gomock.Call { +func (mr *UnsignedTxMockRecorder) NumCredentials() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NumCredentials", reflect.TypeOf((*MockUnsignedTx)(nil).NumCredentials)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NumCredentials", reflect.TypeOf((*UnsignedTx)(nil).NumCredentials)) } // SetBytes mocks base method. -func (m *MockUnsignedTx) SetBytes(unsignedBytes []byte) { +func (m *UnsignedTx) SetBytes(unsignedBytes []byte) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetBytes", unsignedBytes) } // SetBytes indicates an expected call of SetBytes. -func (mr *MockUnsignedTxMockRecorder) SetBytes(unsignedBytes any) *gomock.Call { +func (mr *UnsignedTxMockRecorder) SetBytes(unsignedBytes any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetBytes", reflect.TypeOf((*MockUnsignedTx)(nil).SetBytes), unsignedBytes) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetBytes", reflect.TypeOf((*UnsignedTx)(nil).SetBytes), unsignedBytes) } // Visit mocks base method. -func (m *MockUnsignedTx) Visit(visitor Visitor) error { +func (m *UnsignedTx) Visit(visitor txs.Visitor) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Visit", visitor) ret0, _ := ret[0].(error) @@ -131,7 +132,7 @@ func (m *MockUnsignedTx) Visit(visitor Visitor) error { } // Visit indicates an expected call of Visit. -func (mr *MockUnsignedTxMockRecorder) Visit(visitor any) *gomock.Call { +func (mr *UnsignedTxMockRecorder) Visit(visitor any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Visit", reflect.TypeOf((*MockUnsignedTx)(nil).Visit), visitor) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Visit", reflect.TypeOf((*UnsignedTx)(nil).Visit), visitor) } diff --git a/vms/components/avax/mock_transferable_in.go b/vms/components/avax/avaxmock/transferable_in.go similarity index 50% rename from vms/components/avax/mock_transferable_in.go rename to vms/components/avax/avaxmock/transferable_in.go index b4db89933057..4221e1830648 100644 --- a/vms/components/avax/mock_transferable_in.go +++ b/vms/components/avax/avaxmock/transferable_in.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=avax -destination=vms/components/avax/mock_transferable_in.go github.com/ava-labs/avalanchego/vms/components/avax TransferableIn +// mockgen -package=avaxmock -destination=vms/components/avax/avaxmock/transferable_in.go -mock_names=TransferableIn=TransferableIn github.com/ava-labs/avalanchego/vms/components/avax TransferableIn // -// Package avax is a generated GoMock package. -package avax +// Package avaxmock is a generated GoMock package. +package avaxmock import ( reflect "reflect" @@ -16,31 +16,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockTransferableIn is a mock of TransferableIn interface. -type MockTransferableIn struct { +// TransferableIn is a mock of TransferableIn interface. +type TransferableIn struct { ctrl *gomock.Controller - recorder *MockTransferableInMockRecorder + recorder *TransferableInMockRecorder } -// MockTransferableInMockRecorder is the mock recorder for MockTransferableIn. -type MockTransferableInMockRecorder struct { - mock *MockTransferableIn +// TransferableInMockRecorder is the mock recorder for TransferableIn. +type TransferableInMockRecorder struct { + mock *TransferableIn } -// NewMockTransferableIn creates a new mock instance. -func NewMockTransferableIn(ctrl *gomock.Controller) *MockTransferableIn { - mock := &MockTransferableIn{ctrl: ctrl} - mock.recorder = &MockTransferableInMockRecorder{mock} +// NewTransferableIn creates a new mock instance. +func NewTransferableIn(ctrl *gomock.Controller) *TransferableIn { + mock := &TransferableIn{ctrl: ctrl} + mock.recorder = &TransferableInMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTransferableIn) EXPECT() *MockTransferableInMockRecorder { +func (m *TransferableIn) EXPECT() *TransferableInMockRecorder { return m.recorder } // Amount mocks base method. -func (m *MockTransferableIn) Amount() uint64 { +func (m *TransferableIn) Amount() uint64 { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Amount") ret0, _ := ret[0].(uint64) @@ -48,13 +48,13 @@ func (m *MockTransferableIn) Amount() uint64 { } // Amount indicates an expected call of Amount. -func (mr *MockTransferableInMockRecorder) Amount() *gomock.Call { +func (mr *TransferableInMockRecorder) Amount() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Amount", reflect.TypeOf((*MockTransferableIn)(nil).Amount)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Amount", reflect.TypeOf((*TransferableIn)(nil).Amount)) } // Cost mocks base method. -func (m *MockTransferableIn) Cost() (uint64, error) { +func (m *TransferableIn) Cost() (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Cost") ret0, _ := ret[0].(uint64) @@ -63,25 +63,25 @@ func (m *MockTransferableIn) Cost() (uint64, error) { } // Cost indicates an expected call of Cost. -func (mr *MockTransferableInMockRecorder) Cost() *gomock.Call { +func (mr *TransferableInMockRecorder) Cost() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cost", reflect.TypeOf((*MockTransferableIn)(nil).Cost)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cost", reflect.TypeOf((*TransferableIn)(nil).Cost)) } // InitCtx mocks base method. -func (m *MockTransferableIn) InitCtx(arg0 *snow.Context) { +func (m *TransferableIn) InitCtx(arg0 *snow.Context) { m.ctrl.T.Helper() m.ctrl.Call(m, "InitCtx", arg0) } // InitCtx indicates an expected call of InitCtx. -func (mr *MockTransferableInMockRecorder) InitCtx(arg0 any) *gomock.Call { +func (mr *TransferableInMockRecorder) InitCtx(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockTransferableIn)(nil).InitCtx), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*TransferableIn)(nil).InitCtx), arg0) } // Verify mocks base method. -func (m *MockTransferableIn) Verify() error { +func (m *TransferableIn) Verify() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Verify") ret0, _ := ret[0].(error) @@ -89,7 +89,7 @@ func (m *MockTransferableIn) Verify() error { } // Verify indicates an expected call of Verify. -func (mr *MockTransferableInMockRecorder) Verify() *gomock.Call { +func (mr *TransferableInMockRecorder) Verify() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockTransferableIn)(nil).Verify)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*TransferableIn)(nil).Verify)) } diff --git a/vms/components/avax/avaxmock/transferable_out.go b/vms/components/avax/avaxmock/transferable_out.go new file mode 100644 index 000000000000..ce30c4d0ddc7 --- /dev/null +++ b/vms/components/avax/avaxmock/transferable_out.go @@ -0,0 +1,95 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/components/avax (interfaces: TransferableOut) +// +// Generated by this command: +// +// mockgen -package=avaxmock -destination=vms/components/avax/avaxmock/transferable_out.go -mock_names=TransferableOut=TransferableOut github.com/ava-labs/avalanchego/vms/components/avax TransferableOut +// + +// Package avaxmock is a generated GoMock package. +package avaxmock + +import ( + reflect "reflect" + + snow "github.com/ava-labs/avalanchego/snow" + verify "github.com/ava-labs/avalanchego/vms/components/verify" + gomock "go.uber.org/mock/gomock" +) + +// TransferableOut is a mock of TransferableOut interface. +type TransferableOut struct { + verify.IsState + + ctrl *gomock.Controller + recorder *TransferableOutMockRecorder +} + +// TransferableOutMockRecorder is the mock recorder for TransferableOut. +type TransferableOutMockRecorder struct { + mock *TransferableOut +} + +// NewTransferableOut creates a new mock instance. +func NewTransferableOut(ctrl *gomock.Controller) *TransferableOut { + mock := &TransferableOut{ctrl: ctrl} + mock.recorder = &TransferableOutMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *TransferableOut) EXPECT() *TransferableOutMockRecorder { + return m.recorder +} + +// Amount mocks base method. +func (m *TransferableOut) Amount() uint64 { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Amount") + ret0, _ := ret[0].(uint64) + return ret0 +} + +// Amount indicates an expected call of Amount. +func (mr *TransferableOutMockRecorder) Amount() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Amount", reflect.TypeOf((*TransferableOut)(nil).Amount)) +} + +// InitCtx mocks base method. +func (m *TransferableOut) InitCtx(arg0 *snow.Context) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "InitCtx", arg0) +} + +// InitCtx indicates an expected call of InitCtx. +func (mr *TransferableOutMockRecorder) InitCtx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*TransferableOut)(nil).InitCtx), arg0) +} + +// Verify mocks base method. +func (m *TransferableOut) Verify() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Verify") + ret0, _ := ret[0].(error) + return ret0 +} + +// Verify indicates an expected call of Verify. +func (mr *TransferableOutMockRecorder) Verify() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*TransferableOut)(nil).Verify)) +} + +// isState mocks base method. +func (m *TransferableOut) isState() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "isState") +} + +// isState indicates an expected call of isState. +func (mr *TransferableOutMockRecorder) isState() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "isState", reflect.TypeOf((*TransferableOut)(nil).isState)) +} diff --git a/vms/components/avax/mock_transferable_out.go b/vms/components/avax/mock_transferable_out.go deleted file mode 100644 index b518b86302d4..000000000000 --- a/vms/components/avax/mock_transferable_out.go +++ /dev/null @@ -1,95 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/components/avax (interfaces: TransferableOut) -// -// Generated by this command: -// -// mockgen -package=avax -destination=vms/components/avax/mock_transferable_out.go github.com/ava-labs/avalanchego/vms/components/avax TransferableOut -// - -// Package avax is a generated GoMock package. -package avax - -import ( - reflect "reflect" - - snow "github.com/ava-labs/avalanchego/snow" - verify "github.com/ava-labs/avalanchego/vms/components/verify" - gomock "go.uber.org/mock/gomock" -) - -// MockTransferableOut is a mock of TransferableOut interface. -type MockTransferableOut struct { - verify.IsState - - ctrl *gomock.Controller - recorder *MockTransferableOutMockRecorder -} - -// MockTransferableOutMockRecorder is the mock recorder for MockTransferableOut. -type MockTransferableOutMockRecorder struct { - mock *MockTransferableOut -} - -// NewMockTransferableOut creates a new mock instance. -func NewMockTransferableOut(ctrl *gomock.Controller) *MockTransferableOut { - mock := &MockTransferableOut{ctrl: ctrl} - mock.recorder = &MockTransferableOutMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockTransferableOut) EXPECT() *MockTransferableOutMockRecorder { - return m.recorder -} - -// Amount mocks base method. -func (m *MockTransferableOut) Amount() uint64 { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Amount") - ret0, _ := ret[0].(uint64) - return ret0 -} - -// Amount indicates an expected call of Amount. -func (mr *MockTransferableOutMockRecorder) Amount() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Amount", reflect.TypeOf((*MockTransferableOut)(nil).Amount)) -} - -// InitCtx mocks base method. -func (m *MockTransferableOut) InitCtx(arg0 *snow.Context) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "InitCtx", arg0) -} - -// InitCtx indicates an expected call of InitCtx. -func (mr *MockTransferableOutMockRecorder) InitCtx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockTransferableOut)(nil).InitCtx), arg0) -} - -// Verify mocks base method. -func (m *MockTransferableOut) Verify() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Verify") - ret0, _ := ret[0].(error) - return ret0 -} - -// Verify indicates an expected call of Verify. -func (mr *MockTransferableOutMockRecorder) Verify() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockTransferableOut)(nil).Verify)) -} - -// isState mocks base method. -func (m *MockTransferableOut) isState() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "isState") -} - -// isState indicates an expected call of isState. -func (mr *MockTransferableOutMockRecorder) isState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "isState", reflect.TypeOf((*MockTransferableOut)(nil).isState)) -} diff --git a/vms/components/verify/mock_verifiable.go b/vms/components/verify/mock_verifiable.go deleted file mode 100644 index fe0e5770500c..000000000000 --- a/vms/components/verify/mock_verifiable.go +++ /dev/null @@ -1,53 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/components/verify (interfaces: Verifiable) -// -// Generated by this command: -// -// mockgen -package=verify -destination=vms/components/verify/mock_verifiable.go github.com/ava-labs/avalanchego/vms/components/verify Verifiable -// - -// Package verify is a generated GoMock package. -package verify - -import ( - reflect "reflect" - - gomock "go.uber.org/mock/gomock" -) - -// MockVerifiable is a mock of Verifiable interface. -type MockVerifiable struct { - ctrl *gomock.Controller - recorder *MockVerifiableMockRecorder -} - -// MockVerifiableMockRecorder is the mock recorder for MockVerifiable. -type MockVerifiableMockRecorder struct { - mock *MockVerifiable -} - -// NewMockVerifiable creates a new mock instance. -func NewMockVerifiable(ctrl *gomock.Controller) *MockVerifiable { - mock := &MockVerifiable{ctrl: ctrl} - mock.recorder = &MockVerifiableMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVerifiable) EXPECT() *MockVerifiableMockRecorder { - return m.recorder -} - -// Verify mocks base method. -func (m *MockVerifiable) Verify() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Verify") - ret0, _ := ret[0].(error) - return ret0 -} - -// Verify indicates an expected call of Verify. -func (mr *MockVerifiableMockRecorder) Verify() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockVerifiable)(nil).Verify)) -} diff --git a/vms/components/verify/subnet_test.go b/vms/components/verify/subnet_test.go index 1e5bee1cd5ab..b58c209268a6 100644 --- a/vms/components/verify/subnet_test.go +++ b/vms/components/verify/subnet_test.go @@ -13,7 +13,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" ) var errMissing = errors.New("missing") @@ -33,7 +33,7 @@ func TestSameSubnet(t *testing.T) { { name: "same chain", ctxF: func(ctrl *gomock.Controller) *snow.Context { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) return &snow.Context{ SubnetID: subnetID0, ChainID: chainID0, @@ -46,7 +46,7 @@ func TestSameSubnet(t *testing.T) { { name: "unknown chain", ctxF: func(ctrl *gomock.Controller) *snow.Context { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), chainID1).Return(subnetID1, errMissing) return &snow.Context{ SubnetID: subnetID0, @@ -60,7 +60,7 @@ func TestSameSubnet(t *testing.T) { { name: "wrong subnet", ctxF: func(ctrl *gomock.Controller) *snow.Context { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), chainID1).Return(subnetID1, nil) return &snow.Context{ SubnetID: subnetID0, @@ -74,7 +74,7 @@ func TestSameSubnet(t *testing.T) { { name: "same subnet", ctxF: func(ctrl *gomock.Controller) *snow.Context { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), chainID1).Return(subnetID0, nil) return &snow.Context{ SubnetID: subnetID0, diff --git a/vms/components/verify/verifymock/verifiable.go b/vms/components/verify/verifymock/verifiable.go new file mode 100644 index 000000000000..53663316573c --- /dev/null +++ b/vms/components/verify/verifymock/verifiable.go @@ -0,0 +1,53 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/components/verify (interfaces: Verifiable) +// +// Generated by this command: +// +// mockgen -package=verifymock -destination=vms/components/verify/verifymock/verifiable.go -mock_names=Verifiable=Verifiable github.com/ava-labs/avalanchego/vms/components/verify Verifiable +// + +// Package verifymock is a generated GoMock package. +package verifymock + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// Verifiable is a mock of Verifiable interface. +type Verifiable struct { + ctrl *gomock.Controller + recorder *VerifiableMockRecorder +} + +// VerifiableMockRecorder is the mock recorder for Verifiable. +type VerifiableMockRecorder struct { + mock *Verifiable +} + +// NewVerifiable creates a new mock instance. +func NewVerifiable(ctrl *gomock.Controller) *Verifiable { + mock := &Verifiable{ctrl: ctrl} + mock.recorder = &VerifiableMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Verifiable) EXPECT() *VerifiableMockRecorder { + return m.recorder +} + +// Verify mocks base method. +func (m *Verifiable) Verify() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Verify") + ret0, _ := ret[0].(error) + return ret0 +} + +// Verify indicates an expected call of Verify. +func (mr *VerifiableMockRecorder) Verify() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*Verifiable)(nil).Verify)) +} diff --git a/vms/mock_manager.go b/vms/mock_manager.go deleted file mode 100644 index cea232ba2a7d..000000000000 --- a/vms/mock_manager.go +++ /dev/null @@ -1,224 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms (interfaces: Factory,Manager) -// -// Generated by this command: -// -// mockgen -package=vms -destination=vms/mock_manager.go github.com/ava-labs/avalanchego/vms Factory,Manager -// - -// Package vms is a generated GoMock package. -package vms - -import ( - context "context" - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - logging "github.com/ava-labs/avalanchego/utils/logging" - gomock "go.uber.org/mock/gomock" -) - -// MockFactory is a mock of Factory interface. -type MockFactory struct { - ctrl *gomock.Controller - recorder *MockFactoryMockRecorder -} - -// MockFactoryMockRecorder is the mock recorder for MockFactory. -type MockFactoryMockRecorder struct { - mock *MockFactory -} - -// NewMockFactory creates a new mock instance. -func NewMockFactory(ctrl *gomock.Controller) *MockFactory { - mock := &MockFactory{ctrl: ctrl} - mock.recorder = &MockFactoryMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFactory) EXPECT() *MockFactoryMockRecorder { - return m.recorder -} - -// New mocks base method. -func (m *MockFactory) New(arg0 logging.Logger) (any, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "New", arg0) - ret0, _ := ret[0].(any) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// New indicates an expected call of New. -func (mr *MockFactoryMockRecorder) New(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "New", reflect.TypeOf((*MockFactory)(nil).New), arg0) -} - -// MockManager is a mock of Manager interface. -type MockManager struct { - ctrl *gomock.Controller - recorder *MockManagerMockRecorder -} - -// MockManagerMockRecorder is the mock recorder for MockManager. -type MockManagerMockRecorder struct { - mock *MockManager -} - -// NewMockManager creates a new mock instance. -func NewMockManager(ctrl *gomock.Controller) *MockManager { - mock := &MockManager{ctrl: ctrl} - mock.recorder = &MockManagerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockManager) EXPECT() *MockManagerMockRecorder { - return m.recorder -} - -// Alias mocks base method. -func (m *MockManager) Alias(arg0 ids.ID, arg1 string) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Alias", arg0, arg1) - ret0, _ := ret[0].(error) - return ret0 -} - -// Alias indicates an expected call of Alias. -func (mr *MockManagerMockRecorder) Alias(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Alias", reflect.TypeOf((*MockManager)(nil).Alias), arg0, arg1) -} - -// Aliases mocks base method. -func (m *MockManager) Aliases(arg0 ids.ID) ([]string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Aliases", arg0) - ret0, _ := ret[0].([]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Aliases indicates an expected call of Aliases. -func (mr *MockManagerMockRecorder) Aliases(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Aliases", reflect.TypeOf((*MockManager)(nil).Aliases), arg0) -} - -// GetFactory mocks base method. -func (m *MockManager) GetFactory(arg0 ids.ID) (Factory, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetFactory", arg0) - ret0, _ := ret[0].(Factory) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetFactory indicates an expected call of GetFactory. -func (mr *MockManagerMockRecorder) GetFactory(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFactory", reflect.TypeOf((*MockManager)(nil).GetFactory), arg0) -} - -// ListFactories mocks base method. -func (m *MockManager) ListFactories() ([]ids.ID, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ListFactories") - ret0, _ := ret[0].([]ids.ID) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ListFactories indicates an expected call of ListFactories. -func (mr *MockManagerMockRecorder) ListFactories() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFactories", reflect.TypeOf((*MockManager)(nil).ListFactories)) -} - -// Lookup mocks base method. -func (m *MockManager) Lookup(arg0 string) (ids.ID, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Lookup", arg0) - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Lookup indicates an expected call of Lookup. -func (mr *MockManagerMockRecorder) Lookup(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Lookup", reflect.TypeOf((*MockManager)(nil).Lookup), arg0) -} - -// PrimaryAlias mocks base method. -func (m *MockManager) PrimaryAlias(arg0 ids.ID) (string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PrimaryAlias", arg0) - ret0, _ := ret[0].(string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// PrimaryAlias indicates an expected call of PrimaryAlias. -func (mr *MockManagerMockRecorder) PrimaryAlias(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrimaryAlias", reflect.TypeOf((*MockManager)(nil).PrimaryAlias), arg0) -} - -// PrimaryAliasOrDefault mocks base method. -func (m *MockManager) PrimaryAliasOrDefault(arg0 ids.ID) string { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "PrimaryAliasOrDefault", arg0) - ret0, _ := ret[0].(string) - return ret0 -} - -// PrimaryAliasOrDefault indicates an expected call of PrimaryAliasOrDefault. -func (mr *MockManagerMockRecorder) PrimaryAliasOrDefault(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrimaryAliasOrDefault", reflect.TypeOf((*MockManager)(nil).PrimaryAliasOrDefault), arg0) -} - -// RegisterFactory mocks base method. -func (m *MockManager) RegisterFactory(arg0 context.Context, arg1 ids.ID, arg2 Factory) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "RegisterFactory", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// RegisterFactory indicates an expected call of RegisterFactory. -func (mr *MockManagerMockRecorder) RegisterFactory(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterFactory", reflect.TypeOf((*MockManager)(nil).RegisterFactory), arg0, arg1, arg2) -} - -// RemoveAliases mocks base method. -func (m *MockManager) RemoveAliases(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "RemoveAliases", arg0) -} - -// RemoveAliases indicates an expected call of RemoveAliases. -func (mr *MockManagerMockRecorder) RemoveAliases(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveAliases", reflect.TypeOf((*MockManager)(nil).RemoveAliases), arg0) -} - -// Versions mocks base method. -func (m *MockManager) Versions() (map[string]string, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Versions") - ret0, _ := ret[0].(map[string]string) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Versions indicates an expected call of Versions. -func (mr *MockManagerMockRecorder) Versions() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Versions", reflect.TypeOf((*MockManager)(nil).Versions)) -} diff --git a/vms/platformvm/block/builder/builder_test.go b/vms/platformvm/block/builder/builder_test.go index 33574b384582..df5def70a850 100644 --- a/vms/platformvm/block/builder/builder_test.go +++ b/vms/platformvm/block/builder/builder_test.go @@ -23,6 +23,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" @@ -495,7 +496,7 @@ func TestGetNextStakerToReward(t *testing.T) { name: "end of time", timestamp: mockable.MaxTime, stateF: func(ctrl *gomock.Controller) state.Chain { - return state.NewMockChain(ctrl) + return statemock.NewChain(ctrl) }, expectedErr: ErrEndOfTime, }, @@ -507,7 +508,7 @@ func TestGetNextStakerToReward(t *testing.T) { currentStakerIter.EXPECT().Next().Return(false) currentStakerIter.EXPECT().Release() - s := state.NewMockChain(ctrl) + s := statemock.NewChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -532,7 +533,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := state.NewMockChain(ctrl) + s := statemock.NewChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -559,7 +560,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := state.NewMockChain(ctrl) + s := statemock.NewChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -586,7 +587,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := state.NewMockChain(ctrl) + s := statemock.NewChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -608,7 +609,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := state.NewMockChain(ctrl) + s := statemock.NewChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -630,7 +631,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := state.NewMockChain(ctrl) + s := statemock.NewChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s diff --git a/vms/platformvm/block/executor/acceptor_test.go b/vms/platformvm/block/executor/acceptor_test.go index 00b75b3fbbab..68a25295fb63 100644 --- a/vms/platformvm/block/executor/acceptor_test.go +++ b/vms/platformvm/block/executor/acceptor_test.go @@ -11,7 +11,8 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/chains/atomic" - "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/chains/atomic/atomicmock" + "github.com/ava-labs/avalanchego/database/databasemock" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/utils" @@ -21,6 +22,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/validators" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -82,7 +84,7 @@ func TestAcceptorVisitAtomicBlock(t *testing.T) { ctrl := gomock.NewController(t) s := state.NewMockState(ctrl) - sharedMemory := atomic.NewMockSharedMemory(ctrl) + sharedMemory := atomicmock.NewSharedMemory(ctrl) parentID := ids.GenerateTestID() acceptor := &acceptor{ @@ -122,7 +124,7 @@ func TestAcceptorVisitAtomicBlock(t *testing.T) { require.ErrorIs(err, errMissingBlockState) // Set [blk]'s state in the map as though it had been verified. - onAcceptState := state.NewMockDiff(ctrl) + onAcceptState := statemock.NewDiff(ctrl) childID := ids.GenerateTestID() atomicRequests := make(map[ids.ID]*atomic.Requests) acceptor.backend.blkIDToState[blk.ID()] = &blockState{ @@ -130,9 +132,9 @@ func TestAcceptorVisitAtomicBlock(t *testing.T) { atomicRequests: atomicRequests, } // Give [blk] a child. - childOnAcceptState := state.NewMockDiff(ctrl) - childOnAbortState := state.NewMockDiff(ctrl) - childOnCommitState := state.NewMockDiff(ctrl) + childOnAcceptState := statemock.NewDiff(ctrl) + childOnAbortState := statemock.NewDiff(ctrl) + childOnCommitState := statemock.NewDiff(ctrl) childState := &blockState{ onAcceptState: childOnAcceptState, proposalBlockState: proposalBlockState{ @@ -146,7 +148,7 @@ func TestAcceptorVisitAtomicBlock(t *testing.T) { s.EXPECT().SetLastAccepted(blk.ID()).Times(1) s.EXPECT().SetHeight(blk.Height()).Times(1) s.EXPECT().AddStatelessBlock(blk).Times(1) - batch := database.NewMockBatch(ctrl) + batch := databasemock.NewBatch(ctrl) s.EXPECT().CommitBatch().Return(batch, nil).Times(1) s.EXPECT().Abort().Times(1) onAcceptState.EXPECT().Apply(s).Times(1) @@ -161,7 +163,7 @@ func TestAcceptorVisitStandardBlock(t *testing.T) { ctrl := gomock.NewController(t) s := state.NewMockState(ctrl) - sharedMemory := atomic.NewMockSharedMemory(ctrl) + sharedMemory := atomicmock.NewSharedMemory(ctrl) parentID := ids.GenerateTestID() clk := &mockable.Clock{} @@ -205,7 +207,7 @@ func TestAcceptorVisitStandardBlock(t *testing.T) { require.ErrorIs(err, errMissingBlockState) // Set [blk]'s state in the map as though it had been verified. - onAcceptState := state.NewMockDiff(ctrl) + onAcceptState := statemock.NewDiff(ctrl) childID := ids.GenerateTestID() atomicRequests := make(map[ids.ID]*atomic.Requests) calledOnAcceptFunc := false @@ -218,9 +220,9 @@ func TestAcceptorVisitStandardBlock(t *testing.T) { atomicRequests: atomicRequests, } // Give [blk] a child. - childOnAcceptState := state.NewMockDiff(ctrl) - childOnAbortState := state.NewMockDiff(ctrl) - childOnCommitState := state.NewMockDiff(ctrl) + childOnAcceptState := statemock.NewDiff(ctrl) + childOnAbortState := statemock.NewDiff(ctrl) + childOnCommitState := statemock.NewDiff(ctrl) childState := &blockState{ onAcceptState: childOnAcceptState, proposalBlockState: proposalBlockState{ @@ -234,7 +236,7 @@ func TestAcceptorVisitStandardBlock(t *testing.T) { s.EXPECT().SetLastAccepted(blk.ID()).Times(1) s.EXPECT().SetHeight(blk.Height()).Times(1) s.EXPECT().AddStatelessBlock(blk).Times(1) - batch := database.NewMockBatch(ctrl) + batch := databasemock.NewBatch(ctrl) s.EXPECT().CommitBatch().Return(batch, nil).Times(1) s.EXPECT().Abort().Times(1) onAcceptState.EXPECT().Apply(s).Times(1) @@ -251,7 +253,7 @@ func TestAcceptorVisitCommitBlock(t *testing.T) { ctrl := gomock.NewController(t) s := state.NewMockState(ctrl) - sharedMemory := atomic.NewMockSharedMemory(ctrl) + sharedMemory := atomicmock.NewSharedMemory(ctrl) parentID := ids.GenerateTestID() acceptor := &acceptor{ @@ -276,9 +278,9 @@ func TestAcceptorVisitCommitBlock(t *testing.T) { require.ErrorIs(err, state.ErrMissingParentState) // Set [blk]'s parent in the state map. - parentOnAcceptState := state.NewMockDiff(ctrl) - parentOnAbortState := state.NewMockDiff(ctrl) - parentOnCommitState := state.NewMockDiff(ctrl) + parentOnAcceptState := statemock.NewDiff(ctrl) + parentOnAbortState := statemock.NewDiff(ctrl) + parentOnCommitState := statemock.NewDiff(ctrl) parentStatelessBlk := block.NewMockBlock(ctrl) calledOnAcceptFunc := false atomicRequests := make(map[ids.ID]*atomic.Requests) @@ -329,7 +331,7 @@ func TestAcceptorVisitCommitBlock(t *testing.T) { atomicRequests: parentState.atomicRequests, } - batch := database.NewMockBatch(ctrl) + batch := databasemock.NewBatch(ctrl) // Set expected calls on dependencies. // Make sure the parent is accepted first. @@ -361,7 +363,7 @@ func TestAcceptorVisitAbortBlock(t *testing.T) { ctrl := gomock.NewController(t) s := state.NewMockState(ctrl) - sharedMemory := atomic.NewMockSharedMemory(ctrl) + sharedMemory := atomicmock.NewSharedMemory(ctrl) parentID := ids.GenerateTestID() acceptor := &acceptor{ @@ -386,9 +388,9 @@ func TestAcceptorVisitAbortBlock(t *testing.T) { require.ErrorIs(err, state.ErrMissingParentState) // Set [blk]'s parent in the state map. - parentOnAcceptState := state.NewMockDiff(ctrl) - parentOnAbortState := state.NewMockDiff(ctrl) - parentOnCommitState := state.NewMockDiff(ctrl) + parentOnAcceptState := statemock.NewDiff(ctrl) + parentOnAbortState := statemock.NewDiff(ctrl) + parentOnCommitState := statemock.NewDiff(ctrl) parentStatelessBlk := block.NewMockBlock(ctrl) calledOnAcceptFunc := false atomicRequests := make(map[ids.ID]*atomic.Requests) @@ -439,7 +441,7 @@ func TestAcceptorVisitAbortBlock(t *testing.T) { atomicRequests: parentState.atomicRequests, } - batch := database.NewMockBatch(ctrl) + batch := databasemock.NewBatch(ctrl) // Set expected calls on dependencies. // Make sure the parent is accepted first. diff --git a/vms/platformvm/block/executor/backend_test.go b/vms/platformvm/block/executor/backend_test.go index a37823da7507..543da45179d2 100644 --- a/vms/platformvm/block/executor/backend_test.go +++ b/vms/platformvm/block/executor/backend_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" ) func TestGetState(t *testing.T) { @@ -22,7 +23,7 @@ func TestGetState(t *testing.T) { var ( mockState = state.NewMockState(ctrl) - onAcceptState = state.NewMockDiff(ctrl) + onAcceptState = statemock.NewDiff(ctrl) blkID1 = ids.GenerateTestID() blkID2 = ids.GenerateTestID() b = &backend{ diff --git a/vms/platformvm/block/executor/block_test.go b/vms/platformvm/block/executor/block_test.go index dfccc413e29b..27eaed415980 100644 --- a/vms/platformvm/block/executor/block_test.go +++ b/vms/platformvm/block/executor/block_test.go @@ -14,7 +14,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/snowtest" - "github.com/ava-labs/avalanchego/snow/uptime" + "github.com/ava-labs/avalanchego/snow/uptime/uptimemock" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" @@ -38,7 +38,7 @@ func TestBlockOptions(t *testing.T) { blkF: func(ctrl *gomock.Controller) *Block { state := state.NewMockState(ctrl) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) manager := &manager{ backend: &backend{ @@ -65,7 +65,7 @@ func TestBlockOptions(t *testing.T) { blkF: func(ctrl *gomock.Controller) *Block { state := state.NewMockState(ctrl) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) manager := &manager{ backend: &backend{ @@ -101,7 +101,7 @@ func TestBlockOptions(t *testing.T) { state := state.NewMockState(ctrl) state.EXPECT().GetTx(stakerTxID).Return(nil, status.Unknown, database.ErrNotFound) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) manager := &manager{ backend: &backend{ @@ -139,7 +139,7 @@ func TestBlockOptions(t *testing.T) { state := state.NewMockState(ctrl) state.EXPECT().GetTx(stakerTxID).Return(nil, status.Unknown, database.ErrClosed) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) manager := &manager{ backend: &backend{ @@ -180,7 +180,7 @@ func TestBlockOptions(t *testing.T) { state := state.NewMockState(ctrl) state.EXPECT().GetTx(stakerTxID).Return(stakerTx, status.Committed, nil) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) manager := &manager{ backend: &backend{ @@ -231,7 +231,7 @@ func TestBlockOptions(t *testing.T) { state.EXPECT().GetTx(stakerTxID).Return(stakerTx, status.Committed, nil) state.EXPECT().GetCurrentValidator(constants.PrimaryNetworkID, nodeID).Return(nil, database.ErrNotFound) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) manager := &manager{ backend: &backend{ @@ -286,7 +286,7 @@ func TestBlockOptions(t *testing.T) { state.EXPECT().GetTx(stakerTxID).Return(stakerTx, status.Committed, nil) state.EXPECT().GetCurrentValidator(constants.PrimaryNetworkID, nodeID).Return(staker, nil) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) uptimes.EXPECT().CalculateUptimePercentFrom(nodeID, constants.PrimaryNetworkID, primaryNetworkValidatorStartTime).Return(0.0, database.ErrNotFound) manager := &manager{ @@ -343,7 +343,7 @@ func TestBlockOptions(t *testing.T) { state.EXPECT().GetCurrentValidator(constants.PrimaryNetworkID, nodeID).Return(staker, nil) state.EXPECT().GetSubnetTransformation(subnetID).Return(nil, database.ErrNotFound) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) manager := &manager{ backend: &backend{ @@ -404,7 +404,7 @@ func TestBlockOptions(t *testing.T) { state.EXPECT().GetCurrentValidator(constants.PrimaryNetworkID, nodeID).Return(staker, nil) state.EXPECT().GetSubnetTransformation(subnetID).Return(transformSubnetTx, nil) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) uptimes.EXPECT().CalculateUptimePercentFrom(nodeID, constants.PrimaryNetworkID, primaryNetworkValidatorStartTime).Return(.5, nil) manager := &manager{ @@ -466,7 +466,7 @@ func TestBlockOptions(t *testing.T) { state.EXPECT().GetCurrentValidator(constants.PrimaryNetworkID, nodeID).Return(staker, nil) state.EXPECT().GetSubnetTransformation(subnetID).Return(transformSubnetTx, nil) - uptimes := uptime.NewMockCalculator(ctrl) + uptimes := uptimemock.NewCalculator(ctrl) uptimes.EXPECT().CalculateUptimePercentFrom(nodeID, constants.PrimaryNetworkID, primaryNetworkValidatorStartTime).Return(.5, nil) manager := &manager{ diff --git a/vms/platformvm/block/executor/mock_manager.go b/vms/platformvm/block/executor/executormock/manager.go similarity index 59% rename from vms/platformvm/block/executor/mock_manager.go rename to vms/platformvm/block/executor/executormock/manager.go index 5e8222383071..1b6c1a5094c1 100644 --- a/vms/platformvm/block/executor/mock_manager.go +++ b/vms/platformvm/block/executor/executormock/manager.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -source=vms/platformvm/block/executor/manager.go -destination=vms/platformvm/block/executor/mock_manager.go -package=executor -exclude_interfaces= +// mockgen -source=vms/platformvm/block/executor/manager.go -destination=vms/platformvm/block/executor/executormock/manager.go -package=executormock -exclude_interfaces= -mock_names=Manager=Manager // -// Package executor is a generated GoMock package. -package executor +// Package executormock is a generated GoMock package. +package executormock import ( reflect "reflect" @@ -21,31 +21,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockManager is a mock of Manager interface. -type MockManager struct { +// Manager is a mock of Manager interface. +type Manager struct { ctrl *gomock.Controller - recorder *MockManagerMockRecorder + recorder *ManagerMockRecorder } -// MockManagerMockRecorder is the mock recorder for MockManager. -type MockManagerMockRecorder struct { - mock *MockManager +// ManagerMockRecorder is the mock recorder for Manager. +type ManagerMockRecorder struct { + mock *Manager } -// NewMockManager creates a new mock instance. -func NewMockManager(ctrl *gomock.Controller) *MockManager { - mock := &MockManager{ctrl: ctrl} - mock.recorder = &MockManagerMockRecorder{mock} +// NewManager creates a new mock instance. +func NewManager(ctrl *gomock.Controller) *Manager { + mock := &Manager{ctrl: ctrl} + mock.recorder = &ManagerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockManager) EXPECT() *MockManagerMockRecorder { +func (m *Manager) EXPECT() *ManagerMockRecorder { return m.recorder } // GetBlock mocks base method. -func (m *MockManager) GetBlock(blkID ids.ID) (snowman.Block, error) { +func (m *Manager) GetBlock(blkID ids.ID) (snowman.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBlock", blkID) ret0, _ := ret[0].(snowman.Block) @@ -54,13 +54,13 @@ func (m *MockManager) GetBlock(blkID ids.ID) (snowman.Block, error) { } // GetBlock indicates an expected call of GetBlock. -func (mr *MockManagerMockRecorder) GetBlock(blkID any) *gomock.Call { +func (mr *ManagerMockRecorder) GetBlock(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*MockManager)(nil).GetBlock), blkID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*Manager)(nil).GetBlock), blkID) } // GetState mocks base method. -func (m *MockManager) GetState(blkID ids.ID) (state.Chain, bool) { +func (m *Manager) GetState(blkID ids.ID) (state.Chain, bool) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetState", blkID) ret0, _ := ret[0].(state.Chain) @@ -69,13 +69,13 @@ func (m *MockManager) GetState(blkID ids.ID) (state.Chain, bool) { } // GetState indicates an expected call of GetState. -func (mr *MockManagerMockRecorder) GetState(blkID any) *gomock.Call { +func (mr *ManagerMockRecorder) GetState(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetState", reflect.TypeOf((*MockManager)(nil).GetState), blkID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetState", reflect.TypeOf((*Manager)(nil).GetState), blkID) } // GetStatelessBlock mocks base method. -func (m *MockManager) GetStatelessBlock(blkID ids.ID) (block.Block, error) { +func (m *Manager) GetStatelessBlock(blkID ids.ID) (block.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetStatelessBlock", blkID) ret0, _ := ret[0].(block.Block) @@ -84,13 +84,13 @@ func (m *MockManager) GetStatelessBlock(blkID ids.ID) (block.Block, error) { } // GetStatelessBlock indicates an expected call of GetStatelessBlock. -func (mr *MockManagerMockRecorder) GetStatelessBlock(blkID any) *gomock.Call { +func (mr *ManagerMockRecorder) GetStatelessBlock(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStatelessBlock", reflect.TypeOf((*MockManager)(nil).GetStatelessBlock), blkID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStatelessBlock", reflect.TypeOf((*Manager)(nil).GetStatelessBlock), blkID) } // LastAccepted mocks base method. -func (m *MockManager) LastAccepted() ids.ID { +func (m *Manager) LastAccepted() ids.ID { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "LastAccepted") ret0, _ := ret[0].(ids.ID) @@ -98,13 +98,13 @@ func (m *MockManager) LastAccepted() ids.ID { } // LastAccepted indicates an expected call of LastAccepted. -func (mr *MockManagerMockRecorder) LastAccepted() *gomock.Call { +func (mr *ManagerMockRecorder) LastAccepted() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAccepted", reflect.TypeOf((*MockManager)(nil).LastAccepted)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LastAccepted", reflect.TypeOf((*Manager)(nil).LastAccepted)) } // NewBlock mocks base method. -func (m *MockManager) NewBlock(arg0 block.Block) snowman.Block { +func (m *Manager) NewBlock(arg0 block.Block) snowman.Block { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "NewBlock", arg0) ret0, _ := ret[0].(snowman.Block) @@ -112,13 +112,13 @@ func (m *MockManager) NewBlock(arg0 block.Block) snowman.Block { } // NewBlock indicates an expected call of NewBlock. -func (mr *MockManagerMockRecorder) NewBlock(arg0 any) *gomock.Call { +func (mr *ManagerMockRecorder) NewBlock(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewBlock", reflect.TypeOf((*MockManager)(nil).NewBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "NewBlock", reflect.TypeOf((*Manager)(nil).NewBlock), arg0) } // Preferred mocks base method. -func (m *MockManager) Preferred() ids.ID { +func (m *Manager) Preferred() ids.ID { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Preferred") ret0, _ := ret[0].(ids.ID) @@ -126,13 +126,13 @@ func (m *MockManager) Preferred() ids.ID { } // Preferred indicates an expected call of Preferred. -func (mr *MockManagerMockRecorder) Preferred() *gomock.Call { +func (mr *ManagerMockRecorder) Preferred() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Preferred", reflect.TypeOf((*MockManager)(nil).Preferred)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Preferred", reflect.TypeOf((*Manager)(nil).Preferred)) } // SetPreference mocks base method. -func (m *MockManager) SetPreference(blkID ids.ID) bool { +func (m *Manager) SetPreference(blkID ids.ID) bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetPreference", blkID) ret0, _ := ret[0].(bool) @@ -140,13 +140,13 @@ func (m *MockManager) SetPreference(blkID ids.ID) bool { } // SetPreference indicates an expected call of SetPreference. -func (mr *MockManagerMockRecorder) SetPreference(blkID any) *gomock.Call { +func (mr *ManagerMockRecorder) SetPreference(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPreference", reflect.TypeOf((*MockManager)(nil).SetPreference), blkID) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPreference", reflect.TypeOf((*Manager)(nil).SetPreference), blkID) } // VerifyTx mocks base method. -func (m *MockManager) VerifyTx(tx *txs.Tx) error { +func (m *Manager) VerifyTx(tx *txs.Tx) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "VerifyTx", tx) ret0, _ := ret[0].(error) @@ -154,13 +154,13 @@ func (m *MockManager) VerifyTx(tx *txs.Tx) error { } // VerifyTx indicates an expected call of VerifyTx. -func (mr *MockManagerMockRecorder) VerifyTx(tx any) *gomock.Call { +func (mr *ManagerMockRecorder) VerifyTx(tx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyTx", reflect.TypeOf((*MockManager)(nil).VerifyTx), tx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyTx", reflect.TypeOf((*Manager)(nil).VerifyTx), tx) } // VerifyUniqueInputs mocks base method. -func (m *MockManager) VerifyUniqueInputs(blkID ids.ID, inputs set.Set[ids.ID]) error { +func (m *Manager) VerifyUniqueInputs(blkID ids.ID, inputs set.Set[ids.ID]) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "VerifyUniqueInputs", blkID, inputs) ret0, _ := ret[0].(error) @@ -168,7 +168,7 @@ func (m *MockManager) VerifyUniqueInputs(blkID ids.ID, inputs set.Set[ids.ID]) e } // VerifyUniqueInputs indicates an expected call of VerifyUniqueInputs. -func (mr *MockManagerMockRecorder) VerifyUniqueInputs(blkID, inputs any) *gomock.Call { +func (mr *ManagerMockRecorder) VerifyUniqueInputs(blkID, inputs any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyUniqueInputs", reflect.TypeOf((*MockManager)(nil).VerifyUniqueInputs), blkID, inputs) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyUniqueInputs", reflect.TypeOf((*Manager)(nil).VerifyUniqueInputs), blkID, inputs) } diff --git a/vms/platformvm/block/executor/proposal_block_test.go b/vms/platformvm/block/executor/proposal_block_test.go index 59141140b04a..124049a26d5c 100644 --- a/vms/platformvm/block/executor/proposal_block_test.go +++ b/vms/platformvm/block/executor/proposal_block_test.go @@ -26,6 +26,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" @@ -53,7 +54,7 @@ func TestApricotProposalBlockTimeVerification(t *testing.T) { parentID := apricotParentBlk.ID() // store parent block, with relevant quantities - onParentAccept := state.NewMockDiff(ctrl) + onParentAccept := statemock.NewDiff(ctrl) env.blkManager.(*manager).blkIDToState[parentID] = &blockState{ statelessBlock: apricotParentBlk, onAcceptState: onParentAccept, @@ -157,7 +158,7 @@ func TestBanffProposalBlockTimeVerification(t *testing.T) { // store parent block, with relevant quantities chainTime := parentTime - onParentAccept := state.NewMockDiff(ctrl) + onParentAccept := statemock.NewDiff(ctrl) onParentAccept.EXPECT().GetTimestamp().Return(parentTime).AnyTimes() onParentAccept.EXPECT().GetFeeState().Return(gas.State{}).AnyTimes() onParentAccept.EXPECT().GetCurrentSupply(constants.PrimaryNetworkID).Return(uint64(1000), nil).AnyTimes() diff --git a/vms/platformvm/block/executor/rejector_test.go b/vms/platformvm/block/executor/rejector_test.go index 41881d277c68..926a139399a6 100644 --- a/vms/platformvm/block/executor/rejector_test.go +++ b/vms/platformvm/block/executor/rejector_test.go @@ -17,7 +17,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/txs" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool/mempoolmock" "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) @@ -119,7 +119,7 @@ func TestRejectBlock(t *testing.T) { blk, err := tt.newBlockFunc() require.NoError(err) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) state := state.NewMockState(ctrl) blkIDToState := map[ids.ID]*blockState{ blk.Parent(): nil, diff --git a/vms/platformvm/block/executor/standard_block_test.go b/vms/platformvm/block/executor/standard_block_test.go index 45f297dc48f7..a84b7efc246d 100644 --- a/vms/platformvm/block/executor/standard_block_test.go +++ b/vms/platformvm/block/executor/standard_block_test.go @@ -21,6 +21,7 @@ import ( "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" @@ -48,7 +49,7 @@ func TestApricotStandardBlockTimeVerification(t *testing.T) { parentID := apricotParentBlk.ID() // store parent block, with relevant quantities - onParentAccept := state.NewMockDiff(ctrl) + onParentAccept := statemock.NewDiff(ctrl) env.blkManager.(*manager).blkIDToState[parentID] = &blockState{ statelessBlock: apricotParentBlk, onAcceptState: onParentAccept, @@ -104,7 +105,7 @@ func TestBanffStandardBlockTimeVerification(t *testing.T) { parentID := banffParentBlk.ID() // store parent block, with relevant quantities - onParentAccept := state.NewMockDiff(ctrl) + onParentAccept := statemock.NewDiff(ctrl) chainTime := env.clk.Time().Truncate(time.Second) env.blkManager.(*manager).blkIDToState[parentID] = &blockState{ statelessBlock: banffParentBlk, diff --git a/vms/platformvm/block/executor/verifier_test.go b/vms/platformvm/block/executor/verifier_test.go index 0d8baaca106f..e8f9f478c29a 100644 --- a/vms/platformvm/block/executor/verifier_test.go +++ b/vms/platformvm/block/executor/verifier_test.go @@ -24,10 +24,12 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool/mempoolmock" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/txsmock" ) func TestVerifierVisitProposalBlock(t *testing.T) { @@ -35,10 +37,10 @@ func TestVerifierVisitProposalBlock(t *testing.T) { ctrl := gomock.NewController(t) s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentOnAcceptState := state.NewMockDiff(ctrl) + parentOnAcceptState := statemock.NewDiff(ctrl) timestamp := time.Now() // One call for each of onCommitState and onAbortState. parentOnAcceptState.EXPECT().GetTimestamp().Return(timestamp).Times(2) @@ -68,7 +70,7 @@ func TestVerifierVisitProposalBlock(t *testing.T) { backend: backend, } - blkTx := txs.NewMockUnsignedTx(ctrl) + blkTx := txsmock.NewUnsignedTx(ctrl) blkTx.EXPECT().Visit(gomock.AssignableToTypeOf(&executor.ProposalTxExecutor{})).Return(nil).Times(1) // We can't serialize [blkTx] because it isn't @@ -119,11 +121,11 @@ func TestVerifierVisitAtomicBlock(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) grandparentID := ids.GenerateTestID() - parentState := state.NewMockDiff(ctrl) + parentState := statemock.NewDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -148,8 +150,8 @@ func TestVerifierVisitAtomicBlock(t *testing.T) { backend: backend, } - onAccept := state.NewMockDiff(ctrl) - blkTx := txs.NewMockUnsignedTx(ctrl) + onAccept := statemock.NewDiff(ctrl) + blkTx := txsmock.NewUnsignedTx(ctrl) inputs := set.Of(ids.GenerateTestID()) blkTx.EXPECT().Visit(gomock.AssignableToTypeOf(&executor.AtomicTxExecutor{})).DoAndReturn( func(e *executor.AtomicTxExecutor) error { @@ -202,10 +204,10 @@ func TestVerifierVisitStandardBlock(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentState := state.NewMockDiff(ctrl) + parentState := statemock.NewDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -230,7 +232,7 @@ func TestVerifierVisitStandardBlock(t *testing.T) { backend: backend, } - blkTx := txs.NewMockUnsignedTx(ctrl) + blkTx := txsmock.NewUnsignedTx(ctrl) atomicRequests := map[ids.ID]*atomic.Requests{ ids.GenerateTestID(): { RemoveRequests: [][]byte{{1}, {2}}, @@ -297,12 +299,12 @@ func TestVerifierVisitCommitBlock(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentOnDecisionState := state.NewMockDiff(ctrl) - parentOnCommitState := state.NewMockDiff(ctrl) - parentOnAbortState := state.NewMockDiff(ctrl) + parentOnDecisionState := statemock.NewDiff(ctrl) + parentOnCommitState := statemock.NewDiff(ctrl) + parentOnAbortState := statemock.NewDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -364,12 +366,12 @@ func TestVerifierVisitAbortBlock(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentOnDecisionState := state.NewMockDiff(ctrl) - parentOnCommitState := state.NewMockDiff(ctrl) - parentOnAbortState := state.NewMockDiff(ctrl) + parentOnDecisionState := statemock.NewDiff(ctrl) + parentOnCommitState := statemock.NewDiff(ctrl) + parentOnAbortState := statemock.NewDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -432,7 +434,7 @@ func TestVerifyUnverifiedParent(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() backend := &backend{ @@ -502,7 +504,7 @@ func TestBanffAbortBlockTimestampChecks(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) parentHeight := uint64(1) @@ -599,7 +601,7 @@ func TestBanffCommitBlockTimestampChecks(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) parentHeight := uint64(1) @@ -664,14 +666,14 @@ func TestVerifierVisitStandardBlockWithDuplicateInputs(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) grandParentID := ids.GenerateTestID() grandParentStatelessBlk := block.NewMockBlock(ctrl) - grandParentState := state.NewMockDiff(ctrl) + grandParentState := statemock.NewDiff(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentState := state.NewMockDiff(ctrl) + parentState := statemock.NewDiff(ctrl) atomicInputs := set.Of(ids.GenerateTestID()) backend := &backend{ @@ -702,7 +704,7 @@ func TestVerifierVisitStandardBlockWithDuplicateInputs(t *testing.T) { backend: backend, } - blkTx := txs.NewMockUnsignedTx(ctrl) + blkTx := txsmock.NewUnsignedTx(ctrl) atomicRequests := map[ids.ID]*atomic.Requests{ ids.GenerateTestID(): { RemoveRequests: [][]byte{{1}, {2}}, @@ -759,11 +761,11 @@ func TestVerifierVisitApricotStandardBlockWithProposalBlockParent(t *testing.T) // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentOnCommitState := state.NewMockDiff(ctrl) - parentOnAbortState := state.NewMockDiff(ctrl) + parentOnCommitState := statemock.NewDiff(ctrl) + parentOnAbortState := statemock.NewDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -815,12 +817,12 @@ func TestVerifierVisitBanffStandardBlockWithProposalBlockParent(t *testing.T) { // Create mocked dependencies. s := state.NewMockState(ctrl) - mempool := mempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) parentTime := time.Now() - parentOnCommitState := state.NewMockDiff(ctrl) - parentOnAbortState := state.NewMockDiff(ctrl) + parentOnCommitState := statemock.NewDiff(ctrl) + parentOnAbortState := statemock.NewDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ diff --git a/vms/platformvm/block/mock_block.go b/vms/platformvm/block/mock_block.go index 7bd281192253..34e00be948a2 100644 --- a/vms/platformvm/block/mock_block.go +++ b/vms/platformvm/block/mock_block.go @@ -1,9 +1,9 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/platformvm/block (interfaces: Block) +// Source: vms/platformvm/block/block.go // // Generated by this command: // -// mockgen -package=block -destination=vms/platformvm/block/mock_block.go github.com/ava-labs/avalanchego/vms/platformvm/block Block +// mockgen -source=vms/platformvm/block/block.go -destination=vms/platformvm/block/mock_block.go -package=block -exclude_interfaces=BanffBlock -mock_names=MockBlock=MockBlock // // Package block is a generated GoMock package. @@ -84,15 +84,15 @@ func (mr *MockBlockMockRecorder) ID() *gomock.Call { } // InitCtx mocks base method. -func (m *MockBlock) InitCtx(arg0 *snow.Context) { +func (m *MockBlock) InitCtx(ctx *snow.Context) { m.ctrl.T.Helper() - m.ctrl.Call(m, "InitCtx", arg0) + m.ctrl.Call(m, "InitCtx", ctx) } // InitCtx indicates an expected call of InitCtx. -func (mr *MockBlockMockRecorder) InitCtx(arg0 any) *gomock.Call { +func (mr *MockBlockMockRecorder) InitCtx(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockBlock)(nil).InitCtx), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockBlock)(nil).InitCtx), ctx) } // Parent mocks base method. @@ -124,29 +124,29 @@ func (mr *MockBlockMockRecorder) Txs() *gomock.Call { } // Visit mocks base method. -func (m *MockBlock) Visit(arg0 Visitor) error { +func (m *MockBlock) Visit(visitor Visitor) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Visit", arg0) + ret := m.ctrl.Call(m, "Visit", visitor) ret0, _ := ret[0].(error) return ret0 } // Visit indicates an expected call of Visit. -func (mr *MockBlockMockRecorder) Visit(arg0 any) *gomock.Call { +func (mr *MockBlockMockRecorder) Visit(visitor any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Visit", reflect.TypeOf((*MockBlock)(nil).Visit), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Visit", reflect.TypeOf((*MockBlock)(nil).Visit), visitor) } // initialize mocks base method. -func (m *MockBlock) initialize(arg0 []byte) error { +func (m *MockBlock) initialize(bytes []byte) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "initialize", arg0) + ret := m.ctrl.Call(m, "initialize", bytes) ret0, _ := ret[0].(error) return ret0 } // initialize indicates an expected call of initialize. -func (mr *MockBlockMockRecorder) initialize(arg0 any) *gomock.Call { +func (mr *MockBlockMockRecorder) initialize(bytes any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "initialize", reflect.TypeOf((*MockBlock)(nil).initialize), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "initialize", reflect.TypeOf((*MockBlock)(nil).initialize), bytes) } diff --git a/vms/platformvm/fx/fxmock/fx.go b/vms/platformvm/fx/fxmock/fx.go new file mode 100644 index 000000000000..39e6d550ad81 --- /dev/null +++ b/vms/platformvm/fx/fxmock/fx.go @@ -0,0 +1,124 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/platformvm/fx (interfaces: Fx) +// +// Generated by this command: +// +// mockgen -package=fxmock -destination=vms/platformvm/fx/fxmock/fx.go -mock_names=Fx=Fx github.com/ava-labs/avalanchego/vms/platformvm/fx Fx +// + +// Package fxmock is a generated GoMock package. +package fxmock + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// Fx is a mock of Fx interface. +type Fx struct { + ctrl *gomock.Controller + recorder *FxMockRecorder +} + +// FxMockRecorder is the mock recorder for Fx. +type FxMockRecorder struct { + mock *Fx +} + +// NewFx creates a new mock instance. +func NewFx(ctrl *gomock.Controller) *Fx { + mock := &Fx{ctrl: ctrl} + mock.recorder = &FxMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Fx) EXPECT() *FxMockRecorder { + return m.recorder +} + +// Bootstrapped mocks base method. +func (m *Fx) Bootstrapped() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Bootstrapped") + ret0, _ := ret[0].(error) + return ret0 +} + +// Bootstrapped indicates an expected call of Bootstrapped. +func (mr *FxMockRecorder) Bootstrapped() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bootstrapped", reflect.TypeOf((*Fx)(nil).Bootstrapped)) +} + +// Bootstrapping mocks base method. +func (m *Fx) Bootstrapping() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Bootstrapping") + ret0, _ := ret[0].(error) + return ret0 +} + +// Bootstrapping indicates an expected call of Bootstrapping. +func (mr *FxMockRecorder) Bootstrapping() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bootstrapping", reflect.TypeOf((*Fx)(nil).Bootstrapping)) +} + +// CreateOutput mocks base method. +func (m *Fx) CreateOutput(arg0 uint64, arg1 any) (any, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateOutput", arg0, arg1) + ret0, _ := ret[0].(any) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// CreateOutput indicates an expected call of CreateOutput. +func (mr *FxMockRecorder) CreateOutput(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOutput", reflect.TypeOf((*Fx)(nil).CreateOutput), arg0, arg1) +} + +// Initialize mocks base method. +func (m *Fx) Initialize(arg0 any) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Initialize", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// Initialize indicates an expected call of Initialize. +func (mr *FxMockRecorder) Initialize(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*Fx)(nil).Initialize), arg0) +} + +// VerifyPermission mocks base method. +func (m *Fx) VerifyPermission(arg0, arg1, arg2, arg3 any) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "VerifyPermission", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(error) + return ret0 +} + +// VerifyPermission indicates an expected call of VerifyPermission. +func (mr *FxMockRecorder) VerifyPermission(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyPermission", reflect.TypeOf((*Fx)(nil).VerifyPermission), arg0, arg1, arg2, arg3) +} + +// VerifyTransfer mocks base method. +func (m *Fx) VerifyTransfer(arg0, arg1, arg2, arg3 any) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "VerifyTransfer", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(error) + return ret0 +} + +// VerifyTransfer indicates an expected call of VerifyTransfer. +func (mr *FxMockRecorder) VerifyTransfer(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyTransfer", reflect.TypeOf((*Fx)(nil).VerifyTransfer), arg0, arg1, arg2, arg3) +} diff --git a/vms/platformvm/fx/fxmock/owner.go b/vms/platformvm/fx/fxmock/owner.go new file mode 100644 index 000000000000..9f1f9b0e6932 --- /dev/null +++ b/vms/platformvm/fx/fxmock/owner.go @@ -0,0 +1,83 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/platformvm/fx (interfaces: Owner) +// +// Generated by this command: +// +// mockgen -package=fxmock -destination=vms/platformvm/fx/fxmock/owner.go -mock_names=Owner=Owner github.com/ava-labs/avalanchego/vms/platformvm/fx Owner +// + +// Package fxmock is a generated GoMock package. +package fxmock + +import ( + reflect "reflect" + + snow "github.com/ava-labs/avalanchego/snow" + verify "github.com/ava-labs/avalanchego/vms/components/verify" + gomock "go.uber.org/mock/gomock" +) + +// Owner is a mock of Owner interface. +type Owner struct { + verify.IsNotState + + ctrl *gomock.Controller + recorder *OwnerMockRecorder +} + +// OwnerMockRecorder is the mock recorder for Owner. +type OwnerMockRecorder struct { + mock *Owner +} + +// NewOwner creates a new mock instance. +func NewOwner(ctrl *gomock.Controller) *Owner { + mock := &Owner{ctrl: ctrl} + mock.recorder = &OwnerMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Owner) EXPECT() *OwnerMockRecorder { + return m.recorder +} + +// InitCtx mocks base method. +func (m *Owner) InitCtx(arg0 *snow.Context) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "InitCtx", arg0) +} + +// InitCtx indicates an expected call of InitCtx. +func (mr *OwnerMockRecorder) InitCtx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*Owner)(nil).InitCtx), arg0) +} + +// Verify mocks base method. +func (m *Owner) Verify() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Verify") + ret0, _ := ret[0].(error) + return ret0 +} + +// Verify indicates an expected call of Verify. +func (mr *OwnerMockRecorder) Verify() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*Owner)(nil).Verify)) +} + +// isState mocks base method. +func (m *Owner) isState() error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "isState") + ret0, _ := ret[0].(error) + return ret0 +} + +// isState indicates an expected call of isState. +func (mr *OwnerMockRecorder) isState() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "isState", reflect.TypeOf((*Owner)(nil).isState)) +} diff --git a/vms/platformvm/fx/mock_fx.go b/vms/platformvm/fx/mock_fx.go deleted file mode 100644 index 6878c124b822..000000000000 --- a/vms/platformvm/fx/mock_fx.go +++ /dev/null @@ -1,191 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/platformvm/fx (interfaces: Fx,Owner) -// -// Generated by this command: -// -// mockgen -package=fx -destination=vms/platformvm/fx/mock_fx.go github.com/ava-labs/avalanchego/vms/platformvm/fx Fx,Owner -// - -// Package fx is a generated GoMock package. -package fx - -import ( - reflect "reflect" - - snow "github.com/ava-labs/avalanchego/snow" - verify "github.com/ava-labs/avalanchego/vms/components/verify" - gomock "go.uber.org/mock/gomock" -) - -// MockFx is a mock of Fx interface. -type MockFx struct { - ctrl *gomock.Controller - recorder *MockFxMockRecorder -} - -// MockFxMockRecorder is the mock recorder for MockFx. -type MockFxMockRecorder struct { - mock *MockFx -} - -// NewMockFx creates a new mock instance. -func NewMockFx(ctrl *gomock.Controller) *MockFx { - mock := &MockFx{ctrl: ctrl} - mock.recorder = &MockFxMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockFx) EXPECT() *MockFxMockRecorder { - return m.recorder -} - -// Bootstrapped mocks base method. -func (m *MockFx) Bootstrapped() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Bootstrapped") - ret0, _ := ret[0].(error) - return ret0 -} - -// Bootstrapped indicates an expected call of Bootstrapped. -func (mr *MockFxMockRecorder) Bootstrapped() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bootstrapped", reflect.TypeOf((*MockFx)(nil).Bootstrapped)) -} - -// Bootstrapping mocks base method. -func (m *MockFx) Bootstrapping() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Bootstrapping") - ret0, _ := ret[0].(error) - return ret0 -} - -// Bootstrapping indicates an expected call of Bootstrapping. -func (mr *MockFxMockRecorder) Bootstrapping() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bootstrapping", reflect.TypeOf((*MockFx)(nil).Bootstrapping)) -} - -// CreateOutput mocks base method. -func (m *MockFx) CreateOutput(arg0 uint64, arg1 any) (any, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "CreateOutput", arg0, arg1) - ret0, _ := ret[0].(any) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// CreateOutput indicates an expected call of CreateOutput. -func (mr *MockFxMockRecorder) CreateOutput(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateOutput", reflect.TypeOf((*MockFx)(nil).CreateOutput), arg0, arg1) -} - -// Initialize mocks base method. -func (m *MockFx) Initialize(arg0 any) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Initialize", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// Initialize indicates an expected call of Initialize. -func (mr *MockFxMockRecorder) Initialize(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*MockFx)(nil).Initialize), arg0) -} - -// VerifyPermission mocks base method. -func (m *MockFx) VerifyPermission(arg0, arg1, arg2, arg3 any) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "VerifyPermission", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(error) - return ret0 -} - -// VerifyPermission indicates an expected call of VerifyPermission. -func (mr *MockFxMockRecorder) VerifyPermission(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyPermission", reflect.TypeOf((*MockFx)(nil).VerifyPermission), arg0, arg1, arg2, arg3) -} - -// VerifyTransfer mocks base method. -func (m *MockFx) VerifyTransfer(arg0, arg1, arg2, arg3 any) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "VerifyTransfer", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(error) - return ret0 -} - -// VerifyTransfer indicates an expected call of VerifyTransfer. -func (mr *MockFxMockRecorder) VerifyTransfer(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyTransfer", reflect.TypeOf((*MockFx)(nil).VerifyTransfer), arg0, arg1, arg2, arg3) -} - -// MockOwner is a mock of Owner interface. -type MockOwner struct { - verify.IsNotState - - ctrl *gomock.Controller - recorder *MockOwnerMockRecorder -} - -// MockOwnerMockRecorder is the mock recorder for MockOwner. -type MockOwnerMockRecorder struct { - mock *MockOwner -} - -// NewMockOwner creates a new mock instance. -func NewMockOwner(ctrl *gomock.Controller) *MockOwner { - mock := &MockOwner{ctrl: ctrl} - mock.recorder = &MockOwnerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockOwner) EXPECT() *MockOwnerMockRecorder { - return m.recorder -} - -// InitCtx mocks base method. -func (m *MockOwner) InitCtx(arg0 *snow.Context) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "InitCtx", arg0) -} - -// InitCtx indicates an expected call of InitCtx. -func (mr *MockOwnerMockRecorder) InitCtx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockOwner)(nil).InitCtx), arg0) -} - -// Verify mocks base method. -func (m *MockOwner) Verify() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Verify") - ret0, _ := ret[0].(error) - return ret0 -} - -// Verify indicates an expected call of Verify. -func (mr *MockOwnerMockRecorder) Verify() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockOwner)(nil).Verify)) -} - -// isState mocks base method. -func (m *MockOwner) isState() error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "isState") - ret0, _ := ret[0].(error) - return ret0 -} - -// isState indicates an expected call of isState. -func (mr *MockOwnerMockRecorder) isState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "isState", reflect.TypeOf((*MockOwner)(nil).isState)) -} diff --git a/vms/platformvm/network/gossip_test.go b/vms/platformvm/network/gossip_test.go index eea36ed5230e..a347c6e332c3 100644 --- a/vms/platformvm/network/gossip_test.go +++ b/vms/platformvm/network/gossip_test.go @@ -14,9 +14,8 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool/mempoolmock" "github.com/ava-labs/avalanchego/vms/txs/mempool" - - pmempool "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool" ) var errFoo = errors.New("foo") @@ -31,7 +30,7 @@ func TestGossipMempoolAddVerificationError(t *testing.T) { TxID: txID, } - mempool := pmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) txVerifier := testTxVerifier{err: errFoo} mempool.EXPECT().Get(txID).Return(nil, false) @@ -65,7 +64,7 @@ func TestGossipMempoolAddError(t *testing.T) { } txVerifier := testTxVerifier{} - mempool := pmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(txID).Return(nil, false) mempool.EXPECT().GetDropReason(txID).Return(nil) @@ -93,7 +92,7 @@ func TestMempoolDuplicate(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - testMempool := pmempool.NewMockMempool(ctrl) + testMempool := mempoolmock.NewMempool(ctrl) txVerifier := testTxVerifier{} txID := ids.GenerateTestID() @@ -130,7 +129,7 @@ func TestGossipAddBloomFilter(t *testing.T) { } txVerifier := testTxVerifier{} - mempool := pmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(txID).Return(nil, false) mempool.EXPECT().GetDropReason(txID).Return(nil) diff --git a/vms/platformvm/network/network_test.go b/vms/platformvm/network/network_test.go index f19600461af7..f649c677450c 100644 --- a/vms/platformvm/network/network_test.go +++ b/vms/platformvm/network/network_test.go @@ -15,8 +15,10 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/common/commonmock" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool/mempoolmock" "github.com/ava-labs/avalanchego/vms/txs/mempool" pmempool "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool" @@ -71,33 +73,33 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { { name: "mempool has transaction", mempoolFunc: func(ctrl *gomock.Controller) pmempool.Mempool { - mempool := pmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(tx, true) return mempool }, appSenderFunc: func(ctrl *gomock.Controller) common.AppSender { - return common.NewMockSender(ctrl) + return commonmock.NewSender(ctrl) }, expectedErr: mempool.ErrDuplicateTx, }, { name: "transaction marked as dropped in mempool", mempoolFunc: func(ctrl *gomock.Controller) pmempool.Mempool { - mempool := pmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, false) mempool.EXPECT().GetDropReason(gomock.Any()).Return(errTest) return mempool }, appSenderFunc: func(ctrl *gomock.Controller) common.AppSender { // Shouldn't gossip the tx - return common.NewMockSender(ctrl) + return commonmock.NewSender(ctrl) }, expectedErr: errTest, }, { name: "transaction invalid", mempoolFunc: func(ctrl *gomock.Controller) pmempool.Mempool { - mempool := pmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, false) mempool.EXPECT().GetDropReason(gomock.Any()).Return(nil) mempool.EXPECT().MarkDropped(gomock.Any(), gomock.Any()) @@ -106,14 +108,14 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { txVerifier: testTxVerifier{err: errTest}, appSenderFunc: func(ctrl *gomock.Controller) common.AppSender { // Shouldn't gossip the tx - return common.NewMockSender(ctrl) + return commonmock.NewSender(ctrl) }, expectedErr: errTest, }, { name: "can't add transaction to mempool", mempoolFunc: func(ctrl *gomock.Controller) pmempool.Mempool { - mempool := pmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, false) mempool.EXPECT().GetDropReason(gomock.Any()).Return(nil) mempool.EXPECT().Add(gomock.Any()).Return(errTest) @@ -122,25 +124,25 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { }, appSenderFunc: func(ctrl *gomock.Controller) common.AppSender { // Shouldn't gossip the tx - return common.NewMockSender(ctrl) + return commonmock.NewSender(ctrl) }, expectedErr: errTest, }, { name: "mempool is disabled if primary network is not being fully synced", mempoolFunc: func(ctrl *gomock.Controller) pmempool.Mempool { - return pmempool.NewMockMempool(ctrl) + return mempoolmock.NewMempool(ctrl) }, partialSyncPrimaryNetwork: true, appSenderFunc: func(ctrl *gomock.Controller) common.AppSender { - return common.NewMockSender(ctrl) + return commonmock.NewSender(ctrl) }, expectedErr: errMempoolDisabledWithPartialSync, }, { name: "happy path", mempoolFunc: func(ctrl *gomock.Controller) pmempool.Mempool { - mempool := pmempool.NewMockMempool(ctrl) + mempool := mempoolmock.NewMempool(ctrl) mempool.EXPECT().Get(gomock.Any()).Return(nil, false) mempool.EXPECT().GetDropReason(gomock.Any()).Return(nil) mempool.EXPECT().Add(gomock.Any()).Return(nil) @@ -150,7 +152,7 @@ func TestNetworkIssueTxFromRPC(t *testing.T) { return mempool }, appSenderFunc: func(ctrl *gomock.Controller) common.AppSender { - appSender := common.NewMockSender(ctrl) + appSender := commonmock.NewSender(ctrl) appSender.EXPECT().SendAppGossip(gomock.Any(), gomock.Any(), gomock.Any()).Return(nil) return appSender }, diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index a7043f37cc57..f1c1cd2f44dc 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -36,6 +36,7 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" + "github.com/ava-labs/avalanchego/vms/platformvm/block/executor/executormock" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -886,7 +887,7 @@ func TestServiceGetBlockByHeight(t *testing.T) { state := state.NewMockState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(ids.Empty, database.ErrNotFound) - manager := blockexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) return &Service{ vm: &VM{ state: state, @@ -906,7 +907,7 @@ func TestServiceGetBlockByHeight(t *testing.T) { state := state.NewMockState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(blockID, nil) - manager := blockexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(nil, database.ErrNotFound) return &Service{ vm: &VM{ @@ -930,7 +931,7 @@ func TestServiceGetBlockByHeight(t *testing.T) { state := state.NewMockState(ctrl) state.EXPECT().GetBlockIDAtHeight(blockHeight).Return(blockID, nil) - manager := blockexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -958,7 +959,7 @@ func TestServiceGetBlockByHeight(t *testing.T) { expected, err := formatting.Encode(formatting.Hex, blockBytes) require.NoError(t, err) - manager := blockexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -986,7 +987,7 @@ func TestServiceGetBlockByHeight(t *testing.T) { expected, err := formatting.Encode(formatting.HexC, blockBytes) require.NoError(t, err) - manager := blockexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ @@ -1014,7 +1015,7 @@ func TestServiceGetBlockByHeight(t *testing.T) { expected, err := formatting.Encode(formatting.HexNC, blockBytes) require.NoError(t, err) - manager := blockexecutor.NewMockManager(ctrl) + manager := executormock.NewManager(ctrl) manager.EXPECT().GetStatelessBlock(blockID).Return(block, nil) return &Service{ vm: &VM{ diff --git a/vms/platformvm/signer/mock_signer.go b/vms/platformvm/signer/signermock/signer.go similarity index 52% rename from vms/platformvm/signer/mock_signer.go rename to vms/platformvm/signer/signermock/signer.go index 04c5100e9488..a6d6f3c24011 100644 --- a/vms/platformvm/signer/mock_signer.go +++ b/vms/platformvm/signer/signermock/signer.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -source=vms/platformvm/signer/signer.go -destination=vms/platformvm/signer/mock_signer.go -package=signer -exclude_interfaces= +// mockgen -source=vms/platformvm/signer/signer.go -destination=vms/platformvm/signer/signermock/signer.go -package=signermock -exclude_interfaces= -mock_names=Signer=Signer // -// Package signer is a generated GoMock package. -package signer +// Package signermock is a generated GoMock package. +package signermock import ( reflect "reflect" @@ -16,31 +16,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockSigner is a mock of Signer interface. -type MockSigner struct { +// Signer is a mock of Signer interface. +type Signer struct { ctrl *gomock.Controller - recorder *MockSignerMockRecorder + recorder *SignerMockRecorder } -// MockSignerMockRecorder is the mock recorder for MockSigner. -type MockSignerMockRecorder struct { - mock *MockSigner +// SignerMockRecorder is the mock recorder for Signer. +type SignerMockRecorder struct { + mock *Signer } -// NewMockSigner creates a new mock instance. -func NewMockSigner(ctrl *gomock.Controller) *MockSigner { - mock := &MockSigner{ctrl: ctrl} - mock.recorder = &MockSignerMockRecorder{mock} +// NewSigner creates a new mock instance. +func NewSigner(ctrl *gomock.Controller) *Signer { + mock := &Signer{ctrl: ctrl} + mock.recorder = &SignerMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockSigner) EXPECT() *MockSignerMockRecorder { +func (m *Signer) EXPECT() *SignerMockRecorder { return m.recorder } // Key mocks base method. -func (m *MockSigner) Key() *bls.PublicKey { +func (m *Signer) Key() *bls.PublicKey { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Key") ret0, _ := ret[0].(*bls.PublicKey) @@ -48,13 +48,13 @@ func (m *MockSigner) Key() *bls.PublicKey { } // Key indicates an expected call of Key. -func (mr *MockSignerMockRecorder) Key() *gomock.Call { +func (mr *SignerMockRecorder) Key() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Key", reflect.TypeOf((*MockSigner)(nil).Key)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Key", reflect.TypeOf((*Signer)(nil).Key)) } // Verify mocks base method. -func (m *MockSigner) Verify() error { +func (m *Signer) Verify() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Verify") ret0, _ := ret[0].(error) @@ -62,7 +62,7 @@ func (m *MockSigner) Verify() error { } // Verify indicates an expected call of Verify. -func (mr *MockSignerMockRecorder) Verify() *gomock.Call { +func (mr *SignerMockRecorder) Verify() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*MockSigner)(nil).Verify)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Verify", reflect.TypeOf((*Signer)(nil).Verify)) } diff --git a/vms/platformvm/stakeable/stakeable_lock_test.go b/vms/platformvm/stakeable/stakeable_lock_test.go index 352137c007f3..4ec43c623ec1 100644 --- a/vms/platformvm/stakeable/stakeable_lock_test.go +++ b/vms/platformvm/stakeable/stakeable_lock_test.go @@ -11,6 +11,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/components/avax/avaxmock" ) var errTest = errors.New("hi mom") @@ -26,7 +27,7 @@ func TestLockOutVerify(t *testing.T) { name: "happy path", locktime: 1, transferableOutF: func(ctrl *gomock.Controller) avax.TransferableOut { - o := avax.NewMockTransferableOut(ctrl) + o := avaxmock.NewTransferableOut(ctrl) o.EXPECT().Verify().Return(nil) return o }, @@ -52,7 +53,7 @@ func TestLockOutVerify(t *testing.T) { name: "inner output fails verification", locktime: 1, transferableOutF: func(ctrl *gomock.Controller) avax.TransferableOut { - o := avax.NewMockTransferableOut(ctrl) + o := avaxmock.NewTransferableOut(ctrl) o.EXPECT().Verify().Return(errTest) return o }, @@ -84,7 +85,7 @@ func TestLockInVerify(t *testing.T) { name: "happy path", locktime: 1, transferableInF: func(ctrl *gomock.Controller) avax.TransferableIn { - o := avax.NewMockTransferableIn(ctrl) + o := avaxmock.NewTransferableIn(ctrl) o.EXPECT().Verify().Return(nil) return o }, @@ -110,7 +111,7 @@ func TestLockInVerify(t *testing.T) { name: "inner input fails verification", locktime: 1, transferableInF: func(ctrl *gomock.Controller) avax.TransferableIn { - o := avax.NewMockTransferableIn(ctrl) + o := avaxmock.NewTransferableIn(ctrl) o.EXPECT().Verify().Return(errTest) return o }, diff --git a/vms/platformvm/state/diff_test.go b/vms/platformvm/state/diff_test.go index edb8e627e5b3..cf3b2793ad8d 100644 --- a/vms/platformvm/state/diff_test.go +++ b/vms/platformvm/state/diff_test.go @@ -17,7 +17,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" - "github.com/ava-labs/avalanchego/vms/platformvm/fx" + "github.com/ava-labs/avalanchego/vms/platformvm/fx/fxmock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) @@ -94,7 +94,6 @@ func TestDiffCurrentSupply(t *testing.T) { func TestDiffCurrentValidator(t *testing.T) { require := require.New(t) - ctrl := gomock.NewController(t) state := NewMockState(ctrl) @@ -262,7 +261,7 @@ func TestDiffSubnet(t *testing.T) { // Initialize parent with one subnet parentStateCreateSubnetTx := &txs.Tx{ Unsigned: &txs.CreateSubnetTx{ - Owner: fx.NewMockOwner(ctrl), + Owner: fxmock.NewOwner(ctrl), }, } state.AddSubnet(parentStateCreateSubnetTx.ID()) @@ -283,7 +282,7 @@ func TestDiffSubnet(t *testing.T) { // Put a subnet createSubnetTx := &txs.Tx{ Unsigned: &txs.CreateSubnetTx{ - Owner: fx.NewMockOwner(ctrl), + Owner: fxmock.NewOwner(ctrl), }, } diff.AddSubnet(createSubnetTx.ID()) @@ -535,8 +534,8 @@ func TestDiffSubnetOwner(t *testing.T) { state := newTestState(t, memdb.New()) var ( - owner1 = fx.NewMockOwner(ctrl) - owner2 = fx.NewMockOwner(ctrl) + owner1 = fxmock.NewOwner(ctrl) + owner2 = fxmock.NewOwner(ctrl) createSubnetTx = &txs.Tx{ Unsigned: &txs.CreateSubnetTx{ @@ -635,9 +634,9 @@ func TestDiffStacking(t *testing.T) { state := newTestState(t, memdb.New()) var ( - owner1 = fx.NewMockOwner(ctrl) - owner2 = fx.NewMockOwner(ctrl) - owner3 = fx.NewMockOwner(ctrl) + owner1 = fxmock.NewOwner(ctrl) + owner2 = fxmock.NewOwner(ctrl) + owner3 = fxmock.NewOwner(ctrl) createSubnetTx = &txs.Tx{ Unsigned: &txs.CreateSubnetTx{ diff --git a/vms/platformvm/state/mock_staker_iterator.go b/vms/platformvm/state/mock_staker_iterator.go index 62ba31d8b1c6..0129198c1f57 100644 --- a/vms/platformvm/state/mock_staker_iterator.go +++ b/vms/platformvm/state/mock_staker_iterator.go @@ -1,9 +1,9 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/platformvm/state (interfaces: StakerIterator) +// Source: vms/platformvm/state/staker.go // // Generated by this command: // -// mockgen -package=state -destination=vms/platformvm/state/mock_staker_iterator.go github.com/ava-labs/avalanchego/vms/platformvm/state StakerIterator +// mockgen -source=vms/platformvm/state/staker.go -destination=vms/platformvm/state/mock_staker_iterator.go -package=state -exclude_interfaces= -mock_names=MockStakerIterator=MockStakerIterator // // Package state is a generated GoMock package. diff --git a/vms/platformvm/state/mock_state.go b/vms/platformvm/state/mock_state.go index f6540df730dc..a565ce2ff4f7 100644 --- a/vms/platformvm/state/mock_state.go +++ b/vms/platformvm/state/mock_state.go @@ -1,9 +1,9 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/platformvm/state (interfaces: Chain,Diff,State) +// Source: vms/platformvm/state/state.go // // Generated by this command: // -// mockgen -package=state -destination=vms/platformvm/state/mock_state.go github.com/ava-labs/avalanchego/vms/platformvm/state Chain,Diff,State +// mockgen -source=vms/platformvm/state/state.go -destination=vms/platformvm/state/mock_state.go -package=state -exclude_interfaces=Chain -mock_names=MockState=MockState // // Package state is a generated GoMock package. @@ -28,1024 +28,6 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockChain is a mock of Chain interface. -type MockChain struct { - ctrl *gomock.Controller - recorder *MockChainMockRecorder -} - -// MockChainMockRecorder is the mock recorder for MockChain. -type MockChainMockRecorder struct { - mock *MockChain -} - -// NewMockChain creates a new mock instance. -func NewMockChain(ctrl *gomock.Controller) *MockChain { - mock := &MockChain{ctrl: ctrl} - mock.recorder = &MockChainMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockChain) EXPECT() *MockChainMockRecorder { - return m.recorder -} - -// AddChain mocks base method. -func (m *MockChain) AddChain(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddChain", arg0) -} - -// AddChain indicates an expected call of AddChain. -func (mr *MockChainMockRecorder) AddChain(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*MockChain)(nil).AddChain), arg0) -} - -// AddRewardUTXO mocks base method. -func (m *MockChain) AddRewardUTXO(arg0 ids.ID, arg1 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddRewardUTXO", arg0, arg1) -} - -// AddRewardUTXO indicates an expected call of AddRewardUTXO. -func (mr *MockChainMockRecorder) AddRewardUTXO(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*MockChain)(nil).AddRewardUTXO), arg0, arg1) -} - -// AddSubnet mocks base method. -func (m *MockChain) AddSubnet(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnet", arg0) -} - -// AddSubnet indicates an expected call of AddSubnet. -func (mr *MockChainMockRecorder) AddSubnet(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*MockChain)(nil).AddSubnet), arg0) -} - -// AddSubnetTransformation mocks base method. -func (m *MockChain) AddSubnetTransformation(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnetTransformation", arg0) -} - -// AddSubnetTransformation indicates an expected call of AddSubnetTransformation. -func (mr *MockChainMockRecorder) AddSubnetTransformation(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*MockChain)(nil).AddSubnetTransformation), arg0) -} - -// AddTx mocks base method. -func (m *MockChain) AddTx(arg0 *txs.Tx, arg1 status.Status) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddTx", arg0, arg1) -} - -// AddTx indicates an expected call of AddTx. -func (mr *MockChainMockRecorder) AddTx(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockChain)(nil).AddTx), arg0, arg1) -} - -// AddUTXO mocks base method. -func (m *MockChain) AddUTXO(arg0 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddUTXO", arg0) -} - -// AddUTXO indicates an expected call of AddUTXO. -func (mr *MockChainMockRecorder) AddUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockChain)(nil).AddUTXO), arg0) -} - -// DeleteCurrentDelegator mocks base method. -func (m *MockChain) DeleteCurrentDelegator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentDelegator", arg0) -} - -// DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. -func (mr *MockChainMockRecorder) DeleteCurrentDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*MockChain)(nil).DeleteCurrentDelegator), arg0) -} - -// DeleteCurrentValidator mocks base method. -func (m *MockChain) DeleteCurrentValidator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentValidator", arg0) -} - -// DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. -func (mr *MockChainMockRecorder) DeleteCurrentValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*MockChain)(nil).DeleteCurrentValidator), arg0) -} - -// DeletePendingDelegator mocks base method. -func (m *MockChain) DeletePendingDelegator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingDelegator", arg0) -} - -// DeletePendingDelegator indicates an expected call of DeletePendingDelegator. -func (mr *MockChainMockRecorder) DeletePendingDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*MockChain)(nil).DeletePendingDelegator), arg0) -} - -// DeletePendingValidator mocks base method. -func (m *MockChain) DeletePendingValidator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingValidator", arg0) -} - -// DeletePendingValidator indicates an expected call of DeletePendingValidator. -func (mr *MockChainMockRecorder) DeletePendingValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*MockChain)(nil).DeletePendingValidator), arg0) -} - -// DeleteUTXO mocks base method. -func (m *MockChain) DeleteUTXO(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteUTXO", arg0) -} - -// DeleteUTXO indicates an expected call of DeleteUTXO. -func (mr *MockChainMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockChain)(nil).DeleteUTXO), arg0) -} - -// GetCurrentDelegatorIterator mocks base method. -func (m *MockChain) GetCurrentDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", arg0, arg1) - ret0, _ := ret[0].(StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. -func (mr *MockChainMockRecorder) GetCurrentDelegatorIterator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*MockChain)(nil).GetCurrentDelegatorIterator), arg0, arg1) -} - -// GetCurrentStakerIterator mocks base method. -func (m *MockChain) GetCurrentStakerIterator() (StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentStakerIterator") - ret0, _ := ret[0].(StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentStakerIterator indicates an expected call of GetCurrentStakerIterator. -func (mr *MockChainMockRecorder) GetCurrentStakerIterator() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentStakerIterator", reflect.TypeOf((*MockChain)(nil).GetCurrentStakerIterator)) -} - -// GetCurrentSupply mocks base method. -func (m *MockChain) GetCurrentSupply(arg0 ids.ID) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentSupply", arg0) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentSupply indicates an expected call of GetCurrentSupply. -func (mr *MockChainMockRecorder) GetCurrentSupply(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*MockChain)(nil).GetCurrentSupply), arg0) -} - -// GetCurrentValidator mocks base method. -func (m *MockChain) GetCurrentValidator(arg0 ids.ID, arg1 ids.NodeID) (*Staker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentValidator", arg0, arg1) - ret0, _ := ret[0].(*Staker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentValidator indicates an expected call of GetCurrentValidator. -func (mr *MockChainMockRecorder) GetCurrentValidator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*MockChain)(nil).GetCurrentValidator), arg0, arg1) -} - -// GetDelegateeReward mocks base method. -func (m *MockChain) GetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDelegateeReward", arg0, arg1) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetDelegateeReward indicates an expected call of GetDelegateeReward. -func (mr *MockChainMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*MockChain)(nil).GetDelegateeReward), arg0, arg1) -} - -// GetFeeState mocks base method. -func (m *MockChain) GetFeeState() gas.State { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetFeeState") - ret0, _ := ret[0].(gas.State) - return ret0 -} - -// GetFeeState indicates an expected call of GetFeeState. -func (mr *MockChainMockRecorder) GetFeeState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeeState", reflect.TypeOf((*MockChain)(nil).GetFeeState)) -} - -// GetPendingDelegatorIterator mocks base method. -func (m *MockChain) GetPendingDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", arg0, arg1) - ret0, _ := ret[0].(StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. -func (mr *MockChainMockRecorder) GetPendingDelegatorIterator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*MockChain)(nil).GetPendingDelegatorIterator), arg0, arg1) -} - -// GetPendingStakerIterator mocks base method. -func (m *MockChain) GetPendingStakerIterator() (StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingStakerIterator") - ret0, _ := ret[0].(StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingStakerIterator indicates an expected call of GetPendingStakerIterator. -func (mr *MockChainMockRecorder) GetPendingStakerIterator() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingStakerIterator", reflect.TypeOf((*MockChain)(nil).GetPendingStakerIterator)) -} - -// GetPendingValidator mocks base method. -func (m *MockChain) GetPendingValidator(arg0 ids.ID, arg1 ids.NodeID) (*Staker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingValidator", arg0, arg1) - ret0, _ := ret[0].(*Staker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingValidator indicates an expected call of GetPendingValidator. -func (mr *MockChainMockRecorder) GetPendingValidator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*MockChain)(nil).GetPendingValidator), arg0, arg1) -} - -// GetSubnetManager mocks base method. -func (m *MockChain) GetSubnetManager(arg0 ids.ID) (ids.ID, []byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetManager", arg0) - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].([]byte) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetSubnetManager indicates an expected call of GetSubnetManager. -func (mr *MockChainMockRecorder) GetSubnetManager(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*MockChain)(nil).GetSubnetManager), arg0) -} - -// GetSubnetOwner mocks base method. -func (m *MockChain) GetSubnetOwner(arg0 ids.ID) (fx.Owner, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetOwner", arg0) - ret0, _ := ret[0].(fx.Owner) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubnetOwner indicates an expected call of GetSubnetOwner. -func (mr *MockChainMockRecorder) GetSubnetOwner(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*MockChain)(nil).GetSubnetOwner), arg0) -} - -// GetSubnetTransformation mocks base method. -func (m *MockChain) GetSubnetTransformation(arg0 ids.ID) (*txs.Tx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetTransformation", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubnetTransformation indicates an expected call of GetSubnetTransformation. -func (mr *MockChainMockRecorder) GetSubnetTransformation(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*MockChain)(nil).GetSubnetTransformation), arg0) -} - -// GetTimestamp mocks base method. -func (m *MockChain) GetTimestamp() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTimestamp") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// GetTimestamp indicates an expected call of GetTimestamp. -func (mr *MockChainMockRecorder) GetTimestamp() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*MockChain)(nil).GetTimestamp)) -} - -// GetTx mocks base method. -func (m *MockChain) GetTx(arg0 ids.ID) (*txs.Tx, status.Status, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTx", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(status.Status) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetTx indicates an expected call of GetTx. -func (mr *MockChainMockRecorder) GetTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockChain)(nil).GetTx), arg0) -} - -// GetUTXO mocks base method. -func (m *MockChain) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUTXO", arg0) - ret0, _ := ret[0].(*avax.UTXO) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUTXO indicates an expected call of GetUTXO. -func (mr *MockChainMockRecorder) GetUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockChain)(nil).GetUTXO), arg0) -} - -// PutCurrentDelegator mocks base method. -func (m *MockChain) PutCurrentDelegator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentDelegator", arg0) -} - -// PutCurrentDelegator indicates an expected call of PutCurrentDelegator. -func (mr *MockChainMockRecorder) PutCurrentDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*MockChain)(nil).PutCurrentDelegator), arg0) -} - -// PutCurrentValidator mocks base method. -func (m *MockChain) PutCurrentValidator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentValidator", arg0) -} - -// PutCurrentValidator indicates an expected call of PutCurrentValidator. -func (mr *MockChainMockRecorder) PutCurrentValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*MockChain)(nil).PutCurrentValidator), arg0) -} - -// PutPendingDelegator mocks base method. -func (m *MockChain) PutPendingDelegator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingDelegator", arg0) -} - -// PutPendingDelegator indicates an expected call of PutPendingDelegator. -func (mr *MockChainMockRecorder) PutPendingDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*MockChain)(nil).PutPendingDelegator), arg0) -} - -// PutPendingValidator mocks base method. -func (m *MockChain) PutPendingValidator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingValidator", arg0) -} - -// PutPendingValidator indicates an expected call of PutPendingValidator. -func (mr *MockChainMockRecorder) PutPendingValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*MockChain)(nil).PutPendingValidator), arg0) -} - -// SetCurrentSupply mocks base method. -func (m *MockChain) SetCurrentSupply(arg0 ids.ID, arg1 uint64) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetCurrentSupply", arg0, arg1) -} - -// SetCurrentSupply indicates an expected call of SetCurrentSupply. -func (mr *MockChainMockRecorder) SetCurrentSupply(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*MockChain)(nil).SetCurrentSupply), arg0, arg1) -} - -// SetDelegateeReward mocks base method. -func (m *MockChain) SetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID, arg2 uint64) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetDelegateeReward", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetDelegateeReward indicates an expected call of SetDelegateeReward. -func (mr *MockChainMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*MockChain)(nil).SetDelegateeReward), arg0, arg1, arg2) -} - -// SetFeeState mocks base method. -func (m *MockChain) SetFeeState(arg0 gas.State) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetFeeState", arg0) -} - -// SetFeeState indicates an expected call of SetFeeState. -func (mr *MockChainMockRecorder) SetFeeState(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*MockChain)(nil).SetFeeState), arg0) -} - -// SetSubnetManager mocks base method. -func (m *MockChain) SetSubnetManager(arg0, arg1 ids.ID, arg2 []byte) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetManager", arg0, arg1, arg2) -} - -// SetSubnetManager indicates an expected call of SetSubnetManager. -func (mr *MockChainMockRecorder) SetSubnetManager(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*MockChain)(nil).SetSubnetManager), arg0, arg1, arg2) -} - -// SetSubnetOwner mocks base method. -func (m *MockChain) SetSubnetOwner(arg0 ids.ID, arg1 fx.Owner) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetOwner", arg0, arg1) -} - -// SetSubnetOwner indicates an expected call of SetSubnetOwner. -func (mr *MockChainMockRecorder) SetSubnetOwner(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*MockChain)(nil).SetSubnetOwner), arg0, arg1) -} - -// SetTimestamp mocks base method. -func (m *MockChain) SetTimestamp(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimestamp", arg0) -} - -// SetTimestamp indicates an expected call of SetTimestamp. -func (mr *MockChainMockRecorder) SetTimestamp(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockChain)(nil).SetTimestamp), arg0) -} - -// MockDiff is a mock of Diff interface. -type MockDiff struct { - ctrl *gomock.Controller - recorder *MockDiffMockRecorder -} - -// MockDiffMockRecorder is the mock recorder for MockDiff. -type MockDiffMockRecorder struct { - mock *MockDiff -} - -// NewMockDiff creates a new mock instance. -func NewMockDiff(ctrl *gomock.Controller) *MockDiff { - mock := &MockDiff{ctrl: ctrl} - mock.recorder = &MockDiffMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockDiff) EXPECT() *MockDiffMockRecorder { - return m.recorder -} - -// AddChain mocks base method. -func (m *MockDiff) AddChain(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddChain", arg0) -} - -// AddChain indicates an expected call of AddChain. -func (mr *MockDiffMockRecorder) AddChain(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*MockDiff)(nil).AddChain), arg0) -} - -// AddRewardUTXO mocks base method. -func (m *MockDiff) AddRewardUTXO(arg0 ids.ID, arg1 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddRewardUTXO", arg0, arg1) -} - -// AddRewardUTXO indicates an expected call of AddRewardUTXO. -func (mr *MockDiffMockRecorder) AddRewardUTXO(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*MockDiff)(nil).AddRewardUTXO), arg0, arg1) -} - -// AddSubnet mocks base method. -func (m *MockDiff) AddSubnet(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnet", arg0) -} - -// AddSubnet indicates an expected call of AddSubnet. -func (mr *MockDiffMockRecorder) AddSubnet(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*MockDiff)(nil).AddSubnet), arg0) -} - -// AddSubnetTransformation mocks base method. -func (m *MockDiff) AddSubnetTransformation(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnetTransformation", arg0) -} - -// AddSubnetTransformation indicates an expected call of AddSubnetTransformation. -func (mr *MockDiffMockRecorder) AddSubnetTransformation(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*MockDiff)(nil).AddSubnetTransformation), arg0) -} - -// AddTx mocks base method. -func (m *MockDiff) AddTx(arg0 *txs.Tx, arg1 status.Status) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddTx", arg0, arg1) -} - -// AddTx indicates an expected call of AddTx. -func (mr *MockDiffMockRecorder) AddTx(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockDiff)(nil).AddTx), arg0, arg1) -} - -// AddUTXO mocks base method. -func (m *MockDiff) AddUTXO(arg0 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddUTXO", arg0) -} - -// AddUTXO indicates an expected call of AddUTXO. -func (mr *MockDiffMockRecorder) AddUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockDiff)(nil).AddUTXO), arg0) -} - -// Apply mocks base method. -func (m *MockDiff) Apply(arg0 Chain) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Apply", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// Apply indicates an expected call of Apply. -func (mr *MockDiffMockRecorder) Apply(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockDiff)(nil).Apply), arg0) -} - -// DeleteCurrentDelegator mocks base method. -func (m *MockDiff) DeleteCurrentDelegator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentDelegator", arg0) -} - -// DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. -func (mr *MockDiffMockRecorder) DeleteCurrentDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*MockDiff)(nil).DeleteCurrentDelegator), arg0) -} - -// DeleteCurrentValidator mocks base method. -func (m *MockDiff) DeleteCurrentValidator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentValidator", arg0) -} - -// DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. -func (mr *MockDiffMockRecorder) DeleteCurrentValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*MockDiff)(nil).DeleteCurrentValidator), arg0) -} - -// DeletePendingDelegator mocks base method. -func (m *MockDiff) DeletePendingDelegator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingDelegator", arg0) -} - -// DeletePendingDelegator indicates an expected call of DeletePendingDelegator. -func (mr *MockDiffMockRecorder) DeletePendingDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*MockDiff)(nil).DeletePendingDelegator), arg0) -} - -// DeletePendingValidator mocks base method. -func (m *MockDiff) DeletePendingValidator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingValidator", arg0) -} - -// DeletePendingValidator indicates an expected call of DeletePendingValidator. -func (mr *MockDiffMockRecorder) DeletePendingValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*MockDiff)(nil).DeletePendingValidator), arg0) -} - -// DeleteUTXO mocks base method. -func (m *MockDiff) DeleteUTXO(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteUTXO", arg0) -} - -// DeleteUTXO indicates an expected call of DeleteUTXO. -func (mr *MockDiffMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockDiff)(nil).DeleteUTXO), arg0) -} - -// GetCurrentDelegatorIterator mocks base method. -func (m *MockDiff) GetCurrentDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", arg0, arg1) - ret0, _ := ret[0].(StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. -func (mr *MockDiffMockRecorder) GetCurrentDelegatorIterator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*MockDiff)(nil).GetCurrentDelegatorIterator), arg0, arg1) -} - -// GetCurrentStakerIterator mocks base method. -func (m *MockDiff) GetCurrentStakerIterator() (StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentStakerIterator") - ret0, _ := ret[0].(StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentStakerIterator indicates an expected call of GetCurrentStakerIterator. -func (mr *MockDiffMockRecorder) GetCurrentStakerIterator() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentStakerIterator", reflect.TypeOf((*MockDiff)(nil).GetCurrentStakerIterator)) -} - -// GetCurrentSupply mocks base method. -func (m *MockDiff) GetCurrentSupply(arg0 ids.ID) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentSupply", arg0) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentSupply indicates an expected call of GetCurrentSupply. -func (mr *MockDiffMockRecorder) GetCurrentSupply(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*MockDiff)(nil).GetCurrentSupply), arg0) -} - -// GetCurrentValidator mocks base method. -func (m *MockDiff) GetCurrentValidator(arg0 ids.ID, arg1 ids.NodeID) (*Staker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentValidator", arg0, arg1) - ret0, _ := ret[0].(*Staker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentValidator indicates an expected call of GetCurrentValidator. -func (mr *MockDiffMockRecorder) GetCurrentValidator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*MockDiff)(nil).GetCurrentValidator), arg0, arg1) -} - -// GetDelegateeReward mocks base method. -func (m *MockDiff) GetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDelegateeReward", arg0, arg1) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetDelegateeReward indicates an expected call of GetDelegateeReward. -func (mr *MockDiffMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*MockDiff)(nil).GetDelegateeReward), arg0, arg1) -} - -// GetFeeState mocks base method. -func (m *MockDiff) GetFeeState() gas.State { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetFeeState") - ret0, _ := ret[0].(gas.State) - return ret0 -} - -// GetFeeState indicates an expected call of GetFeeState. -func (mr *MockDiffMockRecorder) GetFeeState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeeState", reflect.TypeOf((*MockDiff)(nil).GetFeeState)) -} - -// GetPendingDelegatorIterator mocks base method. -func (m *MockDiff) GetPendingDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", arg0, arg1) - ret0, _ := ret[0].(StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. -func (mr *MockDiffMockRecorder) GetPendingDelegatorIterator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*MockDiff)(nil).GetPendingDelegatorIterator), arg0, arg1) -} - -// GetPendingStakerIterator mocks base method. -func (m *MockDiff) GetPendingStakerIterator() (StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingStakerIterator") - ret0, _ := ret[0].(StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingStakerIterator indicates an expected call of GetPendingStakerIterator. -func (mr *MockDiffMockRecorder) GetPendingStakerIterator() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingStakerIterator", reflect.TypeOf((*MockDiff)(nil).GetPendingStakerIterator)) -} - -// GetPendingValidator mocks base method. -func (m *MockDiff) GetPendingValidator(arg0 ids.ID, arg1 ids.NodeID) (*Staker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingValidator", arg0, arg1) - ret0, _ := ret[0].(*Staker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingValidator indicates an expected call of GetPendingValidator. -func (mr *MockDiffMockRecorder) GetPendingValidator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*MockDiff)(nil).GetPendingValidator), arg0, arg1) -} - -// GetSubnetManager mocks base method. -func (m *MockDiff) GetSubnetManager(arg0 ids.ID) (ids.ID, []byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetManager", arg0) - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].([]byte) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetSubnetManager indicates an expected call of GetSubnetManager. -func (mr *MockDiffMockRecorder) GetSubnetManager(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*MockDiff)(nil).GetSubnetManager), arg0) -} - -// GetSubnetOwner mocks base method. -func (m *MockDiff) GetSubnetOwner(arg0 ids.ID) (fx.Owner, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetOwner", arg0) - ret0, _ := ret[0].(fx.Owner) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubnetOwner indicates an expected call of GetSubnetOwner. -func (mr *MockDiffMockRecorder) GetSubnetOwner(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*MockDiff)(nil).GetSubnetOwner), arg0) -} - -// GetSubnetTransformation mocks base method. -func (m *MockDiff) GetSubnetTransformation(arg0 ids.ID) (*txs.Tx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetTransformation", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubnetTransformation indicates an expected call of GetSubnetTransformation. -func (mr *MockDiffMockRecorder) GetSubnetTransformation(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*MockDiff)(nil).GetSubnetTransformation), arg0) -} - -// GetTimestamp mocks base method. -func (m *MockDiff) GetTimestamp() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTimestamp") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// GetTimestamp indicates an expected call of GetTimestamp. -func (mr *MockDiffMockRecorder) GetTimestamp() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*MockDiff)(nil).GetTimestamp)) -} - -// GetTx mocks base method. -func (m *MockDiff) GetTx(arg0 ids.ID) (*txs.Tx, status.Status, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTx", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(status.Status) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetTx indicates an expected call of GetTx. -func (mr *MockDiffMockRecorder) GetTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockDiff)(nil).GetTx), arg0) -} - -// GetUTXO mocks base method. -func (m *MockDiff) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUTXO", arg0) - ret0, _ := ret[0].(*avax.UTXO) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUTXO indicates an expected call of GetUTXO. -func (mr *MockDiffMockRecorder) GetUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockDiff)(nil).GetUTXO), arg0) -} - -// PutCurrentDelegator mocks base method. -func (m *MockDiff) PutCurrentDelegator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentDelegator", arg0) -} - -// PutCurrentDelegator indicates an expected call of PutCurrentDelegator. -func (mr *MockDiffMockRecorder) PutCurrentDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*MockDiff)(nil).PutCurrentDelegator), arg0) -} - -// PutCurrentValidator mocks base method. -func (m *MockDiff) PutCurrentValidator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentValidator", arg0) -} - -// PutCurrentValidator indicates an expected call of PutCurrentValidator. -func (mr *MockDiffMockRecorder) PutCurrentValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*MockDiff)(nil).PutCurrentValidator), arg0) -} - -// PutPendingDelegator mocks base method. -func (m *MockDiff) PutPendingDelegator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingDelegator", arg0) -} - -// PutPendingDelegator indicates an expected call of PutPendingDelegator. -func (mr *MockDiffMockRecorder) PutPendingDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*MockDiff)(nil).PutPendingDelegator), arg0) -} - -// PutPendingValidator mocks base method. -func (m *MockDiff) PutPendingValidator(arg0 *Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingValidator", arg0) -} - -// PutPendingValidator indicates an expected call of PutPendingValidator. -func (mr *MockDiffMockRecorder) PutPendingValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*MockDiff)(nil).PutPendingValidator), arg0) -} - -// SetCurrentSupply mocks base method. -func (m *MockDiff) SetCurrentSupply(arg0 ids.ID, arg1 uint64) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetCurrentSupply", arg0, arg1) -} - -// SetCurrentSupply indicates an expected call of SetCurrentSupply. -func (mr *MockDiffMockRecorder) SetCurrentSupply(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*MockDiff)(nil).SetCurrentSupply), arg0, arg1) -} - -// SetDelegateeReward mocks base method. -func (m *MockDiff) SetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID, arg2 uint64) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetDelegateeReward", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetDelegateeReward indicates an expected call of SetDelegateeReward. -func (mr *MockDiffMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*MockDiff)(nil).SetDelegateeReward), arg0, arg1, arg2) -} - -// SetFeeState mocks base method. -func (m *MockDiff) SetFeeState(arg0 gas.State) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetFeeState", arg0) -} - -// SetFeeState indicates an expected call of SetFeeState. -func (mr *MockDiffMockRecorder) SetFeeState(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*MockDiff)(nil).SetFeeState), arg0) -} - -// SetSubnetManager mocks base method. -func (m *MockDiff) SetSubnetManager(arg0, arg1 ids.ID, arg2 []byte) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetManager", arg0, arg1, arg2) -} - -// SetSubnetManager indicates an expected call of SetSubnetManager. -func (mr *MockDiffMockRecorder) SetSubnetManager(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*MockDiff)(nil).SetSubnetManager), arg0, arg1, arg2) -} - -// SetSubnetOwner mocks base method. -func (m *MockDiff) SetSubnetOwner(arg0 ids.ID, arg1 fx.Owner) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetOwner", arg0, arg1) -} - -// SetSubnetOwner indicates an expected call of SetSubnetOwner. -func (mr *MockDiffMockRecorder) SetSubnetOwner(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*MockDiff)(nil).SetSubnetOwner), arg0, arg1) -} - -// SetTimestamp mocks base method. -func (m *MockDiff) SetTimestamp(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimestamp", arg0) -} - -// SetTimestamp indicates an expected call of SetTimestamp. -func (mr *MockDiffMockRecorder) SetTimestamp(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockDiff)(nil).SetTimestamp), arg0) -} - // MockState is a mock of State interface. type MockState struct { ctrl *gomock.Controller @@ -1082,115 +64,115 @@ func (mr *MockStateMockRecorder) Abort() *gomock.Call { } // AddChain mocks base method. -func (m *MockState) AddChain(arg0 *txs.Tx) { +func (m *MockState) AddChain(createChainTx *txs.Tx) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddChain", arg0) + m.ctrl.Call(m, "AddChain", createChainTx) } // AddChain indicates an expected call of AddChain. -func (mr *MockStateMockRecorder) AddChain(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) AddChain(createChainTx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*MockState)(nil).AddChain), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*MockState)(nil).AddChain), createChainTx) } // AddRewardUTXO mocks base method. -func (m *MockState) AddRewardUTXO(arg0 ids.ID, arg1 *avax.UTXO) { +func (m *MockState) AddRewardUTXO(txID ids.ID, utxo *avax.UTXO) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddRewardUTXO", arg0, arg1) + m.ctrl.Call(m, "AddRewardUTXO", txID, utxo) } // AddRewardUTXO indicates an expected call of AddRewardUTXO. -func (mr *MockStateMockRecorder) AddRewardUTXO(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) AddRewardUTXO(txID, utxo any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*MockState)(nil).AddRewardUTXO), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*MockState)(nil).AddRewardUTXO), txID, utxo) } // AddStatelessBlock mocks base method. -func (m *MockState) AddStatelessBlock(arg0 block.Block) { +func (m *MockState) AddStatelessBlock(block block.Block) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddStatelessBlock", arg0) + m.ctrl.Call(m, "AddStatelessBlock", block) } // AddStatelessBlock indicates an expected call of AddStatelessBlock. -func (mr *MockStateMockRecorder) AddStatelessBlock(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) AddStatelessBlock(block any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddStatelessBlock", reflect.TypeOf((*MockState)(nil).AddStatelessBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddStatelessBlock", reflect.TypeOf((*MockState)(nil).AddStatelessBlock), block) } // AddSubnet mocks base method. -func (m *MockState) AddSubnet(arg0 ids.ID) { +func (m *MockState) AddSubnet(subnetID ids.ID) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnet", arg0) + m.ctrl.Call(m, "AddSubnet", subnetID) } // AddSubnet indicates an expected call of AddSubnet. -func (mr *MockStateMockRecorder) AddSubnet(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) AddSubnet(subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*MockState)(nil).AddSubnet), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*MockState)(nil).AddSubnet), subnetID) } // AddSubnetTransformation mocks base method. -func (m *MockState) AddSubnetTransformation(arg0 *txs.Tx) { +func (m *MockState) AddSubnetTransformation(transformSubnetTx *txs.Tx) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnetTransformation", arg0) + m.ctrl.Call(m, "AddSubnetTransformation", transformSubnetTx) } // AddSubnetTransformation indicates an expected call of AddSubnetTransformation. -func (mr *MockStateMockRecorder) AddSubnetTransformation(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) AddSubnetTransformation(transformSubnetTx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*MockState)(nil).AddSubnetTransformation), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*MockState)(nil).AddSubnetTransformation), transformSubnetTx) } // AddTx mocks base method. -func (m *MockState) AddTx(arg0 *txs.Tx, arg1 status.Status) { +func (m *MockState) AddTx(tx *txs.Tx, status status.Status) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddTx", arg0, arg1) + m.ctrl.Call(m, "AddTx", tx, status) } // AddTx indicates an expected call of AddTx. -func (mr *MockStateMockRecorder) AddTx(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) AddTx(tx, status any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockState)(nil).AddTx), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockState)(nil).AddTx), tx, status) } // AddUTXO mocks base method. -func (m *MockState) AddUTXO(arg0 *avax.UTXO) { +func (m *MockState) AddUTXO(utxo *avax.UTXO) { m.ctrl.T.Helper() - m.ctrl.Call(m, "AddUTXO", arg0) + m.ctrl.Call(m, "AddUTXO", utxo) } // AddUTXO indicates an expected call of AddUTXO. -func (mr *MockStateMockRecorder) AddUTXO(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) AddUTXO(utxo any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockState)(nil).AddUTXO), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockState)(nil).AddUTXO), utxo) } // ApplyValidatorPublicKeyDiffs mocks base method. -func (m *MockState) ApplyValidatorPublicKeyDiffs(arg0 context.Context, arg1 map[ids.NodeID]*validators.GetValidatorOutput, arg2, arg3 uint64) error { +func (m *MockState) ApplyValidatorPublicKeyDiffs(ctx context.Context, validators map[ids.NodeID]*validators.GetValidatorOutput, startHeight, endHeight uint64) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ApplyValidatorPublicKeyDiffs", arg0, arg1, arg2, arg3) + ret := m.ctrl.Call(m, "ApplyValidatorPublicKeyDiffs", ctx, validators, startHeight, endHeight) ret0, _ := ret[0].(error) return ret0 } // ApplyValidatorPublicKeyDiffs indicates an expected call of ApplyValidatorPublicKeyDiffs. -func (mr *MockStateMockRecorder) ApplyValidatorPublicKeyDiffs(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *MockStateMockRecorder) ApplyValidatorPublicKeyDiffs(ctx, validators, startHeight, endHeight any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyValidatorPublicKeyDiffs", reflect.TypeOf((*MockState)(nil).ApplyValidatorPublicKeyDiffs), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyValidatorPublicKeyDiffs", reflect.TypeOf((*MockState)(nil).ApplyValidatorPublicKeyDiffs), ctx, validators, startHeight, endHeight) } // ApplyValidatorWeightDiffs mocks base method. -func (m *MockState) ApplyValidatorWeightDiffs(arg0 context.Context, arg1 map[ids.NodeID]*validators.GetValidatorOutput, arg2, arg3 uint64, arg4 ids.ID) error { +func (m *MockState) ApplyValidatorWeightDiffs(ctx context.Context, validators map[ids.NodeID]*validators.GetValidatorOutput, startHeight, endHeight uint64, subnetID ids.ID) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ApplyValidatorWeightDiffs", arg0, arg1, arg2, arg3, arg4) + ret := m.ctrl.Call(m, "ApplyValidatorWeightDiffs", ctx, validators, startHeight, endHeight, subnetID) ret0, _ := ret[0].(error) return ret0 } // ApplyValidatorWeightDiffs indicates an expected call of ApplyValidatorWeightDiffs. -func (mr *MockStateMockRecorder) ApplyValidatorWeightDiffs(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { +func (mr *MockStateMockRecorder) ApplyValidatorWeightDiffs(ctx, validators, startHeight, endHeight, subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyValidatorWeightDiffs", reflect.TypeOf((*MockState)(nil).ApplyValidatorWeightDiffs), arg0, arg1, arg2, arg3, arg4) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ApplyValidatorWeightDiffs", reflect.TypeOf((*MockState)(nil).ApplyValidatorWeightDiffs), ctx, validators, startHeight, endHeight, subnetID) } // Checksum mocks base method. @@ -1251,108 +233,108 @@ func (mr *MockStateMockRecorder) CommitBatch() *gomock.Call { } // DeleteCurrentDelegator mocks base method. -func (m *MockState) DeleteCurrentDelegator(arg0 *Staker) { +func (m *MockState) DeleteCurrentDelegator(staker *Staker) { m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentDelegator", arg0) + m.ctrl.Call(m, "DeleteCurrentDelegator", staker) } // DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. -func (mr *MockStateMockRecorder) DeleteCurrentDelegator(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) DeleteCurrentDelegator(staker any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*MockState)(nil).DeleteCurrentDelegator), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*MockState)(nil).DeleteCurrentDelegator), staker) } // DeleteCurrentValidator mocks base method. -func (m *MockState) DeleteCurrentValidator(arg0 *Staker) { +func (m *MockState) DeleteCurrentValidator(staker *Staker) { m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentValidator", arg0) + m.ctrl.Call(m, "DeleteCurrentValidator", staker) } // DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. -func (mr *MockStateMockRecorder) DeleteCurrentValidator(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) DeleteCurrentValidator(staker any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*MockState)(nil).DeleteCurrentValidator), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*MockState)(nil).DeleteCurrentValidator), staker) } // DeletePendingDelegator mocks base method. -func (m *MockState) DeletePendingDelegator(arg0 *Staker) { +func (m *MockState) DeletePendingDelegator(staker *Staker) { m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingDelegator", arg0) + m.ctrl.Call(m, "DeletePendingDelegator", staker) } // DeletePendingDelegator indicates an expected call of DeletePendingDelegator. -func (mr *MockStateMockRecorder) DeletePendingDelegator(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) DeletePendingDelegator(staker any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*MockState)(nil).DeletePendingDelegator), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*MockState)(nil).DeletePendingDelegator), staker) } // DeletePendingValidator mocks base method. -func (m *MockState) DeletePendingValidator(arg0 *Staker) { +func (m *MockState) DeletePendingValidator(staker *Staker) { m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingValidator", arg0) + m.ctrl.Call(m, "DeletePendingValidator", staker) } // DeletePendingValidator indicates an expected call of DeletePendingValidator. -func (mr *MockStateMockRecorder) DeletePendingValidator(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) DeletePendingValidator(staker any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*MockState)(nil).DeletePendingValidator), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*MockState)(nil).DeletePendingValidator), staker) } // DeleteUTXO mocks base method. -func (m *MockState) DeleteUTXO(arg0 ids.ID) { +func (m *MockState) DeleteUTXO(utxoID ids.ID) { m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteUTXO", arg0) + m.ctrl.Call(m, "DeleteUTXO", utxoID) } // DeleteUTXO indicates an expected call of DeleteUTXO. -func (mr *MockStateMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) DeleteUTXO(utxoID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockState)(nil).DeleteUTXO), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockState)(nil).DeleteUTXO), utxoID) } // GetBlockIDAtHeight mocks base method. -func (m *MockState) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { +func (m *MockState) GetBlockIDAtHeight(height uint64) (ids.ID, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0) + ret := m.ctrl.Call(m, "GetBlockIDAtHeight", height) ret0, _ := ret[0].(ids.ID) ret1, _ := ret[1].(error) return ret0, ret1 } // GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. -func (mr *MockStateMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetBlockIDAtHeight(height any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*MockState)(nil).GetBlockIDAtHeight), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*MockState)(nil).GetBlockIDAtHeight), height) } // GetChains mocks base method. -func (m *MockState) GetChains(arg0 ids.ID) ([]*txs.Tx, error) { +func (m *MockState) GetChains(subnetID ids.ID) ([]*txs.Tx, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetChains", arg0) + ret := m.ctrl.Call(m, "GetChains", subnetID) ret0, _ := ret[0].([]*txs.Tx) ret1, _ := ret[1].(error) return ret0, ret1 } // GetChains indicates an expected call of GetChains. -func (mr *MockStateMockRecorder) GetChains(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetChains(subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChains", reflect.TypeOf((*MockState)(nil).GetChains), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChains", reflect.TypeOf((*MockState)(nil).GetChains), subnetID) } // GetCurrentDelegatorIterator mocks base method. -func (m *MockState) GetCurrentDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (StakerIterator, error) { +func (m *MockState) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", arg0, arg1) + ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", subnetID, nodeID) ret0, _ := ret[0].(StakerIterator) ret1, _ := ret[1].(error) return ret0, ret1 } // GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. -func (mr *MockStateMockRecorder) GetCurrentDelegatorIterator(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetCurrentDelegatorIterator(subnetID, nodeID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*MockState)(nil).GetCurrentDelegatorIterator), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*MockState)(nil).GetCurrentDelegatorIterator), subnetID, nodeID) } // GetCurrentStakerIterator mocks base method. @@ -1371,48 +353,48 @@ func (mr *MockStateMockRecorder) GetCurrentStakerIterator() *gomock.Call { } // GetCurrentSupply mocks base method. -func (m *MockState) GetCurrentSupply(arg0 ids.ID) (uint64, error) { +func (m *MockState) GetCurrentSupply(subnetID ids.ID) (uint64, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentSupply", arg0) + ret := m.ctrl.Call(m, "GetCurrentSupply", subnetID) ret0, _ := ret[0].(uint64) ret1, _ := ret[1].(error) return ret0, ret1 } // GetCurrentSupply indicates an expected call of GetCurrentSupply. -func (mr *MockStateMockRecorder) GetCurrentSupply(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetCurrentSupply(subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*MockState)(nil).GetCurrentSupply), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*MockState)(nil).GetCurrentSupply), subnetID) } // GetCurrentValidator mocks base method. -func (m *MockState) GetCurrentValidator(arg0 ids.ID, arg1 ids.NodeID) (*Staker, error) { +func (m *MockState) GetCurrentValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentValidator", arg0, arg1) + ret := m.ctrl.Call(m, "GetCurrentValidator", subnetID, nodeID) ret0, _ := ret[0].(*Staker) ret1, _ := ret[1].(error) return ret0, ret1 } // GetCurrentValidator indicates an expected call of GetCurrentValidator. -func (mr *MockStateMockRecorder) GetCurrentValidator(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetCurrentValidator(subnetID, nodeID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*MockState)(nil).GetCurrentValidator), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*MockState)(nil).GetCurrentValidator), subnetID, nodeID) } // GetDelegateeReward mocks base method. -func (m *MockState) GetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID) (uint64, error) { +func (m *MockState) GetDelegateeReward(subnetID ids.ID, nodeID ids.NodeID) (uint64, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDelegateeReward", arg0, arg1) + ret := m.ctrl.Call(m, "GetDelegateeReward", subnetID, nodeID) ret0, _ := ret[0].(uint64) ret1, _ := ret[1].(error) return ret0, ret1 } // GetDelegateeReward indicates an expected call of GetDelegateeReward. -func (mr *MockStateMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetDelegateeReward(subnetID, nodeID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*MockState)(nil).GetDelegateeReward), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*MockState)(nil).GetDelegateeReward), subnetID, nodeID) } // GetFeeState mocks base method. @@ -1444,18 +426,18 @@ func (mr *MockStateMockRecorder) GetLastAccepted() *gomock.Call { } // GetPendingDelegatorIterator mocks base method. -func (m *MockState) GetPendingDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (StakerIterator, error) { +func (m *MockState) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", arg0, arg1) + ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", subnetID, nodeID) ret0, _ := ret[0].(StakerIterator) ret1, _ := ret[1].(error) return ret0, ret1 } // GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. -func (mr *MockStateMockRecorder) GetPendingDelegatorIterator(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetPendingDelegatorIterator(subnetID, nodeID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*MockState)(nil).GetPendingDelegatorIterator), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*MockState)(nil).GetPendingDelegatorIterator), subnetID, nodeID) } // GetPendingStakerIterator mocks base method. @@ -1474,63 +456,63 @@ func (mr *MockStateMockRecorder) GetPendingStakerIterator() *gomock.Call { } // GetPendingValidator mocks base method. -func (m *MockState) GetPendingValidator(arg0 ids.ID, arg1 ids.NodeID) (*Staker, error) { +func (m *MockState) GetPendingValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingValidator", arg0, arg1) + ret := m.ctrl.Call(m, "GetPendingValidator", subnetID, nodeID) ret0, _ := ret[0].(*Staker) ret1, _ := ret[1].(error) return ret0, ret1 } // GetPendingValidator indicates an expected call of GetPendingValidator. -func (mr *MockStateMockRecorder) GetPendingValidator(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetPendingValidator(subnetID, nodeID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*MockState)(nil).GetPendingValidator), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*MockState)(nil).GetPendingValidator), subnetID, nodeID) } // GetRewardUTXOs mocks base method. -func (m *MockState) GetRewardUTXOs(arg0 ids.ID) ([]*avax.UTXO, error) { +func (m *MockState) GetRewardUTXOs(txID ids.ID) ([]*avax.UTXO, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRewardUTXOs", arg0) + ret := m.ctrl.Call(m, "GetRewardUTXOs", txID) ret0, _ := ret[0].([]*avax.UTXO) ret1, _ := ret[1].(error) return ret0, ret1 } // GetRewardUTXOs indicates an expected call of GetRewardUTXOs. -func (mr *MockStateMockRecorder) GetRewardUTXOs(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetRewardUTXOs(txID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRewardUTXOs", reflect.TypeOf((*MockState)(nil).GetRewardUTXOs), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRewardUTXOs", reflect.TypeOf((*MockState)(nil).GetRewardUTXOs), txID) } // GetStartTime mocks base method. -func (m *MockState) GetStartTime(arg0 ids.NodeID, arg1 ids.ID) (time.Time, error) { +func (m *MockState) GetStartTime(nodeID ids.NodeID, subnetID ids.ID) (time.Time, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStartTime", arg0, arg1) + ret := m.ctrl.Call(m, "GetStartTime", nodeID, subnetID) ret0, _ := ret[0].(time.Time) ret1, _ := ret[1].(error) return ret0, ret1 } // GetStartTime indicates an expected call of GetStartTime. -func (mr *MockStateMockRecorder) GetStartTime(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetStartTime(nodeID, subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStartTime", reflect.TypeOf((*MockState)(nil).GetStartTime), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStartTime", reflect.TypeOf((*MockState)(nil).GetStartTime), nodeID, subnetID) } // GetStatelessBlock mocks base method. -func (m *MockState) GetStatelessBlock(arg0 ids.ID) (block.Block, error) { +func (m *MockState) GetStatelessBlock(blockID ids.ID) (block.Block, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetStatelessBlock", arg0) + ret := m.ctrl.Call(m, "GetStatelessBlock", blockID) ret0, _ := ret[0].(block.Block) ret1, _ := ret[1].(error) return ret0, ret1 } // GetStatelessBlock indicates an expected call of GetStatelessBlock. -func (mr *MockStateMockRecorder) GetStatelessBlock(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetStatelessBlock(blockID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStatelessBlock", reflect.TypeOf((*MockState)(nil).GetStatelessBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetStatelessBlock", reflect.TypeOf((*MockState)(nil).GetStatelessBlock), blockID) } // GetSubnetIDs mocks base method. @@ -1549,9 +531,9 @@ func (mr *MockStateMockRecorder) GetSubnetIDs() *gomock.Call { } // GetSubnetManager mocks base method. -func (m *MockState) GetSubnetManager(arg0 ids.ID) (ids.ID, []byte, error) { +func (m *MockState) GetSubnetManager(subnetID ids.ID) (ids.ID, []byte, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetManager", arg0) + ret := m.ctrl.Call(m, "GetSubnetManager", subnetID) ret0, _ := ret[0].(ids.ID) ret1, _ := ret[1].([]byte) ret2, _ := ret[2].(error) @@ -1559,39 +541,39 @@ func (m *MockState) GetSubnetManager(arg0 ids.ID) (ids.ID, []byte, error) { } // GetSubnetManager indicates an expected call of GetSubnetManager. -func (mr *MockStateMockRecorder) GetSubnetManager(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetSubnetManager(subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*MockState)(nil).GetSubnetManager), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*MockState)(nil).GetSubnetManager), subnetID) } // GetSubnetOwner mocks base method. -func (m *MockState) GetSubnetOwner(arg0 ids.ID) (fx.Owner, error) { +func (m *MockState) GetSubnetOwner(subnetID ids.ID) (fx.Owner, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetOwner", arg0) + ret := m.ctrl.Call(m, "GetSubnetOwner", subnetID) ret0, _ := ret[0].(fx.Owner) ret1, _ := ret[1].(error) return ret0, ret1 } // GetSubnetOwner indicates an expected call of GetSubnetOwner. -func (mr *MockStateMockRecorder) GetSubnetOwner(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetSubnetOwner(subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*MockState)(nil).GetSubnetOwner), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*MockState)(nil).GetSubnetOwner), subnetID) } // GetSubnetTransformation mocks base method. -func (m *MockState) GetSubnetTransformation(arg0 ids.ID) (*txs.Tx, error) { +func (m *MockState) GetSubnetTransformation(subnetID ids.ID) (*txs.Tx, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetTransformation", arg0) + ret := m.ctrl.Call(m, "GetSubnetTransformation", subnetID) ret0, _ := ret[0].(*txs.Tx) ret1, _ := ret[1].(error) return ret0, ret1 } // GetSubnetTransformation indicates an expected call of GetSubnetTransformation. -func (mr *MockStateMockRecorder) GetSubnetTransformation(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetSubnetTransformation(subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*MockState)(nil).GetSubnetTransformation), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*MockState)(nil).GetSubnetTransformation), subnetID) } // GetTimestamp mocks base method. @@ -1609,9 +591,9 @@ func (mr *MockStateMockRecorder) GetTimestamp() *gomock.Call { } // GetTx mocks base method. -func (m *MockState) GetTx(arg0 ids.ID) (*txs.Tx, status.Status, error) { +func (m *MockState) GetTx(txID ids.ID) (*txs.Tx, status.Status, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTx", arg0) + ret := m.ctrl.Call(m, "GetTx", txID) ret0, _ := ret[0].(*txs.Tx) ret1, _ := ret[1].(status.Status) ret2, _ := ret[2].(error) @@ -1619,30 +601,30 @@ func (m *MockState) GetTx(arg0 ids.ID) (*txs.Tx, status.Status, error) { } // GetTx indicates an expected call of GetTx. -func (mr *MockStateMockRecorder) GetTx(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetTx(txID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockState)(nil).GetTx), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockState)(nil).GetTx), txID) } // GetUTXO mocks base method. -func (m *MockState) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { +func (m *MockState) GetUTXO(utxoID ids.ID) (*avax.UTXO, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUTXO", arg0) + ret := m.ctrl.Call(m, "GetUTXO", utxoID) ret0, _ := ret[0].(*avax.UTXO) ret1, _ := ret[1].(error) return ret0, ret1 } // GetUTXO indicates an expected call of GetUTXO. -func (mr *MockStateMockRecorder) GetUTXO(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetUTXO(utxoID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockState)(nil).GetUTXO), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockState)(nil).GetUTXO), utxoID) } // GetUptime mocks base method. -func (m *MockState) GetUptime(arg0 ids.NodeID, arg1 ids.ID) (time.Duration, time.Time, error) { +func (m *MockState) GetUptime(nodeID ids.NodeID, subnetID ids.ID) (time.Duration, time.Time, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUptime", arg0, arg1) + ret := m.ctrl.Call(m, "GetUptime", nodeID, subnetID) ret0, _ := ret[0].(time.Duration) ret1, _ := ret[1].(time.Time) ret2, _ := ret[2].(error) @@ -1650,196 +632,196 @@ func (m *MockState) GetUptime(arg0 ids.NodeID, arg1 ids.ID) (time.Duration, time } // GetUptime indicates an expected call of GetUptime. -func (mr *MockStateMockRecorder) GetUptime(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) GetUptime(nodeID, subnetID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUptime", reflect.TypeOf((*MockState)(nil).GetUptime), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUptime", reflect.TypeOf((*MockState)(nil).GetUptime), nodeID, subnetID) } // PutCurrentDelegator mocks base method. -func (m *MockState) PutCurrentDelegator(arg0 *Staker) { +func (m *MockState) PutCurrentDelegator(staker *Staker) { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentDelegator", arg0) + m.ctrl.Call(m, "PutCurrentDelegator", staker) } // PutCurrentDelegator indicates an expected call of PutCurrentDelegator. -func (mr *MockStateMockRecorder) PutCurrentDelegator(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) PutCurrentDelegator(staker any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*MockState)(nil).PutCurrentDelegator), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*MockState)(nil).PutCurrentDelegator), staker) } // PutCurrentValidator mocks base method. -func (m *MockState) PutCurrentValidator(arg0 *Staker) { +func (m *MockState) PutCurrentValidator(staker *Staker) { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentValidator", arg0) + m.ctrl.Call(m, "PutCurrentValidator", staker) } // PutCurrentValidator indicates an expected call of PutCurrentValidator. -func (mr *MockStateMockRecorder) PutCurrentValidator(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) PutCurrentValidator(staker any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*MockState)(nil).PutCurrentValidator), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*MockState)(nil).PutCurrentValidator), staker) } // PutPendingDelegator mocks base method. -func (m *MockState) PutPendingDelegator(arg0 *Staker) { +func (m *MockState) PutPendingDelegator(staker *Staker) { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingDelegator", arg0) + m.ctrl.Call(m, "PutPendingDelegator", staker) } // PutPendingDelegator indicates an expected call of PutPendingDelegator. -func (mr *MockStateMockRecorder) PutPendingDelegator(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) PutPendingDelegator(staker any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*MockState)(nil).PutPendingDelegator), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*MockState)(nil).PutPendingDelegator), staker) } // PutPendingValidator mocks base method. -func (m *MockState) PutPendingValidator(arg0 *Staker) { +func (m *MockState) PutPendingValidator(staker *Staker) { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingValidator", arg0) + m.ctrl.Call(m, "PutPendingValidator", staker) } // PutPendingValidator indicates an expected call of PutPendingValidator. -func (mr *MockStateMockRecorder) PutPendingValidator(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) PutPendingValidator(staker any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*MockState)(nil).PutPendingValidator), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*MockState)(nil).PutPendingValidator), staker) } // ReindexBlocks mocks base method. -func (m *MockState) ReindexBlocks(arg0 sync.Locker, arg1 logging.Logger) error { +func (m *MockState) ReindexBlocks(lock sync.Locker, log logging.Logger) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ReindexBlocks", arg0, arg1) + ret := m.ctrl.Call(m, "ReindexBlocks", lock, log) ret0, _ := ret[0].(error) return ret0 } // ReindexBlocks indicates an expected call of ReindexBlocks. -func (mr *MockStateMockRecorder) ReindexBlocks(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) ReindexBlocks(lock, log any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReindexBlocks", reflect.TypeOf((*MockState)(nil).ReindexBlocks), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ReindexBlocks", reflect.TypeOf((*MockState)(nil).ReindexBlocks), lock, log) } // SetCurrentSupply mocks base method. -func (m *MockState) SetCurrentSupply(arg0 ids.ID, arg1 uint64) { +func (m *MockState) SetCurrentSupply(subnetID ids.ID, cs uint64) { m.ctrl.T.Helper() - m.ctrl.Call(m, "SetCurrentSupply", arg0, arg1) + m.ctrl.Call(m, "SetCurrentSupply", subnetID, cs) } // SetCurrentSupply indicates an expected call of SetCurrentSupply. -func (mr *MockStateMockRecorder) SetCurrentSupply(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetCurrentSupply(subnetID, cs any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*MockState)(nil).SetCurrentSupply), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*MockState)(nil).SetCurrentSupply), subnetID, cs) } // SetDelegateeReward mocks base method. -func (m *MockState) SetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID, arg2 uint64) error { +func (m *MockState) SetDelegateeReward(subnetID ids.ID, nodeID ids.NodeID, amount uint64) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetDelegateeReward", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "SetDelegateeReward", subnetID, nodeID, amount) ret0, _ := ret[0].(error) return ret0 } // SetDelegateeReward indicates an expected call of SetDelegateeReward. -func (mr *MockStateMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetDelegateeReward(subnetID, nodeID, amount any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*MockState)(nil).SetDelegateeReward), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*MockState)(nil).SetDelegateeReward), subnetID, nodeID, amount) } // SetFeeState mocks base method. -func (m *MockState) SetFeeState(arg0 gas.State) { +func (m *MockState) SetFeeState(f gas.State) { m.ctrl.T.Helper() - m.ctrl.Call(m, "SetFeeState", arg0) + m.ctrl.Call(m, "SetFeeState", f) } // SetFeeState indicates an expected call of SetFeeState. -func (mr *MockStateMockRecorder) SetFeeState(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetFeeState(f any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*MockState)(nil).SetFeeState), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*MockState)(nil).SetFeeState), f) } // SetHeight mocks base method. -func (m *MockState) SetHeight(arg0 uint64) { +func (m *MockState) SetHeight(height uint64) { m.ctrl.T.Helper() - m.ctrl.Call(m, "SetHeight", arg0) + m.ctrl.Call(m, "SetHeight", height) } // SetHeight indicates an expected call of SetHeight. -func (mr *MockStateMockRecorder) SetHeight(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetHeight(height any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetHeight", reflect.TypeOf((*MockState)(nil).SetHeight), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetHeight", reflect.TypeOf((*MockState)(nil).SetHeight), height) } // SetLastAccepted mocks base method. -func (m *MockState) SetLastAccepted(arg0 ids.ID) { +func (m *MockState) SetLastAccepted(blkID ids.ID) { m.ctrl.T.Helper() - m.ctrl.Call(m, "SetLastAccepted", arg0) + m.ctrl.Call(m, "SetLastAccepted", blkID) } // SetLastAccepted indicates an expected call of SetLastAccepted. -func (mr *MockStateMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetLastAccepted(blkID any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*MockState)(nil).SetLastAccepted), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*MockState)(nil).SetLastAccepted), blkID) } // SetSubnetManager mocks base method. -func (m *MockState) SetSubnetManager(arg0, arg1 ids.ID, arg2 []byte) { +func (m *MockState) SetSubnetManager(subnetID, chainID ids.ID, addr []byte) { m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetManager", arg0, arg1, arg2) + m.ctrl.Call(m, "SetSubnetManager", subnetID, chainID, addr) } // SetSubnetManager indicates an expected call of SetSubnetManager. -func (mr *MockStateMockRecorder) SetSubnetManager(arg0, arg1, arg2 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetSubnetManager(subnetID, chainID, addr any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*MockState)(nil).SetSubnetManager), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*MockState)(nil).SetSubnetManager), subnetID, chainID, addr) } // SetSubnetOwner mocks base method. -func (m *MockState) SetSubnetOwner(arg0 ids.ID, arg1 fx.Owner) { +func (m *MockState) SetSubnetOwner(subnetID ids.ID, owner fx.Owner) { m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetOwner", arg0, arg1) + m.ctrl.Call(m, "SetSubnetOwner", subnetID, owner) } // SetSubnetOwner indicates an expected call of SetSubnetOwner. -func (mr *MockStateMockRecorder) SetSubnetOwner(arg0, arg1 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetSubnetOwner(subnetID, owner any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*MockState)(nil).SetSubnetOwner), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*MockState)(nil).SetSubnetOwner), subnetID, owner) } // SetTimestamp mocks base method. -func (m *MockState) SetTimestamp(arg0 time.Time) { +func (m *MockState) SetTimestamp(tm time.Time) { m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimestamp", arg0) + m.ctrl.Call(m, "SetTimestamp", tm) } // SetTimestamp indicates an expected call of SetTimestamp. -func (mr *MockStateMockRecorder) SetTimestamp(arg0 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetTimestamp(tm any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockState)(nil).SetTimestamp), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockState)(nil).SetTimestamp), tm) } // SetUptime mocks base method. -func (m *MockState) SetUptime(arg0 ids.NodeID, arg1 ids.ID, arg2 time.Duration, arg3 time.Time) error { +func (m *MockState) SetUptime(nodeID ids.NodeID, subnetID ids.ID, upDuration time.Duration, lastUpdated time.Time) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetUptime", arg0, arg1, arg2, arg3) + ret := m.ctrl.Call(m, "SetUptime", nodeID, subnetID, upDuration, lastUpdated) ret0, _ := ret[0].(error) return ret0 } // SetUptime indicates an expected call of SetUptime. -func (mr *MockStateMockRecorder) SetUptime(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *MockStateMockRecorder) SetUptime(nodeID, subnetID, upDuration, lastUpdated any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetUptime", reflect.TypeOf((*MockState)(nil).SetUptime), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetUptime", reflect.TypeOf((*MockState)(nil).SetUptime), nodeID, subnetID, upDuration, lastUpdated) } // UTXOIDs mocks base method. -func (m *MockState) UTXOIDs(arg0 []byte, arg1 ids.ID, arg2 int) ([]ids.ID, error) { +func (m *MockState) UTXOIDs(addr []byte, previous ids.ID, limit int) ([]ids.ID, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "UTXOIDs", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "UTXOIDs", addr, previous, limit) ret0, _ := ret[0].([]ids.ID) ret1, _ := ret[1].(error) return ret0, ret1 } // UTXOIDs indicates an expected call of UTXOIDs. -func (mr *MockStateMockRecorder) UTXOIDs(arg0, arg1, arg2 any) *gomock.Call { +func (mr *MockStateMockRecorder) UTXOIDs(addr, previous, limit any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UTXOIDs", reflect.TypeOf((*MockState)(nil).UTXOIDs), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UTXOIDs", reflect.TypeOf((*MockState)(nil).UTXOIDs), addr, previous, limit) } diff --git a/vms/platformvm/state/staker_test.go b/vms/platformvm/state/staker_test.go index 579d61cc841d..91b7b8047508 100644 --- a/vms/platformvm/state/staker_test.go +++ b/vms/platformvm/state/staker_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/vms/platformvm/signer" + "github.com/ava-labs/avalanchego/vms/platformvm/signer/signermock" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) @@ -159,7 +160,7 @@ func TestNewCurrentStaker(t *testing.T) { }, staker) ctrl := gomock.NewController(t) - signer := signer.NewMockSigner(ctrl) + signer := signermock.NewSigner(ctrl) signer.EXPECT().Verify().Return(errCustom) stakerTx.Signer = signer @@ -191,7 +192,7 @@ func TestNewPendingStaker(t *testing.T) { }, staker) ctrl := gomock.NewController(t) - signer := signer.NewMockSigner(ctrl) + signer := signermock.NewSigner(ctrl) signer.EXPECT().Verify().Return(errCustom) stakerTx.Signer = signer diff --git a/vms/platformvm/state/state_test.go b/vms/platformvm/state/state_test.go index fcfd02dfa1ce..41a51b17d588 100644 --- a/vms/platformvm/state/state_test.go +++ b/vms/platformvm/state/state_test.go @@ -33,7 +33,7 @@ import ( "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" - "github.com/ava-labs/avalanchego/vms/platformvm/fx" + "github.com/ava-labs/avalanchego/vms/platformvm/fx/fxmock" "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/reward" @@ -1274,8 +1274,8 @@ func TestStateSubnetOwner(t *testing.T) { ctrl := gomock.NewController(t) var ( - owner1 = fx.NewMockOwner(ctrl) - owner2 = fx.NewMockOwner(ctrl) + owner1 = fxmock.NewOwner(ctrl) + owner2 = fxmock.NewOwner(ctrl) createSubnetTx = &txs.Tx{ Unsigned: &txs.CreateSubnetTx{ diff --git a/vms/platformvm/state/statemock/chain.go b/vms/platformvm/state/statemock/chain.go new file mode 100644 index 000000000000..b0d239671610 --- /dev/null +++ b/vms/platformvm/state/statemock/chain.go @@ -0,0 +1,526 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/platformvm/state (interfaces: Chain) +// +// Generated by this command: +// +// mockgen -package=statemock -destination=vms/platformvm/state/statemock/chain.go -mock_names=Chain=Chain github.com/ava-labs/avalanchego/vms/platformvm/state Chain +// + +// Package statemock is a generated GoMock package. +package statemock + +import ( + reflect "reflect" + time "time" + + ids "github.com/ava-labs/avalanchego/ids" + avax "github.com/ava-labs/avalanchego/vms/components/avax" + gas "github.com/ava-labs/avalanchego/vms/components/gas" + fx "github.com/ava-labs/avalanchego/vms/platformvm/fx" + state "github.com/ava-labs/avalanchego/vms/platformvm/state" + status "github.com/ava-labs/avalanchego/vms/platformvm/status" + txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" + gomock "go.uber.org/mock/gomock" +) + +// Chain is a mock of Chain interface. +type Chain struct { + ctrl *gomock.Controller + recorder *ChainMockRecorder +} + +// ChainMockRecorder is the mock recorder for Chain. +type ChainMockRecorder struct { + mock *Chain +} + +// NewChain creates a new mock instance. +func NewChain(ctrl *gomock.Controller) *Chain { + mock := &Chain{ctrl: ctrl} + mock.recorder = &ChainMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Chain) EXPECT() *ChainMockRecorder { + return m.recorder +} + +// AddChain mocks base method. +func (m *Chain) AddChain(arg0 *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddChain", arg0) +} + +// AddChain indicates an expected call of AddChain. +func (mr *ChainMockRecorder) AddChain(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*Chain)(nil).AddChain), arg0) +} + +// AddRewardUTXO mocks base method. +func (m *Chain) AddRewardUTXO(arg0 ids.ID, arg1 *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddRewardUTXO", arg0, arg1) +} + +// AddRewardUTXO indicates an expected call of AddRewardUTXO. +func (mr *ChainMockRecorder) AddRewardUTXO(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*Chain)(nil).AddRewardUTXO), arg0, arg1) +} + +// AddSubnet mocks base method. +func (m *Chain) AddSubnet(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddSubnet", arg0) +} + +// AddSubnet indicates an expected call of AddSubnet. +func (mr *ChainMockRecorder) AddSubnet(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*Chain)(nil).AddSubnet), arg0) +} + +// AddSubnetTransformation mocks base method. +func (m *Chain) AddSubnetTransformation(arg0 *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddSubnetTransformation", arg0) +} + +// AddSubnetTransformation indicates an expected call of AddSubnetTransformation. +func (mr *ChainMockRecorder) AddSubnetTransformation(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*Chain)(nil).AddSubnetTransformation), arg0) +} + +// AddTx mocks base method. +func (m *Chain) AddTx(arg0 *txs.Tx, arg1 status.Status) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddTx", arg0, arg1) +} + +// AddTx indicates an expected call of AddTx. +func (mr *ChainMockRecorder) AddTx(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*Chain)(nil).AddTx), arg0, arg1) +} + +// AddUTXO mocks base method. +func (m *Chain) AddUTXO(arg0 *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddUTXO", arg0) +} + +// AddUTXO indicates an expected call of AddUTXO. +func (mr *ChainMockRecorder) AddUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*Chain)(nil).AddUTXO), arg0) +} + +// DeleteCurrentDelegator mocks base method. +func (m *Chain) DeleteCurrentDelegator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteCurrentDelegator", arg0) +} + +// DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. +func (mr *ChainMockRecorder) DeleteCurrentDelegator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*Chain)(nil).DeleteCurrentDelegator), arg0) +} + +// DeleteCurrentValidator mocks base method. +func (m *Chain) DeleteCurrentValidator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteCurrentValidator", arg0) +} + +// DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. +func (mr *ChainMockRecorder) DeleteCurrentValidator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*Chain)(nil).DeleteCurrentValidator), arg0) +} + +// DeletePendingDelegator mocks base method. +func (m *Chain) DeletePendingDelegator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeletePendingDelegator", arg0) +} + +// DeletePendingDelegator indicates an expected call of DeletePendingDelegator. +func (mr *ChainMockRecorder) DeletePendingDelegator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*Chain)(nil).DeletePendingDelegator), arg0) +} + +// DeletePendingValidator mocks base method. +func (m *Chain) DeletePendingValidator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeletePendingValidator", arg0) +} + +// DeletePendingValidator indicates an expected call of DeletePendingValidator. +func (mr *ChainMockRecorder) DeletePendingValidator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*Chain)(nil).DeletePendingValidator), arg0) +} + +// DeleteUTXO mocks base method. +func (m *Chain) DeleteUTXO(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteUTXO", arg0) +} + +// DeleteUTXO indicates an expected call of DeleteUTXO. +func (mr *ChainMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*Chain)(nil).DeleteUTXO), arg0) +} + +// GetCurrentDelegatorIterator mocks base method. +func (m *Chain) GetCurrentDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (state.StakerIterator, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", arg0, arg1) + ret0, _ := ret[0].(state.StakerIterator) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. +func (mr *ChainMockRecorder) GetCurrentDelegatorIterator(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*Chain)(nil).GetCurrentDelegatorIterator), arg0, arg1) +} + +// GetCurrentStakerIterator mocks base method. +func (m *Chain) GetCurrentStakerIterator() (state.StakerIterator, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentStakerIterator") + ret0, _ := ret[0].(state.StakerIterator) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentStakerIterator indicates an expected call of GetCurrentStakerIterator. +func (mr *ChainMockRecorder) GetCurrentStakerIterator() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentStakerIterator", reflect.TypeOf((*Chain)(nil).GetCurrentStakerIterator)) +} + +// GetCurrentSupply mocks base method. +func (m *Chain) GetCurrentSupply(arg0 ids.ID) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentSupply", arg0) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentSupply indicates an expected call of GetCurrentSupply. +func (mr *ChainMockRecorder) GetCurrentSupply(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*Chain)(nil).GetCurrentSupply), arg0) +} + +// GetCurrentValidator mocks base method. +func (m *Chain) GetCurrentValidator(arg0 ids.ID, arg1 ids.NodeID) (*state.Staker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentValidator", arg0, arg1) + ret0, _ := ret[0].(*state.Staker) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentValidator indicates an expected call of GetCurrentValidator. +func (mr *ChainMockRecorder) GetCurrentValidator(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*Chain)(nil).GetCurrentValidator), arg0, arg1) +} + +// GetDelegateeReward mocks base method. +func (m *Chain) GetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetDelegateeReward", arg0, arg1) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetDelegateeReward indicates an expected call of GetDelegateeReward. +func (mr *ChainMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*Chain)(nil).GetDelegateeReward), arg0, arg1) +} + +// GetFeeState mocks base method. +func (m *Chain) GetFeeState() gas.State { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetFeeState") + ret0, _ := ret[0].(gas.State) + return ret0 +} + +// GetFeeState indicates an expected call of GetFeeState. +func (mr *ChainMockRecorder) GetFeeState() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeeState", reflect.TypeOf((*Chain)(nil).GetFeeState)) +} + +// GetPendingDelegatorIterator mocks base method. +func (m *Chain) GetPendingDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (state.StakerIterator, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", arg0, arg1) + ret0, _ := ret[0].(state.StakerIterator) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. +func (mr *ChainMockRecorder) GetPendingDelegatorIterator(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*Chain)(nil).GetPendingDelegatorIterator), arg0, arg1) +} + +// GetPendingStakerIterator mocks base method. +func (m *Chain) GetPendingStakerIterator() (state.StakerIterator, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingStakerIterator") + ret0, _ := ret[0].(state.StakerIterator) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingStakerIterator indicates an expected call of GetPendingStakerIterator. +func (mr *ChainMockRecorder) GetPendingStakerIterator() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingStakerIterator", reflect.TypeOf((*Chain)(nil).GetPendingStakerIterator)) +} + +// GetPendingValidator mocks base method. +func (m *Chain) GetPendingValidator(arg0 ids.ID, arg1 ids.NodeID) (*state.Staker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingValidator", arg0, arg1) + ret0, _ := ret[0].(*state.Staker) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingValidator indicates an expected call of GetPendingValidator. +func (mr *ChainMockRecorder) GetPendingValidator(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*Chain)(nil).GetPendingValidator), arg0, arg1) +} + +// GetSubnetManager mocks base method. +func (m *Chain) GetSubnetManager(arg0 ids.ID) (ids.ID, []byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetManager", arg0) + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].([]byte) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetSubnetManager indicates an expected call of GetSubnetManager. +func (mr *ChainMockRecorder) GetSubnetManager(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*Chain)(nil).GetSubnetManager), arg0) +} + +// GetSubnetOwner mocks base method. +func (m *Chain) GetSubnetOwner(arg0 ids.ID) (fx.Owner, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetOwner", arg0) + ret0, _ := ret[0].(fx.Owner) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSubnetOwner indicates an expected call of GetSubnetOwner. +func (mr *ChainMockRecorder) GetSubnetOwner(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*Chain)(nil).GetSubnetOwner), arg0) +} + +// GetSubnetTransformation mocks base method. +func (m *Chain) GetSubnetTransformation(arg0 ids.ID) (*txs.Tx, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetTransformation", arg0) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSubnetTransformation indicates an expected call of GetSubnetTransformation. +func (mr *ChainMockRecorder) GetSubnetTransformation(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*Chain)(nil).GetSubnetTransformation), arg0) +} + +// GetTimestamp mocks base method. +func (m *Chain) GetTimestamp() time.Time { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTimestamp") + ret0, _ := ret[0].(time.Time) + return ret0 +} + +// GetTimestamp indicates an expected call of GetTimestamp. +func (mr *ChainMockRecorder) GetTimestamp() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*Chain)(nil).GetTimestamp)) +} + +// GetTx mocks base method. +func (m *Chain) GetTx(arg0 ids.ID) (*txs.Tx, status.Status, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTx", arg0) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(status.Status) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetTx indicates an expected call of GetTx. +func (mr *ChainMockRecorder) GetTx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*Chain)(nil).GetTx), arg0) +} + +// GetUTXO mocks base method. +func (m *Chain) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUTXO", arg0) + ret0, _ := ret[0].(*avax.UTXO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUTXO indicates an expected call of GetUTXO. +func (mr *ChainMockRecorder) GetUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*Chain)(nil).GetUTXO), arg0) +} + +// PutCurrentDelegator mocks base method. +func (m *Chain) PutCurrentDelegator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutCurrentDelegator", arg0) +} + +// PutCurrentDelegator indicates an expected call of PutCurrentDelegator. +func (mr *ChainMockRecorder) PutCurrentDelegator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*Chain)(nil).PutCurrentDelegator), arg0) +} + +// PutCurrentValidator mocks base method. +func (m *Chain) PutCurrentValidator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutCurrentValidator", arg0) +} + +// PutCurrentValidator indicates an expected call of PutCurrentValidator. +func (mr *ChainMockRecorder) PutCurrentValidator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*Chain)(nil).PutCurrentValidator), arg0) +} + +// PutPendingDelegator mocks base method. +func (m *Chain) PutPendingDelegator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutPendingDelegator", arg0) +} + +// PutPendingDelegator indicates an expected call of PutPendingDelegator. +func (mr *ChainMockRecorder) PutPendingDelegator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*Chain)(nil).PutPendingDelegator), arg0) +} + +// PutPendingValidator mocks base method. +func (m *Chain) PutPendingValidator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutPendingValidator", arg0) +} + +// PutPendingValidator indicates an expected call of PutPendingValidator. +func (mr *ChainMockRecorder) PutPendingValidator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*Chain)(nil).PutPendingValidator), arg0) +} + +// SetCurrentSupply mocks base method. +func (m *Chain) SetCurrentSupply(arg0 ids.ID, arg1 uint64) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetCurrentSupply", arg0, arg1) +} + +// SetCurrentSupply indicates an expected call of SetCurrentSupply. +func (mr *ChainMockRecorder) SetCurrentSupply(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*Chain)(nil).SetCurrentSupply), arg0, arg1) +} + +// SetDelegateeReward mocks base method. +func (m *Chain) SetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID, arg2 uint64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetDelegateeReward", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetDelegateeReward indicates an expected call of SetDelegateeReward. +func (mr *ChainMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*Chain)(nil).SetDelegateeReward), arg0, arg1, arg2) +} + +// SetFeeState mocks base method. +func (m *Chain) SetFeeState(arg0 gas.State) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetFeeState", arg0) +} + +// SetFeeState indicates an expected call of SetFeeState. +func (mr *ChainMockRecorder) SetFeeState(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*Chain)(nil).SetFeeState), arg0) +} + +// SetSubnetManager mocks base method. +func (m *Chain) SetSubnetManager(arg0, arg1 ids.ID, arg2 []byte) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetSubnetManager", arg0, arg1, arg2) +} + +// SetSubnetManager indicates an expected call of SetSubnetManager. +func (mr *ChainMockRecorder) SetSubnetManager(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*Chain)(nil).SetSubnetManager), arg0, arg1, arg2) +} + +// SetSubnetOwner mocks base method. +func (m *Chain) SetSubnetOwner(arg0 ids.ID, arg1 fx.Owner) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetSubnetOwner", arg0, arg1) +} + +// SetSubnetOwner indicates an expected call of SetSubnetOwner. +func (mr *ChainMockRecorder) SetSubnetOwner(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*Chain)(nil).SetSubnetOwner), arg0, arg1) +} + +// SetTimestamp mocks base method. +func (m *Chain) SetTimestamp(arg0 time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetTimestamp", arg0) +} + +// SetTimestamp indicates an expected call of SetTimestamp. +func (mr *ChainMockRecorder) SetTimestamp(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*Chain)(nil).SetTimestamp), arg0) +} diff --git a/vms/platformvm/state/statemock/diff.go b/vms/platformvm/state/statemock/diff.go new file mode 100644 index 000000000000..350326ffb47c --- /dev/null +++ b/vms/platformvm/state/statemock/diff.go @@ -0,0 +1,540 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/platformvm/state (interfaces: Diff) +// +// Generated by this command: +// +// mockgen -package=statemock -destination=vms/platformvm/state/statemock/diff.go -mock_names=Diff=Diff github.com/ava-labs/avalanchego/vms/platformvm/state Diff +// + +// Package statemock is a generated GoMock package. +package statemock + +import ( + reflect "reflect" + time "time" + + ids "github.com/ava-labs/avalanchego/ids" + avax "github.com/ava-labs/avalanchego/vms/components/avax" + gas "github.com/ava-labs/avalanchego/vms/components/gas" + fx "github.com/ava-labs/avalanchego/vms/platformvm/fx" + state "github.com/ava-labs/avalanchego/vms/platformvm/state" + status "github.com/ava-labs/avalanchego/vms/platformvm/status" + txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" + gomock "go.uber.org/mock/gomock" +) + +// Diff is a mock of Diff interface. +type Diff struct { + ctrl *gomock.Controller + recorder *DiffMockRecorder +} + +// DiffMockRecorder is the mock recorder for Diff. +type DiffMockRecorder struct { + mock *Diff +} + +// NewDiff creates a new mock instance. +func NewDiff(ctrl *gomock.Controller) *Diff { + mock := &Diff{ctrl: ctrl} + mock.recorder = &DiffMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Diff) EXPECT() *DiffMockRecorder { + return m.recorder +} + +// AddChain mocks base method. +func (m *Diff) AddChain(arg0 *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddChain", arg0) +} + +// AddChain indicates an expected call of AddChain. +func (mr *DiffMockRecorder) AddChain(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*Diff)(nil).AddChain), arg0) +} + +// AddRewardUTXO mocks base method. +func (m *Diff) AddRewardUTXO(arg0 ids.ID, arg1 *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddRewardUTXO", arg0, arg1) +} + +// AddRewardUTXO indicates an expected call of AddRewardUTXO. +func (mr *DiffMockRecorder) AddRewardUTXO(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*Diff)(nil).AddRewardUTXO), arg0, arg1) +} + +// AddSubnet mocks base method. +func (m *Diff) AddSubnet(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddSubnet", arg0) +} + +// AddSubnet indicates an expected call of AddSubnet. +func (mr *DiffMockRecorder) AddSubnet(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*Diff)(nil).AddSubnet), arg0) +} + +// AddSubnetTransformation mocks base method. +func (m *Diff) AddSubnetTransformation(arg0 *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddSubnetTransformation", arg0) +} + +// AddSubnetTransformation indicates an expected call of AddSubnetTransformation. +func (mr *DiffMockRecorder) AddSubnetTransformation(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*Diff)(nil).AddSubnetTransformation), arg0) +} + +// AddTx mocks base method. +func (m *Diff) AddTx(arg0 *txs.Tx, arg1 status.Status) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddTx", arg0, arg1) +} + +// AddTx indicates an expected call of AddTx. +func (mr *DiffMockRecorder) AddTx(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*Diff)(nil).AddTx), arg0, arg1) +} + +// AddUTXO mocks base method. +func (m *Diff) AddUTXO(arg0 *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddUTXO", arg0) +} + +// AddUTXO indicates an expected call of AddUTXO. +func (mr *DiffMockRecorder) AddUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*Diff)(nil).AddUTXO), arg0) +} + +// Apply mocks base method. +func (m *Diff) Apply(arg0 state.Chain) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Apply", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// Apply indicates an expected call of Apply. +func (mr *DiffMockRecorder) Apply(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*Diff)(nil).Apply), arg0) +} + +// DeleteCurrentDelegator mocks base method. +func (m *Diff) DeleteCurrentDelegator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteCurrentDelegator", arg0) +} + +// DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. +func (mr *DiffMockRecorder) DeleteCurrentDelegator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*Diff)(nil).DeleteCurrentDelegator), arg0) +} + +// DeleteCurrentValidator mocks base method. +func (m *Diff) DeleteCurrentValidator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteCurrentValidator", arg0) +} + +// DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. +func (mr *DiffMockRecorder) DeleteCurrentValidator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*Diff)(nil).DeleteCurrentValidator), arg0) +} + +// DeletePendingDelegator mocks base method. +func (m *Diff) DeletePendingDelegator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeletePendingDelegator", arg0) +} + +// DeletePendingDelegator indicates an expected call of DeletePendingDelegator. +func (mr *DiffMockRecorder) DeletePendingDelegator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*Diff)(nil).DeletePendingDelegator), arg0) +} + +// DeletePendingValidator mocks base method. +func (m *Diff) DeletePendingValidator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeletePendingValidator", arg0) +} + +// DeletePendingValidator indicates an expected call of DeletePendingValidator. +func (mr *DiffMockRecorder) DeletePendingValidator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*Diff)(nil).DeletePendingValidator), arg0) +} + +// DeleteUTXO mocks base method. +func (m *Diff) DeleteUTXO(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteUTXO", arg0) +} + +// DeleteUTXO indicates an expected call of DeleteUTXO. +func (mr *DiffMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*Diff)(nil).DeleteUTXO), arg0) +} + +// GetCurrentDelegatorIterator mocks base method. +func (m *Diff) GetCurrentDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (state.StakerIterator, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", arg0, arg1) + ret0, _ := ret[0].(state.StakerIterator) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. +func (mr *DiffMockRecorder) GetCurrentDelegatorIterator(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*Diff)(nil).GetCurrentDelegatorIterator), arg0, arg1) +} + +// GetCurrentStakerIterator mocks base method. +func (m *Diff) GetCurrentStakerIterator() (state.StakerIterator, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentStakerIterator") + ret0, _ := ret[0].(state.StakerIterator) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentStakerIterator indicates an expected call of GetCurrentStakerIterator. +func (mr *DiffMockRecorder) GetCurrentStakerIterator() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentStakerIterator", reflect.TypeOf((*Diff)(nil).GetCurrentStakerIterator)) +} + +// GetCurrentSupply mocks base method. +func (m *Diff) GetCurrentSupply(arg0 ids.ID) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentSupply", arg0) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentSupply indicates an expected call of GetCurrentSupply. +func (mr *DiffMockRecorder) GetCurrentSupply(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*Diff)(nil).GetCurrentSupply), arg0) +} + +// GetCurrentValidator mocks base method. +func (m *Diff) GetCurrentValidator(arg0 ids.ID, arg1 ids.NodeID) (*state.Staker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentValidator", arg0, arg1) + ret0, _ := ret[0].(*state.Staker) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentValidator indicates an expected call of GetCurrentValidator. +func (mr *DiffMockRecorder) GetCurrentValidator(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*Diff)(nil).GetCurrentValidator), arg0, arg1) +} + +// GetDelegateeReward mocks base method. +func (m *Diff) GetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetDelegateeReward", arg0, arg1) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetDelegateeReward indicates an expected call of GetDelegateeReward. +func (mr *DiffMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*Diff)(nil).GetDelegateeReward), arg0, arg1) +} + +// GetFeeState mocks base method. +func (m *Diff) GetFeeState() gas.State { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetFeeState") + ret0, _ := ret[0].(gas.State) + return ret0 +} + +// GetFeeState indicates an expected call of GetFeeState. +func (mr *DiffMockRecorder) GetFeeState() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeeState", reflect.TypeOf((*Diff)(nil).GetFeeState)) +} + +// GetPendingDelegatorIterator mocks base method. +func (m *Diff) GetPendingDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (state.StakerIterator, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", arg0, arg1) + ret0, _ := ret[0].(state.StakerIterator) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. +func (mr *DiffMockRecorder) GetPendingDelegatorIterator(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*Diff)(nil).GetPendingDelegatorIterator), arg0, arg1) +} + +// GetPendingStakerIterator mocks base method. +func (m *Diff) GetPendingStakerIterator() (state.StakerIterator, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingStakerIterator") + ret0, _ := ret[0].(state.StakerIterator) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingStakerIterator indicates an expected call of GetPendingStakerIterator. +func (mr *DiffMockRecorder) GetPendingStakerIterator() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingStakerIterator", reflect.TypeOf((*Diff)(nil).GetPendingStakerIterator)) +} + +// GetPendingValidator mocks base method. +func (m *Diff) GetPendingValidator(arg0 ids.ID, arg1 ids.NodeID) (*state.Staker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingValidator", arg0, arg1) + ret0, _ := ret[0].(*state.Staker) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingValidator indicates an expected call of GetPendingValidator. +func (mr *DiffMockRecorder) GetPendingValidator(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*Diff)(nil).GetPendingValidator), arg0, arg1) +} + +// GetSubnetManager mocks base method. +func (m *Diff) GetSubnetManager(arg0 ids.ID) (ids.ID, []byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetManager", arg0) + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].([]byte) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetSubnetManager indicates an expected call of GetSubnetManager. +func (mr *DiffMockRecorder) GetSubnetManager(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*Diff)(nil).GetSubnetManager), arg0) +} + +// GetSubnetOwner mocks base method. +func (m *Diff) GetSubnetOwner(arg0 ids.ID) (fx.Owner, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetOwner", arg0) + ret0, _ := ret[0].(fx.Owner) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSubnetOwner indicates an expected call of GetSubnetOwner. +func (mr *DiffMockRecorder) GetSubnetOwner(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*Diff)(nil).GetSubnetOwner), arg0) +} + +// GetSubnetTransformation mocks base method. +func (m *Diff) GetSubnetTransformation(arg0 ids.ID) (*txs.Tx, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetTransformation", arg0) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSubnetTransformation indicates an expected call of GetSubnetTransformation. +func (mr *DiffMockRecorder) GetSubnetTransformation(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*Diff)(nil).GetSubnetTransformation), arg0) +} + +// GetTimestamp mocks base method. +func (m *Diff) GetTimestamp() time.Time { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTimestamp") + ret0, _ := ret[0].(time.Time) + return ret0 +} + +// GetTimestamp indicates an expected call of GetTimestamp. +func (mr *DiffMockRecorder) GetTimestamp() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*Diff)(nil).GetTimestamp)) +} + +// GetTx mocks base method. +func (m *Diff) GetTx(arg0 ids.ID) (*txs.Tx, status.Status, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTx", arg0) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(status.Status) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetTx indicates an expected call of GetTx. +func (mr *DiffMockRecorder) GetTx(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*Diff)(nil).GetTx), arg0) +} + +// GetUTXO mocks base method. +func (m *Diff) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUTXO", arg0) + ret0, _ := ret[0].(*avax.UTXO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUTXO indicates an expected call of GetUTXO. +func (mr *DiffMockRecorder) GetUTXO(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*Diff)(nil).GetUTXO), arg0) +} + +// PutCurrentDelegator mocks base method. +func (m *Diff) PutCurrentDelegator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutCurrentDelegator", arg0) +} + +// PutCurrentDelegator indicates an expected call of PutCurrentDelegator. +func (mr *DiffMockRecorder) PutCurrentDelegator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*Diff)(nil).PutCurrentDelegator), arg0) +} + +// PutCurrentValidator mocks base method. +func (m *Diff) PutCurrentValidator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutCurrentValidator", arg0) +} + +// PutCurrentValidator indicates an expected call of PutCurrentValidator. +func (mr *DiffMockRecorder) PutCurrentValidator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*Diff)(nil).PutCurrentValidator), arg0) +} + +// PutPendingDelegator mocks base method. +func (m *Diff) PutPendingDelegator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutPendingDelegator", arg0) +} + +// PutPendingDelegator indicates an expected call of PutPendingDelegator. +func (mr *DiffMockRecorder) PutPendingDelegator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*Diff)(nil).PutPendingDelegator), arg0) +} + +// PutPendingValidator mocks base method. +func (m *Diff) PutPendingValidator(arg0 *state.Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutPendingValidator", arg0) +} + +// PutPendingValidator indicates an expected call of PutPendingValidator. +func (mr *DiffMockRecorder) PutPendingValidator(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*Diff)(nil).PutPendingValidator), arg0) +} + +// SetCurrentSupply mocks base method. +func (m *Diff) SetCurrentSupply(arg0 ids.ID, arg1 uint64) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetCurrentSupply", arg0, arg1) +} + +// SetCurrentSupply indicates an expected call of SetCurrentSupply. +func (mr *DiffMockRecorder) SetCurrentSupply(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*Diff)(nil).SetCurrentSupply), arg0, arg1) +} + +// SetDelegateeReward mocks base method. +func (m *Diff) SetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID, arg2 uint64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetDelegateeReward", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetDelegateeReward indicates an expected call of SetDelegateeReward. +func (mr *DiffMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*Diff)(nil).SetDelegateeReward), arg0, arg1, arg2) +} + +// SetFeeState mocks base method. +func (m *Diff) SetFeeState(arg0 gas.State) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetFeeState", arg0) +} + +// SetFeeState indicates an expected call of SetFeeState. +func (mr *DiffMockRecorder) SetFeeState(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*Diff)(nil).SetFeeState), arg0) +} + +// SetSubnetManager mocks base method. +func (m *Diff) SetSubnetManager(arg0, arg1 ids.ID, arg2 []byte) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetSubnetManager", arg0, arg1, arg2) +} + +// SetSubnetManager indicates an expected call of SetSubnetManager. +func (mr *DiffMockRecorder) SetSubnetManager(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*Diff)(nil).SetSubnetManager), arg0, arg1, arg2) +} + +// SetSubnetOwner mocks base method. +func (m *Diff) SetSubnetOwner(arg0 ids.ID, arg1 fx.Owner) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetSubnetOwner", arg0, arg1) +} + +// SetSubnetOwner indicates an expected call of SetSubnetOwner. +func (mr *DiffMockRecorder) SetSubnetOwner(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*Diff)(nil).SetSubnetOwner), arg0, arg1) +} + +// SetTimestamp mocks base method. +func (m *Diff) SetTimestamp(arg0 time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetTimestamp", arg0) +} + +// SetTimestamp indicates an expected call of SetTimestamp. +func (mr *DiffMockRecorder) SetTimestamp(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*Diff)(nil).SetTimestamp), arg0) +} diff --git a/vms/platformvm/txs/add_permissionless_delegator_tx_test.go b/vms/platformvm/txs/add_permissionless_delegator_tx_test.go index 152706391aa3..7f5625b6e50c 100644 --- a/vms/platformvm/txs/add_permissionless_delegator_tx_test.go +++ b/vms/platformvm/txs/add_permissionless_delegator_tx_test.go @@ -18,7 +18,8 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "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/components/avax/avaxmock" + "github.com/ava-labs/avalanchego/vms/platformvm/fx/fxmock" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/vms/types" @@ -1583,7 +1584,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { { name: "invalid rewards owner", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessDelegatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(errCustom) return &AddPermissionlessDelegatorTx{ BaseTx: validBaseTx, @@ -1609,10 +1610,10 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { { name: "invalid stake output", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessDelegatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() - stakeOut := avax.NewMockTransferableOut(ctrl) + stakeOut := avaxmock.NewTransferableOut(ctrl) stakeOut.EXPECT().Verify().Return(errCustom) return &AddPermissionlessDelegatorTx{ BaseTx: validBaseTx, @@ -1636,7 +1637,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { { name: "multiple staked assets", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessDelegatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() return &AddPermissionlessDelegatorTx{ BaseTx: validBaseTx, @@ -1670,7 +1671,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { { name: "stake not sorted", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessDelegatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessDelegatorTx{ @@ -1705,7 +1706,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { { name: "stake overflow", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessDelegatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessDelegatorTx{ @@ -1741,7 +1742,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { { name: "weight mismatch", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessDelegatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessDelegatorTx{ @@ -1776,7 +1777,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { { name: "valid subnet validator", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessDelegatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessDelegatorTx{ @@ -1811,7 +1812,7 @@ func TestAddPermissionlessDelegatorTxSyntacticVerify(t *testing.T) { { name: "valid primary network validator", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessDelegatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessDelegatorTx{ diff --git a/vms/platformvm/txs/add_permissionless_validator_tx_test.go b/vms/platformvm/txs/add_permissionless_validator_tx_test.go index 389f28b13e2a..5caa7cd040df 100644 --- a/vms/platformvm/txs/add_permissionless_validator_tx_test.go +++ b/vms/platformvm/txs/add_permissionless_validator_tx_test.go @@ -18,7 +18,8 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/bls" "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/components/avax/avaxmock" + "github.com/ava-labs/avalanchego/vms/platformvm/fx/fxmock" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" @@ -1495,7 +1496,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "invalid rewards owner", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(errCustom) return &AddPermissionlessValidatorTx{ BaseTx: validBaseTx, @@ -1525,7 +1526,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "wrong signer", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() return &AddPermissionlessValidatorTx{ BaseTx: validBaseTx, @@ -1555,10 +1556,10 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "invalid stake output", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() - stakeOut := avax.NewMockTransferableOut(ctrl) + stakeOut := avaxmock.NewTransferableOut(ctrl) stakeOut.EXPECT().Verify().Return(errCustom) return &AddPermissionlessValidatorTx{ BaseTx: validBaseTx, @@ -1586,7 +1587,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "stake overflow", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessValidatorTx{ @@ -1625,7 +1626,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "multiple staked assets", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() return &AddPermissionlessValidatorTx{ BaseTx: validBaseTx, @@ -1663,7 +1664,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "stake not sorted", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessValidatorTx{ @@ -1702,7 +1703,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "weight mismatch", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessValidatorTx{ @@ -1741,7 +1742,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "valid subnet validator", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessValidatorTx{ @@ -1780,7 +1781,7 @@ func TestAddPermissionlessValidatorTxSyntacticVerify(t *testing.T) { { name: "valid primary network validator", txFunc: func(ctrl *gomock.Controller) *AddPermissionlessValidatorTx { - rewardsOwner := fx.NewMockOwner(ctrl) + rewardsOwner := fxmock.NewOwner(ctrl) rewardsOwner.EXPECT().Verify().Return(nil).AnyTimes() assetID := ids.GenerateTestID() return &AddPermissionlessValidatorTx{ diff --git a/vms/platformvm/txs/executor/staker_tx_verification_test.go b/vms/platformvm/txs/executor/staker_tx_verification_test.go index aa8ea9319c81..d2f85b8d87e7 100644 --- a/vms/platformvm/txs/executor/staker_tx_verification_test.go +++ b/vms/platformvm/txs/executor/staker_tx_verification_test.go @@ -22,9 +22,10 @@ import ( "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" - "github.com/ava-labs/avalanchego/vms/platformvm/utxo" + "github.com/ava-labs/avalanchego/vms/platformvm/utxo/utxomock" "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) @@ -119,7 +120,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := state.NewMockChain(ctrl) + mockState := statemock.NewChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now) return mockState }, @@ -143,7 +144,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := state.NewMockChain(ctrl) + mockState := statemock.NewChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after Durango fork activation since now.After(activeForkTime) return mockState }, @@ -169,7 +170,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetTimestamp().Return(verifiedTx.StartTime()).Times(2) return state }, @@ -195,7 +196,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -224,7 +225,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -253,7 +254,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -283,7 +284,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -316,7 +317,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetTimestamp().Return(time.Unix(1, 0)).Times(2) // chain time is after fork activation since time.Unix(1, 0).After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -349,7 +350,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := state.NewMockChain(ctrl) + mockState := statemock.NewChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return mockState @@ -384,7 +385,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := state.NewMockChain(ctrl) + mockState := statemock.NewChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) // State says validator exists @@ -413,7 +414,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := state.NewMockChain(ctrl) + mockState := statemock.NewChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(3) // chain time is after latest fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) mockState.EXPECT().GetCurrentValidator(subnetID, verifiedTx.NodeID()).Return(nil, database.ErrNotFound) @@ -439,7 +440,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) - flowChecker := utxo.NewMockVerifier(ctrl) + flowChecker := utxomock.NewVerifier(ctrl) flowChecker.EXPECT().VerifySpend( gomock.Any(), gomock.Any(), @@ -462,7 +463,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := state.NewMockChain(ctrl) + mockState := statemock.NewChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(3) // chain time is after latest fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) mockState.EXPECT().GetCurrentValidator(subnetID, verifiedTx.NodeID()).Return(nil, database.ErrNotFound) @@ -487,7 +488,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { bootstrapped := &utils.Atomic[bool]{} bootstrapped.Set(true) - flowChecker := utxo.NewMockVerifier(ctrl) + flowChecker := utxomock.NewVerifier(ctrl) flowChecker.EXPECT().VerifySpend( gomock.Any(), gomock.Any(), @@ -510,7 +511,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := state.NewMockChain(ctrl) + mockState := statemock.NewChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(3) // chain time is after Durango fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) mockState.EXPECT().GetCurrentValidator(subnetID, verifiedTx.NodeID()).Return(nil, database.ErrNotFound) @@ -599,7 +600,7 @@ func TestGetValidatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetSubnetTransformation(subnetID).Return(nil, errTest) return state }, @@ -611,7 +612,7 @@ func TestGetValidatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) tx := &txs.Tx{ Unsigned: &txs.AddDelegatorTx{}, } @@ -626,7 +627,7 @@ func TestGetValidatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) tx := &txs.Tx{ Unsigned: &txs.TransformSubnetTx{ AssetID: customAssetID, @@ -716,7 +717,7 @@ func TestGetDelegatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) state.EXPECT().GetSubnetTransformation(subnetID).Return(nil, errTest) return state }, @@ -728,7 +729,7 @@ func TestGetDelegatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) tx := &txs.Tx{ Unsigned: &txs.AddDelegatorTx{}, } @@ -743,7 +744,7 @@ func TestGetDelegatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := state.NewMockChain(ctrl) + state := statemock.NewChain(ctrl) tx := &txs.Tx{ Unsigned: &txs.TransformSubnetTx{ AssetID: customAssetID, diff --git a/vms/platformvm/txs/executor/standard_tx_executor_test.go b/vms/platformvm/txs/executor/standard_tx_executor_test.go index d2a0010f87c5..e0400698fb30 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor_test.go +++ b/vms/platformvm/txs/executor/standard_tx_executor_test.go @@ -27,13 +27,14 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/config" - "github.com/ava-labs/avalanchego/vms/platformvm/fx" + "github.com/ava-labs/avalanchego/vms/platformvm/fx/fxmock" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" - "github.com/ava-labs/avalanchego/vms/platformvm/utxo" + "github.com/ava-labs/avalanchego/vms/platformvm/utxo/utxomock" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" @@ -1721,11 +1722,11 @@ func newRemoveSubnetValidatorTx(t *testing.T) (*txs.RemoveSubnetValidatorTx, *tx // for verifying RemoveSubnetValidatorTx. type removeSubnetValidatorTxVerifyEnv struct { latestForkTime time.Time - fx *fx.MockFx - flowChecker *utxo.MockVerifier + fx *fxmock.Fx + flowChecker *utxomock.Verifier unsignedTx *txs.RemoveSubnetValidatorTx tx *txs.Tx - state *state.MockDiff + state *statemock.Diff staker *state.Staker } @@ -1735,10 +1736,10 @@ func newValidRemoveSubnetValidatorTxVerifyEnv(t *testing.T, ctrl *gomock.Control t.Helper() now := time.Now() - mockFx := fx.NewMockFx(ctrl) - mockFlowChecker := utxo.NewMockVerifier(ctrl) + mockFx := fxmock.NewFx(ctrl) + mockFlowChecker := utxomock.NewVerifier(ctrl) unsignedTx, tx := newRemoveSubnetValidatorTx(t) - mockState := state.NewMockDiff(ctrl) + mockState := statemock.NewDiff(ctrl) return removeSubnetValidatorTxVerifyEnv{ latestForkTime: now, fx: mockFx, @@ -1770,7 +1771,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { // Set dependency expectations. env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil).Times(1) - subnetOwner := fx.NewMockOwner(ctrl) + subnetOwner := fxmock.NewOwner(ctrl) env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil).Times(1) env.fx.EXPECT().VerifyPermission(env.unsignedTx, env.unsignedTx.SubnetAuth, env.tx.Creds[len(env.tx.Creds)-1], subnetOwner).Return(nil).Times(1) env.flowChecker.EXPECT().VerifySpend( @@ -1807,7 +1808,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) // Setting the subnet ID to the Primary Network ID makes the tx fail syntactic verification env.tx.Unsigned.(*txs.RemoveSubnetValidatorTx).Subnet = constants.PrimaryNetworkID - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() cfg := &config.Config{ @@ -1835,7 +1836,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { name: "node isn't a validator of the subnet", newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(nil, database.ErrNotFound) env.state.EXPECT().GetPendingValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(nil, database.ErrNotFound) @@ -1900,7 +1901,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) // Remove credentials env.tx.Creds = nil - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) @@ -1929,7 +1930,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { name: "can't find subnet", newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(nil, database.ErrNotFound) @@ -1959,10 +1960,10 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { name: "no permission to remove validator", newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) - subnetOwner := fx.NewMockOwner(ctrl) + subnetOwner := fxmock.NewOwner(ctrl) env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil) env.fx.EXPECT().VerifyPermission(gomock.Any(), env.unsignedTx.SubnetAuth, env.tx.Creds[len(env.tx.Creds)-1], subnetOwner).Return(errTest) @@ -1991,10 +1992,10 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { name: "flow checker failed", newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) - subnetOwner := fx.NewMockOwner(ctrl) + subnetOwner := fxmock.NewOwner(ctrl) env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil) env.fx.EXPECT().VerifyPermission(gomock.Any(), env.unsignedTx.SubnetAuth, env.tx.Creds[len(env.tx.Creds)-1], subnetOwner).Return(nil) env.flowChecker.EXPECT().VerifySpend( @@ -2138,11 +2139,11 @@ func newTransformSubnetTx(t *testing.T) (*txs.TransformSubnetTx, *txs.Tx) { // for verifying TransformSubnetTx. type transformSubnetTxVerifyEnv struct { latestForkTime time.Time - fx *fx.MockFx - flowChecker *utxo.MockVerifier + fx *fxmock.Fx + flowChecker *utxomock.Verifier unsignedTx *txs.TransformSubnetTx tx *txs.Tx - state *state.MockDiff + state *statemock.Diff staker *state.Staker } @@ -2152,10 +2153,10 @@ func newValidTransformSubnetTxVerifyEnv(t *testing.T, ctrl *gomock.Controller) t t.Helper() now := time.Now() - mockFx := fx.NewMockFx(ctrl) - mockFlowChecker := utxo.NewMockVerifier(ctrl) + mockFx := fxmock.NewFx(ctrl) + mockFlowChecker := utxomock.NewVerifier(ctrl) unsignedTx, tx := newTransformSubnetTx(t) - mockState := state.NewMockDiff(ctrl) + mockState := statemock.NewDiff(ctrl) return transformSubnetTxVerifyEnv{ latestForkTime: now, fx: mockFx, @@ -2184,7 +2185,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) // Setting the tx to nil makes the tx fail syntactic verification env.tx.Unsigned = (*txs.TransformSubnetTx)(nil) - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() cfg := &config.Config{ @@ -2213,7 +2214,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { newExecutor: func(ctrl *gomock.Controller) (*txs.TransformSubnetTx, *StandardTxExecutor) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) env.unsignedTx.MaxStakeDuration = math.MaxUint32 - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() cfg := &config.Config{ @@ -2243,7 +2244,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) // Remove credentials env.tx.Creds = nil - env.state = state.NewMockDiff(ctrl) + env.state = statemock.NewDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() cfg := &config.Config{ @@ -2273,8 +2274,8 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { name: "flow checker failed", newExecutor: func(ctrl *gomock.Controller) (*txs.TransformSubnetTx, *StandardTxExecutor) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) - env.state = state.NewMockDiff(ctrl) - subnetOwner := fx.NewMockOwner(ctrl) + env.state = statemock.NewDiff(ctrl) + subnetOwner := fxmock.NewOwner(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil) env.state.EXPECT().GetSubnetManager(env.unsignedTx.Subnet).Return(ids.Empty, nil, database.ErrNotFound).Times(1) @@ -2313,7 +2314,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) // Set dependency expectations. - subnetOwner := fx.NewMockOwner(ctrl) + subnetOwner := fxmock.NewOwner(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil).Times(1) env.state.EXPECT().GetSubnetManager(env.unsignedTx.Subnet).Return(ids.GenerateTestID(), make([]byte, 20), nil) @@ -2348,7 +2349,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) // Set dependency expectations. - subnetOwner := fx.NewMockOwner(ctrl) + subnetOwner := fxmock.NewOwner(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil).Times(1) env.state.EXPECT().GetSubnetManager(env.unsignedTx.Subnet).Return(ids.Empty, nil, database.ErrNotFound).Times(1) diff --git a/vms/platformvm/txs/mempool/mock_mempool.go b/vms/platformvm/txs/mempool/mempoolmock/mempool.go similarity index 56% rename from vms/platformvm/txs/mempool/mock_mempool.go rename to vms/platformvm/txs/mempool/mempoolmock/mempool.go index c47f42e92718..7d81182575c5 100644 --- a/vms/platformvm/txs/mempool/mock_mempool.go +++ b/vms/platformvm/txs/mempool/mempoolmock/mempool.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=mempool -destination=vms/platformvm/txs/mempool/mock_mempool.go github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool Mempool +// mockgen -package=mempoolmock -destination=vms/platformvm/txs/mempool/mempoolmock/mempool.go -mock_names=Mempool=Mempool github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool Mempool // -// Package mempool is a generated GoMock package. -package mempool +// Package mempoolmock is a generated GoMock package. +package mempoolmock import ( reflect "reflect" @@ -17,31 +17,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockMempool is a mock of Mempool interface. -type MockMempool struct { +// Mempool is a mock of Mempool interface. +type Mempool struct { ctrl *gomock.Controller - recorder *MockMempoolMockRecorder + recorder *MempoolMockRecorder } -// MockMempoolMockRecorder is the mock recorder for MockMempool. -type MockMempoolMockRecorder struct { - mock *MockMempool +// MempoolMockRecorder is the mock recorder for Mempool. +type MempoolMockRecorder struct { + mock *Mempool } -// NewMockMempool creates a new mock instance. -func NewMockMempool(ctrl *gomock.Controller) *MockMempool { - mock := &MockMempool{ctrl: ctrl} - mock.recorder = &MockMempoolMockRecorder{mock} +// NewMempool creates a new mock instance. +func NewMempool(ctrl *gomock.Controller) *Mempool { + mock := &Mempool{ctrl: ctrl} + mock.recorder = &MempoolMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockMempool) EXPECT() *MockMempoolMockRecorder { +func (m *Mempool) EXPECT() *MempoolMockRecorder { return m.recorder } // Add mocks base method. -func (m *MockMempool) Add(arg0 *txs.Tx) error { +func (m *Mempool) Add(arg0 *txs.Tx) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Add", arg0) ret0, _ := ret[0].(error) @@ -49,13 +49,13 @@ func (m *MockMempool) Add(arg0 *txs.Tx) error { } // Add indicates an expected call of Add. -func (mr *MockMempoolMockRecorder) Add(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) Add(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockMempool)(nil).Add), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*Mempool)(nil).Add), arg0) } // Get mocks base method. -func (m *MockMempool) Get(arg0 ids.ID) (*txs.Tx, bool) { +func (m *Mempool) Get(arg0 ids.ID) (*txs.Tx, bool) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get", arg0) ret0, _ := ret[0].(*txs.Tx) @@ -64,13 +64,13 @@ func (m *MockMempool) Get(arg0 ids.ID) (*txs.Tx, bool) { } // Get indicates an expected call of Get. -func (mr *MockMempoolMockRecorder) Get(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) Get(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockMempool)(nil).Get), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*Mempool)(nil).Get), arg0) } // GetDropReason mocks base method. -func (m *MockMempool) GetDropReason(arg0 ids.ID) error { +func (m *Mempool) GetDropReason(arg0 ids.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetDropReason", arg0) ret0, _ := ret[0].(error) @@ -78,25 +78,25 @@ func (m *MockMempool) GetDropReason(arg0 ids.ID) error { } // GetDropReason indicates an expected call of GetDropReason. -func (mr *MockMempoolMockRecorder) GetDropReason(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) GetDropReason(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDropReason", reflect.TypeOf((*MockMempool)(nil).GetDropReason), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDropReason", reflect.TypeOf((*Mempool)(nil).GetDropReason), arg0) } // Iterate mocks base method. -func (m *MockMempool) Iterate(arg0 func(*txs.Tx) bool) { +func (m *Mempool) Iterate(arg0 func(*txs.Tx) bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "Iterate", arg0) } // Iterate indicates an expected call of Iterate. -func (mr *MockMempoolMockRecorder) Iterate(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) Iterate(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Iterate", reflect.TypeOf((*MockMempool)(nil).Iterate), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Iterate", reflect.TypeOf((*Mempool)(nil).Iterate), arg0) } // Len mocks base method. -func (m *MockMempool) Len() int { +func (m *Mempool) Len() int { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Len") ret0, _ := ret[0].(int) @@ -104,25 +104,25 @@ func (m *MockMempool) Len() int { } // Len indicates an expected call of Len. -func (mr *MockMempoolMockRecorder) Len() *gomock.Call { +func (mr *MempoolMockRecorder) Len() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Len", reflect.TypeOf((*MockMempool)(nil).Len)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Len", reflect.TypeOf((*Mempool)(nil).Len)) } // MarkDropped mocks base method. -func (m *MockMempool) MarkDropped(arg0 ids.ID, arg1 error) { +func (m *Mempool) MarkDropped(arg0 ids.ID, arg1 error) { m.ctrl.T.Helper() m.ctrl.Call(m, "MarkDropped", arg0, arg1) } // MarkDropped indicates an expected call of MarkDropped. -func (mr *MockMempoolMockRecorder) MarkDropped(arg0, arg1 any) *gomock.Call { +func (mr *MempoolMockRecorder) MarkDropped(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkDropped", reflect.TypeOf((*MockMempool)(nil).MarkDropped), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MarkDropped", reflect.TypeOf((*Mempool)(nil).MarkDropped), arg0, arg1) } // Peek mocks base method. -func (m *MockMempool) Peek() (*txs.Tx, bool) { +func (m *Mempool) Peek() (*txs.Tx, bool) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Peek") ret0, _ := ret[0].(*txs.Tx) @@ -131,13 +131,13 @@ func (m *MockMempool) Peek() (*txs.Tx, bool) { } // Peek indicates an expected call of Peek. -func (mr *MockMempoolMockRecorder) Peek() *gomock.Call { +func (mr *MempoolMockRecorder) Peek() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Peek", reflect.TypeOf((*MockMempool)(nil).Peek)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Peek", reflect.TypeOf((*Mempool)(nil).Peek)) } // Remove mocks base method. -func (m *MockMempool) Remove(arg0 ...*txs.Tx) { +func (m *Mempool) Remove(arg0 ...*txs.Tx) { m.ctrl.T.Helper() varargs := []any{} for _, a := range arg0 { @@ -147,19 +147,19 @@ func (m *MockMempool) Remove(arg0 ...*txs.Tx) { } // Remove indicates an expected call of Remove. -func (mr *MockMempoolMockRecorder) Remove(arg0 ...any) *gomock.Call { +func (mr *MempoolMockRecorder) Remove(arg0 ...any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockMempool)(nil).Remove), arg0...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*Mempool)(nil).Remove), arg0...) } // RequestBuildBlock mocks base method. -func (m *MockMempool) RequestBuildBlock(arg0 bool) { +func (m *Mempool) RequestBuildBlock(arg0 bool) { m.ctrl.T.Helper() m.ctrl.Call(m, "RequestBuildBlock", arg0) } // RequestBuildBlock indicates an expected call of RequestBuildBlock. -func (mr *MockMempoolMockRecorder) RequestBuildBlock(arg0 any) *gomock.Call { +func (mr *MempoolMockRecorder) RequestBuildBlock(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RequestBuildBlock", reflect.TypeOf((*MockMempool)(nil).RequestBuildBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RequestBuildBlock", reflect.TypeOf((*Mempool)(nil).RequestBuildBlock), arg0) } diff --git a/vms/platformvm/txs/remove_subnet_validator_tx_test.go b/vms/platformvm/txs/remove_subnet_validator_tx_test.go index 02439701637a..605190977957 100644 --- a/vms/platformvm/txs/remove_subnet_validator_tx_test.go +++ b/vms/platformvm/txs/remove_subnet_validator_tx_test.go @@ -17,7 +17,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/verify" + "github.com/ava-labs/avalanchego/vms/components/verify/verifymock" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/vms/types" @@ -597,7 +597,7 @@ func TestRemoveSubnetValidatorTxSyntacticVerify(t *testing.T) { name: "invalid subnetAuth", txFunc: func(ctrl *gomock.Controller) *RemoveSubnetValidatorTx { // This SubnetAuth fails verification. - invalidSubnetAuth := verify.NewMockVerifiable(ctrl) + invalidSubnetAuth := verifymock.NewVerifiable(ctrl) invalidSubnetAuth.EXPECT().Verify().Return(errInvalidSubnetAuth) return &RemoveSubnetValidatorTx{ // Set subnetID so we don't error on that check. @@ -614,7 +614,7 @@ func TestRemoveSubnetValidatorTxSyntacticVerify(t *testing.T) { name: "passes verification", txFunc: func(ctrl *gomock.Controller) *RemoveSubnetValidatorTx { // This SubnetAuth passes verification. - validSubnetAuth := verify.NewMockVerifiable(ctrl) + validSubnetAuth := verifymock.NewVerifiable(ctrl) validSubnetAuth.EXPECT().Verify().Return(nil) return &RemoveSubnetValidatorTx{ // Set subnetID so we don't error on that check. diff --git a/vms/platformvm/txs/transfer_subnet_ownership_tx_test.go b/vms/platformvm/txs/transfer_subnet_ownership_tx_test.go index ffac26536a22..a84a1492920e 100644 --- a/vms/platformvm/txs/transfer_subnet_ownership_tx_test.go +++ b/vms/platformvm/txs/transfer_subnet_ownership_tx_test.go @@ -16,8 +16,8 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/verify" - "github.com/ava-labs/avalanchego/vms/platformvm/fx" + "github.com/ava-labs/avalanchego/vms/components/verify/verifymock" + "github.com/ava-labs/avalanchego/vms/platformvm/fx/fxmock" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/vms/types" @@ -620,7 +620,7 @@ func TestTransferSubnetOwnershipTxSyntacticVerify(t *testing.T) { name: "invalid subnetAuth", txFunc: func(ctrl *gomock.Controller) *TransferSubnetOwnershipTx { // This SubnetAuth fails verification. - invalidSubnetAuth := verify.NewMockVerifiable(ctrl) + invalidSubnetAuth := verifymock.NewVerifiable(ctrl) invalidSubnetAuth.EXPECT().Verify().Return(errInvalidSubnetAuth) return &TransferSubnetOwnershipTx{ // Set subnetID so we don't error on that check. @@ -635,9 +635,9 @@ func TestTransferSubnetOwnershipTxSyntacticVerify(t *testing.T) { name: "passes verification", txFunc: func(ctrl *gomock.Controller) *TransferSubnetOwnershipTx { // This SubnetAuth passes verification. - validSubnetAuth := verify.NewMockVerifiable(ctrl) + validSubnetAuth := verifymock.NewVerifiable(ctrl) validSubnetAuth.EXPECT().Verify().Return(nil) - mockOwner := fx.NewMockOwner(ctrl) + mockOwner := fxmock.NewOwner(ctrl) mockOwner.EXPECT().Verify().Return(nil) return &TransferSubnetOwnershipTx{ // Set subnetID so we don't error on that check. diff --git a/vms/platformvm/txs/transform_subnet_tx_test.go b/vms/platformvm/txs/transform_subnet_tx_test.go index 30f3c492c351..f007a49e32b7 100644 --- a/vms/platformvm/txs/transform_subnet_tx_test.go +++ b/vms/platformvm/txs/transform_subnet_tx_test.go @@ -16,7 +16,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/components/verify" + "github.com/ava-labs/avalanchego/vms/components/verify/verifymock" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -960,7 +960,7 @@ func TestTransformSubnetTxSyntacticVerify(t *testing.T) { name: "invalid subnetAuth", txFunc: func(ctrl *gomock.Controller) *TransformSubnetTx { // This SubnetAuth fails verification. - invalidSubnetAuth := verify.NewMockVerifiable(ctrl) + invalidSubnetAuth := verifymock.NewVerifiable(ctrl) invalidSubnetAuth.EXPECT().Verify().Return(errInvalidSubnetAuth) return &TransformSubnetTx{ BaseTx: validBaseTx, @@ -1010,7 +1010,7 @@ func TestTransformSubnetTxSyntacticVerify(t *testing.T) { name: "passes verification", txFunc: func(ctrl *gomock.Controller) *TransformSubnetTx { // This SubnetAuth passes verification. - validSubnetAuth := verify.NewMockVerifiable(ctrl) + validSubnetAuth := verifymock.NewVerifiable(ctrl) validSubnetAuth.EXPECT().Verify().Return(nil) return &TransformSubnetTx{ BaseTx: validBaseTx, diff --git a/vms/platformvm/txs/mock_unsigned_tx.go b/vms/platformvm/txs/txsmock/unsigned_tx.go similarity index 56% rename from vms/platformvm/txs/mock_unsigned_tx.go rename to vms/platformvm/txs/txsmock/unsigned_tx.go index f775c5203a4f..a7ba0daac896 100644 --- a/vms/platformvm/txs/mock_unsigned_tx.go +++ b/vms/platformvm/txs/txsmock/unsigned_tx.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -source=vms/platformvm/txs/unsigned_tx.go -destination=vms/platformvm/txs/mock_unsigned_tx.go -package=txs -exclude_interfaces= +// mockgen -source=vms/platformvm/txs/unsigned_tx.go -destination=vms/platformvm/txs/txsmock/unsigned_tx.go -package=txsmock -exclude_interfaces= -mock_names=UnsignedTx=UnsignedTx // -// Package txs is a generated GoMock package. -package txs +// Package txsmock is a generated GoMock package. +package txsmock import ( reflect "reflect" @@ -16,34 +16,35 @@ import ( snow "github.com/ava-labs/avalanchego/snow" set "github.com/ava-labs/avalanchego/utils/set" avax "github.com/ava-labs/avalanchego/vms/components/avax" + txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" gomock "go.uber.org/mock/gomock" ) -// MockUnsignedTx is a mock of UnsignedTx interface. -type MockUnsignedTx struct { +// UnsignedTx is a mock of UnsignedTx interface. +type UnsignedTx struct { ctrl *gomock.Controller - recorder *MockUnsignedTxMockRecorder + recorder *UnsignedTxMockRecorder } -// MockUnsignedTxMockRecorder is the mock recorder for MockUnsignedTx. -type MockUnsignedTxMockRecorder struct { - mock *MockUnsignedTx +// UnsignedTxMockRecorder is the mock recorder for UnsignedTx. +type UnsignedTxMockRecorder struct { + mock *UnsignedTx } -// NewMockUnsignedTx creates a new mock instance. -func NewMockUnsignedTx(ctrl *gomock.Controller) *MockUnsignedTx { - mock := &MockUnsignedTx{ctrl: ctrl} - mock.recorder = &MockUnsignedTxMockRecorder{mock} +// NewUnsignedTx creates a new mock instance. +func NewUnsignedTx(ctrl *gomock.Controller) *UnsignedTx { + mock := &UnsignedTx{ctrl: ctrl} + mock.recorder = &UnsignedTxMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockUnsignedTx) EXPECT() *MockUnsignedTxMockRecorder { +func (m *UnsignedTx) EXPECT() *UnsignedTxMockRecorder { return m.recorder } // Bytes mocks base method. -func (m *MockUnsignedTx) Bytes() []byte { +func (m *UnsignedTx) Bytes() []byte { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Bytes") ret0, _ := ret[0].([]byte) @@ -51,25 +52,25 @@ func (m *MockUnsignedTx) Bytes() []byte { } // Bytes indicates an expected call of Bytes. -func (mr *MockUnsignedTxMockRecorder) Bytes() *gomock.Call { +func (mr *UnsignedTxMockRecorder) Bytes() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*MockUnsignedTx)(nil).Bytes)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bytes", reflect.TypeOf((*UnsignedTx)(nil).Bytes)) } // InitCtx mocks base method. -func (m *MockUnsignedTx) InitCtx(ctx *snow.Context) { +func (m *UnsignedTx) InitCtx(ctx *snow.Context) { m.ctrl.T.Helper() m.ctrl.Call(m, "InitCtx", ctx) } // InitCtx indicates an expected call of InitCtx. -func (mr *MockUnsignedTxMockRecorder) InitCtx(ctx any) *gomock.Call { +func (mr *UnsignedTxMockRecorder) InitCtx(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*MockUnsignedTx)(nil).InitCtx), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InitCtx", reflect.TypeOf((*UnsignedTx)(nil).InitCtx), ctx) } // InputIDs mocks base method. -func (m *MockUnsignedTx) InputIDs() set.Set[ids.ID] { +func (m *UnsignedTx) InputIDs() set.Set[ids.ID] { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "InputIDs") ret0, _ := ret[0].(set.Set[ids.ID]) @@ -77,13 +78,13 @@ func (m *MockUnsignedTx) InputIDs() set.Set[ids.ID] { } // InputIDs indicates an expected call of InputIDs. -func (mr *MockUnsignedTxMockRecorder) InputIDs() *gomock.Call { +func (mr *UnsignedTxMockRecorder) InputIDs() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InputIDs", reflect.TypeOf((*MockUnsignedTx)(nil).InputIDs)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "InputIDs", reflect.TypeOf((*UnsignedTx)(nil).InputIDs)) } // Outputs mocks base method. -func (m *MockUnsignedTx) Outputs() []*avax.TransferableOutput { +func (m *UnsignedTx) Outputs() []*avax.TransferableOutput { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Outputs") ret0, _ := ret[0].([]*avax.TransferableOutput) @@ -91,25 +92,25 @@ func (m *MockUnsignedTx) Outputs() []*avax.TransferableOutput { } // Outputs indicates an expected call of Outputs. -func (mr *MockUnsignedTxMockRecorder) Outputs() *gomock.Call { +func (mr *UnsignedTxMockRecorder) Outputs() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Outputs", reflect.TypeOf((*MockUnsignedTx)(nil).Outputs)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Outputs", reflect.TypeOf((*UnsignedTx)(nil).Outputs)) } // SetBytes mocks base method. -func (m *MockUnsignedTx) SetBytes(unsignedBytes []byte) { +func (m *UnsignedTx) SetBytes(unsignedBytes []byte) { m.ctrl.T.Helper() m.ctrl.Call(m, "SetBytes", unsignedBytes) } // SetBytes indicates an expected call of SetBytes. -func (mr *MockUnsignedTxMockRecorder) SetBytes(unsignedBytes any) *gomock.Call { +func (mr *UnsignedTxMockRecorder) SetBytes(unsignedBytes any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetBytes", reflect.TypeOf((*MockUnsignedTx)(nil).SetBytes), unsignedBytes) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetBytes", reflect.TypeOf((*UnsignedTx)(nil).SetBytes), unsignedBytes) } // SyntacticVerify mocks base method. -func (m *MockUnsignedTx) SyntacticVerify(ctx *snow.Context) error { +func (m *UnsignedTx) SyntacticVerify(ctx *snow.Context) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SyntacticVerify", ctx) ret0, _ := ret[0].(error) @@ -117,13 +118,13 @@ func (m *MockUnsignedTx) SyntacticVerify(ctx *snow.Context) error { } // SyntacticVerify indicates an expected call of SyntacticVerify. -func (mr *MockUnsignedTxMockRecorder) SyntacticVerify(ctx any) *gomock.Call { +func (mr *UnsignedTxMockRecorder) SyntacticVerify(ctx any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SyntacticVerify", reflect.TypeOf((*MockUnsignedTx)(nil).SyntacticVerify), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SyntacticVerify", reflect.TypeOf((*UnsignedTx)(nil).SyntacticVerify), ctx) } // Visit mocks base method. -func (m *MockUnsignedTx) Visit(visitor Visitor) error { +func (m *UnsignedTx) Visit(visitor txs.Visitor) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Visit", visitor) ret0, _ := ret[0].(error) @@ -131,7 +132,7 @@ func (m *MockUnsignedTx) Visit(visitor Visitor) error { } // Visit indicates an expected call of Visit. -func (mr *MockUnsignedTxMockRecorder) Visit(visitor any) *gomock.Call { +func (mr *UnsignedTxMockRecorder) Visit(visitor any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Visit", reflect.TypeOf((*MockUnsignedTx)(nil).Visit), visitor) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Visit", reflect.TypeOf((*UnsignedTx)(nil).Visit), visitor) } diff --git a/vms/platformvm/utxo/mock_verifier.go b/vms/platformvm/utxo/mock_verifier.go deleted file mode 100644 index 0447806cb7ae..000000000000 --- a/vms/platformvm/utxo/mock_verifier.go +++ /dev/null @@ -1,71 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/platformvm/utxo (interfaces: Verifier) -// -// Generated by this command: -// -// mockgen -package=utxo -destination=vms/platformvm/utxo/mock_verifier.go github.com/ava-labs/avalanchego/vms/platformvm/utxo Verifier -// - -// Package utxo is a generated GoMock package. -package utxo - -import ( - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - avax "github.com/ava-labs/avalanchego/vms/components/avax" - verify "github.com/ava-labs/avalanchego/vms/components/verify" - txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" - gomock "go.uber.org/mock/gomock" -) - -// MockVerifier is a mock of Verifier interface. -type MockVerifier struct { - ctrl *gomock.Controller - recorder *MockVerifierMockRecorder -} - -// MockVerifierMockRecorder is the mock recorder for MockVerifier. -type MockVerifierMockRecorder struct { - mock *MockVerifier -} - -// NewMockVerifier creates a new mock instance. -func NewMockVerifier(ctrl *gomock.Controller) *MockVerifier { - mock := &MockVerifier{ctrl: ctrl} - mock.recorder = &MockVerifierMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVerifier) EXPECT() *MockVerifierMockRecorder { - return m.recorder -} - -// VerifySpend mocks base method. -func (m *MockVerifier) VerifySpend(arg0 txs.UnsignedTx, arg1 avax.UTXOGetter, arg2 []*avax.TransferableInput, arg3 []*avax.TransferableOutput, arg4 []verify.Verifiable, arg5 map[ids.ID]uint64) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "VerifySpend", arg0, arg1, arg2, arg3, arg4, arg5) - ret0, _ := ret[0].(error) - return ret0 -} - -// VerifySpend indicates an expected call of VerifySpend. -func (mr *MockVerifierMockRecorder) VerifySpend(arg0, arg1, arg2, arg3, arg4, arg5 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifySpend", reflect.TypeOf((*MockVerifier)(nil).VerifySpend), arg0, arg1, arg2, arg3, arg4, arg5) -} - -// VerifySpendUTXOs mocks base method. -func (m *MockVerifier) VerifySpendUTXOs(arg0 txs.UnsignedTx, arg1 []*avax.UTXO, arg2 []*avax.TransferableInput, arg3 []*avax.TransferableOutput, arg4 []verify.Verifiable, arg5 map[ids.ID]uint64) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "VerifySpendUTXOs", arg0, arg1, arg2, arg3, arg4, arg5) - ret0, _ := ret[0].(error) - return ret0 -} - -// VerifySpendUTXOs indicates an expected call of VerifySpendUTXOs. -func (mr *MockVerifierMockRecorder) VerifySpendUTXOs(arg0, arg1, arg2, arg3, arg4, arg5 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifySpendUTXOs", reflect.TypeOf((*MockVerifier)(nil).VerifySpendUTXOs), arg0, arg1, arg2, arg3, arg4, arg5) -} diff --git a/vms/platformvm/utxo/utxomock/verifier.go b/vms/platformvm/utxo/utxomock/verifier.go new file mode 100644 index 000000000000..9da143719b87 --- /dev/null +++ b/vms/platformvm/utxo/utxomock/verifier.go @@ -0,0 +1,71 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/platformvm/utxo (interfaces: Verifier) +// +// Generated by this command: +// +// mockgen -package=utxomock -destination=vms/platformvm/utxo/utxomock/verifier.go -mock_names=Verifier=Verifier github.com/ava-labs/avalanchego/vms/platformvm/utxo Verifier +// + +// Package utxomock is a generated GoMock package. +package utxomock + +import ( + reflect "reflect" + + ids "github.com/ava-labs/avalanchego/ids" + avax "github.com/ava-labs/avalanchego/vms/components/avax" + verify "github.com/ava-labs/avalanchego/vms/components/verify" + txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" + gomock "go.uber.org/mock/gomock" +) + +// Verifier is a mock of Verifier interface. +type Verifier struct { + ctrl *gomock.Controller + recorder *VerifierMockRecorder +} + +// VerifierMockRecorder is the mock recorder for Verifier. +type VerifierMockRecorder struct { + mock *Verifier +} + +// NewVerifier creates a new mock instance. +func NewVerifier(ctrl *gomock.Controller) *Verifier { + mock := &Verifier{ctrl: ctrl} + mock.recorder = &VerifierMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Verifier) EXPECT() *VerifierMockRecorder { + return m.recorder +} + +// VerifySpend mocks base method. +func (m *Verifier) VerifySpend(arg0 txs.UnsignedTx, arg1 avax.UTXOGetter, arg2 []*avax.TransferableInput, arg3 []*avax.TransferableOutput, arg4 []verify.Verifiable, arg5 map[ids.ID]uint64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "VerifySpend", arg0, arg1, arg2, arg3, arg4, arg5) + ret0, _ := ret[0].(error) + return ret0 +} + +// VerifySpend indicates an expected call of VerifySpend. +func (mr *VerifierMockRecorder) VerifySpend(arg0, arg1, arg2, arg3, arg4, arg5 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifySpend", reflect.TypeOf((*Verifier)(nil).VerifySpend), arg0, arg1, arg2, arg3, arg4, arg5) +} + +// VerifySpendUTXOs mocks base method. +func (m *Verifier) VerifySpendUTXOs(arg0 txs.UnsignedTx, arg1 []*avax.UTXO, arg2 []*avax.TransferableInput, arg3 []*avax.TransferableOutput, arg4 []verify.Verifiable, arg5 map[ids.ID]uint64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "VerifySpendUTXOs", arg0, arg1, arg2, arg3, arg4, arg5) + ret0, _ := ret[0].(error) + return ret0 +} + +// VerifySpendUTXOs indicates an expected call of VerifySpendUTXOs. +func (mr *VerifierMockRecorder) VerifySpendUTXOs(arg0, arg1, arg2, arg3, arg4, arg5 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifySpendUTXOs", reflect.TypeOf((*Verifier)(nil).VerifySpendUTXOs), arg0, arg1, arg2, arg3, arg4, arg5) +} diff --git a/vms/platformvm/warp/signature_test.go b/vms/platformvm/warp/signature_test.go index eedec396fcdc..7cb61296c1da 100644 --- a/vms/platformvm/warp/signature_test.go +++ b/vms/platformvm/warp/signature_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" @@ -166,7 +167,7 @@ func TestSignatureVerification(t *testing.T) { name: "can't get subnetID", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, errTest) return state }, @@ -193,7 +194,7 @@ func TestSignatureVerification(t *testing.T) { name: "can't get validator set", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(nil, errTest) return state @@ -221,7 +222,7 @@ func TestSignatureVerification(t *testing.T) { name: "weight overflow", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(map[ids.NodeID]*validators.GetValidatorOutput{ testVdrs[0].nodeID: { @@ -256,7 +257,7 @@ func TestSignatureVerification(t *testing.T) { name: "invalid bit set index", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -287,7 +288,7 @@ func TestSignatureVerification(t *testing.T) { name: "unknown index", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -321,7 +322,7 @@ func TestSignatureVerification(t *testing.T) { name: "insufficient weight", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -366,7 +367,7 @@ func TestSignatureVerification(t *testing.T) { name: "can't parse sig", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -401,7 +402,7 @@ func TestSignatureVerification(t *testing.T) { name: "no validators", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(nil, nil) return state @@ -437,7 +438,7 @@ func TestSignatureVerification(t *testing.T) { name: "invalid signature (substitute)", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -482,7 +483,7 @@ func TestSignatureVerification(t *testing.T) { name: "invalid signature (missing one)", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -523,7 +524,7 @@ func TestSignatureVerification(t *testing.T) { name: "invalid signature (extra one)", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -569,7 +570,7 @@ func TestSignatureVerification(t *testing.T) { name: "valid signature", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -614,7 +615,7 @@ func TestSignatureVerification(t *testing.T) { name: "valid signature (boundary)", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(vdrs, nil) return state @@ -659,7 +660,7 @@ func TestSignatureVerification(t *testing.T) { name: "valid signature (missing key)", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(map[ids.NodeID]*validators.GetValidatorOutput{ testVdrs[0].nodeID: { @@ -721,7 +722,7 @@ func TestSignatureVerification(t *testing.T) { name: "valid signature (duplicate key)", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetSubnetID(gomock.Any(), sourceChainID).Return(subnetID, nil) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(map[ids.NodeID]*validators.GetValidatorOutput{ testVdrs[0].nodeID: { @@ -781,7 +782,7 @@ func TestSignatureVerification(t *testing.T) { name: "incorrect networkID", networkID: constants.UnitTestID, stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) return state }, quorumNum: 1, diff --git a/vms/platformvm/warp/validator_test.go b/vms/platformvm/warp/validator_test.go index 4e9d64cc3f67..15e811073149 100644 --- a/vms/platformvm/warp/validator_test.go +++ b/vms/platformvm/warp/validator_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" "github.com/ava-labs/avalanchego/snow/validators/validatorstest" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/set" @@ -32,7 +33,7 @@ func TestGetCanonicalValidatorSet(t *testing.T) { { name: "can't get validator set", stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return(nil, errTest) return state }, @@ -41,7 +42,7 @@ func TestGetCanonicalValidatorSet(t *testing.T) { { name: "all validators have public keys; no duplicate pub keys", stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return( map[ids.NodeID]*validators.GetValidatorOutput{ testVdrs[0].nodeID: { @@ -66,7 +67,7 @@ func TestGetCanonicalValidatorSet(t *testing.T) { { name: "all validators have public keys; duplicate pub keys", stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return( map[ids.NodeID]*validators.GetValidatorOutput{ testVdrs[0].nodeID: { @@ -107,7 +108,7 @@ func TestGetCanonicalValidatorSet(t *testing.T) { { name: "validator without public key; no duplicate pub keys", stateF: func(ctrl *gomock.Controller) validators.State { - state := validators.NewMockState(ctrl) + state := validatorsmock.NewState(ctrl) state.EXPECT().GetValidatorSet(gomock.Any(), pChainHeight, subnetID).Return( map[ids.NodeID]*validators.GetValidatorOutput{ testVdrs[0].nodeID: { diff --git a/vms/proposervm/block_test.go b/vms/proposervm/block_test.go index 4603a30f40d4..9713891c808e 100644 --- a/vms/proposervm/block_test.go +++ b/vms/proposervm/block_test.go @@ -19,15 +19,19 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowman" + "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmanmock" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" "github.com/ava-labs/avalanchego/staking" "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/vms/proposervm/proposer" - "github.com/ava-labs/avalanchego/vms/proposervm/scheduler" + "github.com/ava-labs/avalanchego/vms/proposervm/proposer/proposermock" + "github.com/ava-labs/avalanchego/vms/proposervm/scheduler/schedulermock" ) // Assert that when the underlying VM implements ChainVMWithBuildBlockContext @@ -47,25 +51,25 @@ func TestPostForkCommonComponents_buildChild(t *testing.T) { blkID = ids.GenerateTestID() ) - innerBlk := snowmantest.NewMockBlock(ctrl) + innerBlk := snowmanmock.NewBlock(ctrl) innerBlk.EXPECT().ID().Return(blkID).AnyTimes() innerBlk.EXPECT().Height().Return(parentHeight + 1).AnyTimes() - builtBlk := snowmantest.NewMockBlock(ctrl) + builtBlk := snowmanmock.NewBlock(ctrl) builtBlk.EXPECT().Bytes().Return([]byte{1, 2, 3}).AnyTimes() builtBlk.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() builtBlk.EXPECT().Height().Return(pChainHeight).AnyTimes() - innerVM := block.NewMockChainVM(ctrl) - innerBlockBuilderVM := block.NewMockBuildBlockWithContextChainVM(ctrl) + innerVM := blockmock.NewChainVM(ctrl) + innerBlockBuilderVM := blockmock.NewBuildBlockWithContextChainVM(ctrl) innerBlockBuilderVM.EXPECT().BuildBlockWithContext(gomock.Any(), &block.Context{ PChainHeight: pChainHeight - 1, }).Return(builtBlk, nil).AnyTimes() - vdrState := validators.NewMockState(ctrl) + vdrState := validatorsmock.NewState(ctrl) vdrState.EXPECT().GetMinimumHeight(context.Background()).Return(pChainHeight, nil).AnyTimes() - windower := proposer.NewMockWindower(ctrl) + windower := proposermock.NewWindower(ctrl) windower.EXPECT().ExpectedProposer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nodeID, nil).AnyTimes() pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) @@ -368,17 +372,17 @@ func TestPostDurangoBuildChildResetScheduler(t *testing.T) { parentHeight uint64 = 1234 ) - innerBlk := snowmantest.NewMockBlock(ctrl) + innerBlk := snowmanmock.NewBlock(ctrl) innerBlk.EXPECT().Height().Return(parentHeight + 1).AnyTimes() - vdrState := validators.NewMockState(ctrl) + vdrState := validatorsmock.NewState(ctrl) vdrState.EXPECT().GetMinimumHeight(context.Background()).Return(pChainHeight, nil).AnyTimes() - windower := proposer.NewMockWindower(ctrl) + windower := proposermock.NewWindower(ctrl) windower.EXPECT().ExpectedProposer(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()). Return(selectedProposer, nil).AnyTimes() // return a proposer different from thisNode, to check whether scheduler is reset - scheduler := scheduler.NewMockScheduler(ctrl) + scheduler := schedulermock.NewScheduler(ctrl) pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) require.NoError(err) @@ -389,7 +393,7 @@ func TestPostDurangoBuildChildResetScheduler(t *testing.T) { StakingLeafSigner: pk, Registerer: prometheus.NewRegistry(), }, - ChainVM: block.NewMockChainVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), ctx: &snow.Context{ NodeID: thisNodeID, ValidatorState: vdrState, diff --git a/vms/proposervm/mock_post_fork_block.go b/vms/proposervm/mock_post_fork_block.go index 7957a91b457d..a57042007bcb 100644 --- a/vms/proposervm/mock_post_fork_block.go +++ b/vms/proposervm/mock_post_fork_block.go @@ -1,9 +1,9 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/proposervm (interfaces: PostForkBlock) +// Source: vms/proposervm/block.go // // Generated by this command: // -// mockgen -package=proposervm -destination=vms/proposervm/mock_post_fork_block.go github.com/ava-labs/avalanchego/vms/proposervm PostForkBlock +// mockgen -source=vms/proposervm/block.go -destination=vms/proposervm/mock_post_fork_block.go -package=proposervm -exclude_interfaces=Block -mock_names=MockPostForkBlock=MockPostForkBlock // // Package proposervm is a generated GoMock package. @@ -254,43 +254,43 @@ func (mr *MockPostForkBlockMockRecorder) setInnerBlk(arg0 any) *gomock.Call { } // verifyPostForkChild mocks base method. -func (m *MockPostForkBlock) verifyPostForkChild(arg0 context.Context, arg1 *postForkBlock) error { +func (m *MockPostForkBlock) verifyPostForkChild(ctx context.Context, child *postForkBlock) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "verifyPostForkChild", arg0, arg1) + ret := m.ctrl.Call(m, "verifyPostForkChild", ctx, child) ret0, _ := ret[0].(error) return ret0 } // verifyPostForkChild indicates an expected call of verifyPostForkChild. -func (mr *MockPostForkBlockMockRecorder) verifyPostForkChild(arg0, arg1 any) *gomock.Call { +func (mr *MockPostForkBlockMockRecorder) verifyPostForkChild(ctx, child any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "verifyPostForkChild", reflect.TypeOf((*MockPostForkBlock)(nil).verifyPostForkChild), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "verifyPostForkChild", reflect.TypeOf((*MockPostForkBlock)(nil).verifyPostForkChild), ctx, child) } // verifyPostForkOption mocks base method. -func (m *MockPostForkBlock) verifyPostForkOption(arg0 context.Context, arg1 *postForkOption) error { +func (m *MockPostForkBlock) verifyPostForkOption(ctx context.Context, child *postForkOption) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "verifyPostForkOption", arg0, arg1) + ret := m.ctrl.Call(m, "verifyPostForkOption", ctx, child) ret0, _ := ret[0].(error) return ret0 } // verifyPostForkOption indicates an expected call of verifyPostForkOption. -func (mr *MockPostForkBlockMockRecorder) verifyPostForkOption(arg0, arg1 any) *gomock.Call { +func (mr *MockPostForkBlockMockRecorder) verifyPostForkOption(ctx, child any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "verifyPostForkOption", reflect.TypeOf((*MockPostForkBlock)(nil).verifyPostForkOption), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "verifyPostForkOption", reflect.TypeOf((*MockPostForkBlock)(nil).verifyPostForkOption), ctx, child) } // verifyPreForkChild mocks base method. -func (m *MockPostForkBlock) verifyPreForkChild(arg0 context.Context, arg1 *preForkBlock) error { +func (m *MockPostForkBlock) verifyPreForkChild(ctx context.Context, child *preForkBlock) error { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "verifyPreForkChild", arg0, arg1) + ret := m.ctrl.Call(m, "verifyPreForkChild", ctx, child) ret0, _ := ret[0].(error) return ret0 } // verifyPreForkChild indicates an expected call of verifyPreForkChild. -func (mr *MockPostForkBlockMockRecorder) verifyPreForkChild(arg0, arg1 any) *gomock.Call { +func (mr *MockPostForkBlockMockRecorder) verifyPreForkChild(ctx, child any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "verifyPreForkChild", reflect.TypeOf((*MockPostForkBlock)(nil).verifyPreForkChild), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "verifyPreForkChild", reflect.TypeOf((*MockPostForkBlock)(nil).verifyPreForkChild), ctx, child) } diff --git a/vms/proposervm/pre_fork_block_test.go b/vms/proposervm/pre_fork_block_test.go index b69ddd5a0d3b..29d250aef624 100644 --- a/vms/proposervm/pre_fork_block_test.go +++ b/vms/proposervm/pre_fork_block_test.go @@ -16,10 +16,11 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowman" + "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmanmock" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" - "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/snow/snowtest" - "github.com/ava-labs/avalanchego/snow/validators" + "github.com/ava-labs/avalanchego/snow/validators/validatorsmock" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" @@ -635,16 +636,16 @@ func TestPreForkBlock_BuildBlockWithContext(t *testing.T) { pChainHeight := uint64(1337) blkID := ids.GenerateTestID() - innerBlk := snowmantest.NewMockBlock(ctrl) + innerBlk := snowmanmock.NewBlock(ctrl) innerBlk.EXPECT().ID().Return(blkID).AnyTimes() innerBlk.EXPECT().Timestamp().Return(mockable.MaxTime) - builtBlk := snowmantest.NewMockBlock(ctrl) + builtBlk := snowmanmock.NewBlock(ctrl) builtBlk.EXPECT().Bytes().Return([]byte{1, 2, 3}).AnyTimes() builtBlk.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() builtBlk.EXPECT().Height().Return(pChainHeight).AnyTimes() - innerVM := block.NewMockChainVM(ctrl) + innerVM := blockmock.NewChainVM(ctrl) innerVM.EXPECT().BuildBlock(gomock.Any()).Return(builtBlk, nil).AnyTimes() - vdrState := validators.NewMockState(ctrl) + vdrState := validatorsmock.NewState(ctrl) vdrState.EXPECT().GetMinimumHeight(context.Background()).Return(pChainHeight, nil).AnyTimes() vm := &VM{ diff --git a/vms/proposervm/proposer/mock_windower.go b/vms/proposervm/proposer/mock_windower.go deleted file mode 100644 index 5384da8ccf80..000000000000 --- a/vms/proposervm/proposer/mock_windower.go +++ /dev/null @@ -1,102 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/proposervm/proposer (interfaces: Windower) -// -// Generated by this command: -// -// mockgen -package=proposer -destination=vms/proposervm/proposer/mock_windower.go github.com/ava-labs/avalanchego/vms/proposervm/proposer Windower -// - -// Package proposer is a generated GoMock package. -package proposer - -import ( - context "context" - reflect "reflect" - time "time" - - ids "github.com/ava-labs/avalanchego/ids" - gomock "go.uber.org/mock/gomock" -) - -// MockWindower is a mock of Windower interface. -type MockWindower struct { - ctrl *gomock.Controller - recorder *MockWindowerMockRecorder -} - -// MockWindowerMockRecorder is the mock recorder for MockWindower. -type MockWindowerMockRecorder struct { - mock *MockWindower -} - -// NewMockWindower creates a new mock instance. -func NewMockWindower(ctrl *gomock.Controller) *MockWindower { - mock := &MockWindower{ctrl: ctrl} - mock.recorder = &MockWindowerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockWindower) EXPECT() *MockWindowerMockRecorder { - return m.recorder -} - -// Delay mocks base method. -func (m *MockWindower) Delay(arg0 context.Context, arg1, arg2 uint64, arg3 ids.NodeID, arg4 int) (time.Duration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Delay", arg0, arg1, arg2, arg3, arg4) - ret0, _ := ret[0].(time.Duration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Delay indicates an expected call of Delay. -func (mr *MockWindowerMockRecorder) Delay(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delay", reflect.TypeOf((*MockWindower)(nil).Delay), arg0, arg1, arg2, arg3, arg4) -} - -// ExpectedProposer mocks base method. -func (m *MockWindower) ExpectedProposer(arg0 context.Context, arg1, arg2, arg3 uint64) (ids.NodeID, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ExpectedProposer", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].(ids.NodeID) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// ExpectedProposer indicates an expected call of ExpectedProposer. -func (mr *MockWindowerMockRecorder) ExpectedProposer(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExpectedProposer", reflect.TypeOf((*MockWindower)(nil).ExpectedProposer), arg0, arg1, arg2, arg3) -} - -// MinDelayForProposer mocks base method. -func (m *MockWindower) MinDelayForProposer(arg0 context.Context, arg1, arg2 uint64, arg3 ids.NodeID, arg4 uint64) (time.Duration, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "MinDelayForProposer", arg0, arg1, arg2, arg3, arg4) - ret0, _ := ret[0].(time.Duration) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// MinDelayForProposer indicates an expected call of MinDelayForProposer. -func (mr *MockWindowerMockRecorder) MinDelayForProposer(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MinDelayForProposer", reflect.TypeOf((*MockWindower)(nil).MinDelayForProposer), arg0, arg1, arg2, arg3, arg4) -} - -// Proposers mocks base method. -func (m *MockWindower) Proposers(arg0 context.Context, arg1, arg2 uint64, arg3 int) ([]ids.NodeID, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Proposers", arg0, arg1, arg2, arg3) - ret0, _ := ret[0].([]ids.NodeID) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// Proposers indicates an expected call of Proposers. -func (mr *MockWindowerMockRecorder) Proposers(arg0, arg1, arg2, arg3 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Proposers", reflect.TypeOf((*MockWindower)(nil).Proposers), arg0, arg1, arg2, arg3) -} diff --git a/vms/proposervm/proposer/proposermock/windower.go b/vms/proposervm/proposer/proposermock/windower.go new file mode 100644 index 000000000000..66d83cb41692 --- /dev/null +++ b/vms/proposervm/proposer/proposermock/windower.go @@ -0,0 +1,102 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/proposervm/proposer (interfaces: Windower) +// +// Generated by this command: +// +// mockgen -package=proposermock -destination=vms/proposervm/proposer/proposermock/windower.go -mock_names=Windower=Windower github.com/ava-labs/avalanchego/vms/proposervm/proposer Windower +// + +// Package proposermock is a generated GoMock package. +package proposermock + +import ( + context "context" + reflect "reflect" + time "time" + + ids "github.com/ava-labs/avalanchego/ids" + gomock "go.uber.org/mock/gomock" +) + +// Windower is a mock of Windower interface. +type Windower struct { + ctrl *gomock.Controller + recorder *WindowerMockRecorder +} + +// WindowerMockRecorder is the mock recorder for Windower. +type WindowerMockRecorder struct { + mock *Windower +} + +// NewWindower creates a new mock instance. +func NewWindower(ctrl *gomock.Controller) *Windower { + mock := &Windower{ctrl: ctrl} + mock.recorder = &WindowerMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Windower) EXPECT() *WindowerMockRecorder { + return m.recorder +} + +// Delay mocks base method. +func (m *Windower) Delay(arg0 context.Context, arg1, arg2 uint64, arg3 ids.NodeID, arg4 int) (time.Duration, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delay", arg0, arg1, arg2, arg3, arg4) + ret0, _ := ret[0].(time.Duration) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Delay indicates an expected call of Delay. +func (mr *WindowerMockRecorder) Delay(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delay", reflect.TypeOf((*Windower)(nil).Delay), arg0, arg1, arg2, arg3, arg4) +} + +// ExpectedProposer mocks base method. +func (m *Windower) ExpectedProposer(arg0 context.Context, arg1, arg2, arg3 uint64) (ids.NodeID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ExpectedProposer", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].(ids.NodeID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ExpectedProposer indicates an expected call of ExpectedProposer. +func (mr *WindowerMockRecorder) ExpectedProposer(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExpectedProposer", reflect.TypeOf((*Windower)(nil).ExpectedProposer), arg0, arg1, arg2, arg3) +} + +// MinDelayForProposer mocks base method. +func (m *Windower) MinDelayForProposer(arg0 context.Context, arg1, arg2 uint64, arg3 ids.NodeID, arg4 uint64) (time.Duration, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "MinDelayForProposer", arg0, arg1, arg2, arg3, arg4) + ret0, _ := ret[0].(time.Duration) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// MinDelayForProposer indicates an expected call of MinDelayForProposer. +func (mr *WindowerMockRecorder) MinDelayForProposer(arg0, arg1, arg2, arg3, arg4 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MinDelayForProposer", reflect.TypeOf((*Windower)(nil).MinDelayForProposer), arg0, arg1, arg2, arg3, arg4) +} + +// Proposers mocks base method. +func (m *Windower) Proposers(arg0 context.Context, arg1, arg2 uint64, arg3 int) ([]ids.NodeID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Proposers", arg0, arg1, arg2, arg3) + ret0, _ := ret[0].([]ids.NodeID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Proposers indicates an expected call of Proposers. +func (mr *WindowerMockRecorder) Proposers(arg0, arg1, arg2, arg3 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Proposers", reflect.TypeOf((*Windower)(nil).Proposers), arg0, arg1, arg2, arg3) +} diff --git a/vms/proposervm/scheduler/mock_scheduler.go b/vms/proposervm/scheduler/mock_scheduler.go deleted file mode 100644 index f4a8f1e62197..000000000000 --- a/vms/proposervm/scheduler/mock_scheduler.go +++ /dev/null @@ -1,76 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/proposervm/scheduler (interfaces: Scheduler) -// -// Generated by this command: -// -// mockgen -package=scheduler -destination=vms/proposervm/scheduler/mock_scheduler.go github.com/ava-labs/avalanchego/vms/proposervm/scheduler Scheduler -// - -// Package scheduler is a generated GoMock package. -package scheduler - -import ( - reflect "reflect" - time "time" - - gomock "go.uber.org/mock/gomock" -) - -// MockScheduler is a mock of Scheduler interface. -type MockScheduler struct { - ctrl *gomock.Controller - recorder *MockSchedulerMockRecorder -} - -// MockSchedulerMockRecorder is the mock recorder for MockScheduler. -type MockSchedulerMockRecorder struct { - mock *MockScheduler -} - -// NewMockScheduler creates a new mock instance. -func NewMockScheduler(ctrl *gomock.Controller) *MockScheduler { - mock := &MockScheduler{ctrl: ctrl} - mock.recorder = &MockSchedulerMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockScheduler) EXPECT() *MockSchedulerMockRecorder { - return m.recorder -} - -// Close mocks base method. -func (m *MockScheduler) Close() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "Close") -} - -// Close indicates an expected call of Close. -func (mr *MockSchedulerMockRecorder) Close() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockScheduler)(nil).Close)) -} - -// Dispatch mocks base method. -func (m *MockScheduler) Dispatch(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "Dispatch", arg0) -} - -// Dispatch indicates an expected call of Dispatch. -func (mr *MockSchedulerMockRecorder) Dispatch(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dispatch", reflect.TypeOf((*MockScheduler)(nil).Dispatch), arg0) -} - -// SetBuildBlockTime mocks base method. -func (m *MockScheduler) SetBuildBlockTime(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetBuildBlockTime", arg0) -} - -// SetBuildBlockTime indicates an expected call of SetBuildBlockTime. -func (mr *MockSchedulerMockRecorder) SetBuildBlockTime(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetBuildBlockTime", reflect.TypeOf((*MockScheduler)(nil).SetBuildBlockTime), arg0) -} diff --git a/vms/proposervm/scheduler/schedulermock/scheduler.go b/vms/proposervm/scheduler/schedulermock/scheduler.go new file mode 100644 index 000000000000..72a9fbbd7a9d --- /dev/null +++ b/vms/proposervm/scheduler/schedulermock/scheduler.go @@ -0,0 +1,76 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/proposervm/scheduler (interfaces: Scheduler) +// +// Generated by this command: +// +// mockgen -package=schedulermock -destination=vms/proposervm/scheduler/schedulermock/scheduler.go -mock_names=Scheduler=Scheduler github.com/ava-labs/avalanchego/vms/proposervm/scheduler Scheduler +// + +// Package schedulermock is a generated GoMock package. +package schedulermock + +import ( + reflect "reflect" + time "time" + + gomock "go.uber.org/mock/gomock" +) + +// Scheduler is a mock of Scheduler interface. +type Scheduler struct { + ctrl *gomock.Controller + recorder *SchedulerMockRecorder +} + +// SchedulerMockRecorder is the mock recorder for Scheduler. +type SchedulerMockRecorder struct { + mock *Scheduler +} + +// NewScheduler creates a new mock instance. +func NewScheduler(ctrl *gomock.Controller) *Scheduler { + mock := &Scheduler{ctrl: ctrl} + mock.recorder = &SchedulerMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Scheduler) EXPECT() *SchedulerMockRecorder { + return m.recorder +} + +// Close mocks base method. +func (m *Scheduler) Close() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Close") +} + +// Close indicates an expected call of Close. +func (mr *SchedulerMockRecorder) Close() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*Scheduler)(nil).Close)) +} + +// Dispatch mocks base method. +func (m *Scheduler) Dispatch(arg0 time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Dispatch", arg0) +} + +// Dispatch indicates an expected call of Dispatch. +func (mr *SchedulerMockRecorder) Dispatch(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Dispatch", reflect.TypeOf((*Scheduler)(nil).Dispatch), arg0) +} + +// SetBuildBlockTime mocks base method. +func (m *Scheduler) SetBuildBlockTime(arg0 time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetBuildBlockTime", arg0) +} + +// SetBuildBlockTime indicates an expected call of SetBuildBlockTime. +func (mr *SchedulerMockRecorder) SetBuildBlockTime(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetBuildBlockTime", reflect.TypeOf((*Scheduler)(nil).SetBuildBlockTime), arg0) +} diff --git a/vms/proposervm/state/mock_state.go b/vms/proposervm/state/statemock/state.go similarity index 59% rename from vms/proposervm/state/mock_state.go rename to vms/proposervm/state/statemock/state.go index e01ab01d93aa..49ac45e9ecd3 100644 --- a/vms/proposervm/state/mock_state.go +++ b/vms/proposervm/state/statemock/state.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=state -destination=vms/proposervm/state/mock_state.go github.com/ava-labs/avalanchego/vms/proposervm/state State +// mockgen -package=statemock -destination=vms/proposervm/state/statemock/state.go -mock_names=State=State github.com/ava-labs/avalanchego/vms/proposervm/state State // -// Package state is a generated GoMock package. -package state +// Package statemock is a generated GoMock package. +package statemock import ( reflect "reflect" @@ -17,31 +17,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockState is a mock of State interface. -type MockState struct { +// State is a mock of State interface. +type State struct { ctrl *gomock.Controller - recorder *MockStateMockRecorder + recorder *StateMockRecorder } -// MockStateMockRecorder is the mock recorder for MockState. -type MockStateMockRecorder struct { - mock *MockState +// StateMockRecorder is the mock recorder for State. +type StateMockRecorder struct { + mock *State } -// NewMockState creates a new mock instance. -func NewMockState(ctrl *gomock.Controller) *MockState { - mock := &MockState{ctrl: ctrl} - mock.recorder = &MockStateMockRecorder{mock} +// NewState creates a new mock instance. +func NewState(ctrl *gomock.Controller) *State { + mock := &State{ctrl: ctrl} + mock.recorder = &StateMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockState) EXPECT() *MockStateMockRecorder { +func (m *State) EXPECT() *StateMockRecorder { return m.recorder } // DeleteBlock mocks base method. -func (m *MockState) DeleteBlock(arg0 ids.ID) error { +func (m *State) DeleteBlock(arg0 ids.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteBlock", arg0) ret0, _ := ret[0].(error) @@ -49,13 +49,13 @@ func (m *MockState) DeleteBlock(arg0 ids.ID) error { } // DeleteBlock indicates an expected call of DeleteBlock. -func (mr *MockStateMockRecorder) DeleteBlock(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) DeleteBlock(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBlock", reflect.TypeOf((*MockState)(nil).DeleteBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBlock", reflect.TypeOf((*State)(nil).DeleteBlock), arg0) } // DeleteBlockIDAtHeight mocks base method. -func (m *MockState) DeleteBlockIDAtHeight(arg0 uint64) error { +func (m *State) DeleteBlockIDAtHeight(arg0 uint64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteBlockIDAtHeight", arg0) ret0, _ := ret[0].(error) @@ -63,13 +63,13 @@ func (m *MockState) DeleteBlockIDAtHeight(arg0 uint64) error { } // DeleteBlockIDAtHeight indicates an expected call of DeleteBlockIDAtHeight. -func (mr *MockStateMockRecorder) DeleteBlockIDAtHeight(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) DeleteBlockIDAtHeight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBlockIDAtHeight", reflect.TypeOf((*MockState)(nil).DeleteBlockIDAtHeight), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteBlockIDAtHeight", reflect.TypeOf((*State)(nil).DeleteBlockIDAtHeight), arg0) } // DeleteLastAccepted mocks base method. -func (m *MockState) DeleteLastAccepted() error { +func (m *State) DeleteLastAccepted() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DeleteLastAccepted") ret0, _ := ret[0].(error) @@ -77,13 +77,13 @@ func (m *MockState) DeleteLastAccepted() error { } // DeleteLastAccepted indicates an expected call of DeleteLastAccepted. -func (mr *MockStateMockRecorder) DeleteLastAccepted() *gomock.Call { +func (mr *StateMockRecorder) DeleteLastAccepted() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteLastAccepted", reflect.TypeOf((*MockState)(nil).DeleteLastAccepted)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteLastAccepted", reflect.TypeOf((*State)(nil).DeleteLastAccepted)) } // GetBlock mocks base method. -func (m *MockState) GetBlock(arg0 ids.ID) (block.Block, error) { +func (m *State) GetBlock(arg0 ids.ID) (block.Block, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBlock", arg0) ret0, _ := ret[0].(block.Block) @@ -92,13 +92,13 @@ func (m *MockState) GetBlock(arg0 ids.ID) (block.Block, error) { } // GetBlock indicates an expected call of GetBlock. -func (mr *MockStateMockRecorder) GetBlock(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) GetBlock(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*MockState)(nil).GetBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlock", reflect.TypeOf((*State)(nil).GetBlock), arg0) } // GetBlockIDAtHeight mocks base method. -func (m *MockState) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { +func (m *State) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetBlockIDAtHeight", arg0) ret0, _ := ret[0].(ids.ID) @@ -107,13 +107,13 @@ func (m *MockState) GetBlockIDAtHeight(arg0 uint64) (ids.ID, error) { } // GetBlockIDAtHeight indicates an expected call of GetBlockIDAtHeight. -func (mr *MockStateMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) GetBlockIDAtHeight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*MockState)(nil).GetBlockIDAtHeight), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBlockIDAtHeight", reflect.TypeOf((*State)(nil).GetBlockIDAtHeight), arg0) } // GetForkHeight mocks base method. -func (m *MockState) GetForkHeight() (uint64, error) { +func (m *State) GetForkHeight() (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetForkHeight") ret0, _ := ret[0].(uint64) @@ -122,13 +122,13 @@ func (m *MockState) GetForkHeight() (uint64, error) { } // GetForkHeight indicates an expected call of GetForkHeight. -func (mr *MockStateMockRecorder) GetForkHeight() *gomock.Call { +func (mr *StateMockRecorder) GetForkHeight() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetForkHeight", reflect.TypeOf((*MockState)(nil).GetForkHeight)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetForkHeight", reflect.TypeOf((*State)(nil).GetForkHeight)) } // GetLastAccepted mocks base method. -func (m *MockState) GetLastAccepted() (ids.ID, error) { +func (m *State) GetLastAccepted() (ids.ID, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetLastAccepted") ret0, _ := ret[0].(ids.ID) @@ -137,13 +137,13 @@ func (m *MockState) GetLastAccepted() (ids.ID, error) { } // GetLastAccepted indicates an expected call of GetLastAccepted. -func (mr *MockStateMockRecorder) GetLastAccepted() *gomock.Call { +func (mr *StateMockRecorder) GetLastAccepted() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastAccepted", reflect.TypeOf((*MockState)(nil).GetLastAccepted)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLastAccepted", reflect.TypeOf((*State)(nil).GetLastAccepted)) } // GetMinimumHeight mocks base method. -func (m *MockState) GetMinimumHeight() (uint64, error) { +func (m *State) GetMinimumHeight() (uint64, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetMinimumHeight") ret0, _ := ret[0].(uint64) @@ -152,13 +152,13 @@ func (m *MockState) GetMinimumHeight() (uint64, error) { } // GetMinimumHeight indicates an expected call of GetMinimumHeight. -func (mr *MockStateMockRecorder) GetMinimumHeight() *gomock.Call { +func (mr *StateMockRecorder) GetMinimumHeight() *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMinimumHeight", reflect.TypeOf((*MockState)(nil).GetMinimumHeight)) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetMinimumHeight", reflect.TypeOf((*State)(nil).GetMinimumHeight)) } // PutBlock mocks base method. -func (m *MockState) PutBlock(arg0 block.Block) error { +func (m *State) PutBlock(arg0 block.Block) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "PutBlock", arg0) ret0, _ := ret[0].(error) @@ -166,13 +166,13 @@ func (m *MockState) PutBlock(arg0 block.Block) error { } // PutBlock indicates an expected call of PutBlock. -func (mr *MockStateMockRecorder) PutBlock(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) PutBlock(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutBlock", reflect.TypeOf((*MockState)(nil).PutBlock), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutBlock", reflect.TypeOf((*State)(nil).PutBlock), arg0) } // SetBlockIDAtHeight mocks base method. -func (m *MockState) SetBlockIDAtHeight(arg0 uint64, arg1 ids.ID) error { +func (m *State) SetBlockIDAtHeight(arg0 uint64, arg1 ids.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetBlockIDAtHeight", arg0, arg1) ret0, _ := ret[0].(error) @@ -180,13 +180,13 @@ func (m *MockState) SetBlockIDAtHeight(arg0 uint64, arg1 ids.ID) error { } // SetBlockIDAtHeight indicates an expected call of SetBlockIDAtHeight. -func (mr *MockStateMockRecorder) SetBlockIDAtHeight(arg0, arg1 any) *gomock.Call { +func (mr *StateMockRecorder) SetBlockIDAtHeight(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetBlockIDAtHeight", reflect.TypeOf((*MockState)(nil).SetBlockIDAtHeight), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetBlockIDAtHeight", reflect.TypeOf((*State)(nil).SetBlockIDAtHeight), arg0, arg1) } // SetForkHeight mocks base method. -func (m *MockState) SetForkHeight(arg0 uint64) error { +func (m *State) SetForkHeight(arg0 uint64) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetForkHeight", arg0) ret0, _ := ret[0].(error) @@ -194,13 +194,13 @@ func (m *MockState) SetForkHeight(arg0 uint64) error { } // SetForkHeight indicates an expected call of SetForkHeight. -func (mr *MockStateMockRecorder) SetForkHeight(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) SetForkHeight(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetForkHeight", reflect.TypeOf((*MockState)(nil).SetForkHeight), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetForkHeight", reflect.TypeOf((*State)(nil).SetForkHeight), arg0) } // SetLastAccepted mocks base method. -func (m *MockState) SetLastAccepted(arg0 ids.ID) error { +func (m *State) SetLastAccepted(arg0 ids.ID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SetLastAccepted", arg0) ret0, _ := ret[0].(error) @@ -208,7 +208,7 @@ func (m *MockState) SetLastAccepted(arg0 ids.ID) error { } // SetLastAccepted indicates an expected call of SetLastAccepted. -func (mr *MockStateMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { +func (mr *StateMockRecorder) SetLastAccepted(arg0 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*MockState)(nil).SetLastAccepted), arg0) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetLastAccepted", reflect.TypeOf((*State)(nil).SetLastAccepted), arg0) } diff --git a/vms/proposervm/vm_test.go b/vms/proposervm/vm_test.go index a689e7d32013..bbd41939516a 100644 --- a/vms/proposervm/vm_test.go +++ b/vms/proposervm/vm_test.go @@ -22,10 +22,12 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowman" + "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmanmock" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" @@ -1887,7 +1889,7 @@ func TestVMInnerBlkCache(t *testing.T) { ctrl := gomock.NewController(t) // Create a VM - innerVM := block.NewMockChainVM(ctrl) + innerVM := blockmock.NewChainVM(ctrl) vm := New( innerVM, Config{ @@ -1914,7 +1916,7 @@ func TestVMInnerBlkCache(t *testing.T) { innerVM.EXPECT().Shutdown(gomock.Any()).Return(nil) { - innerBlk := snowmantest.NewMockBlock(ctrl) + innerBlk := snowmanmock.NewBlock(ctrl) innerBlkID := ids.GenerateTestID() innerVM.EXPECT().LastAccepted(gomock.Any()).Return(innerBlkID, nil) innerVM.EXPECT().GetBlock(gomock.Any(), innerBlkID).Return(innerBlk, nil) @@ -1952,7 +1954,7 @@ func TestVMInnerBlkCache(t *testing.T) { require.NoError(err) // We will ask the inner VM to parse. - mockInnerBlkNearTip := snowmantest.NewMockBlock(ctrl) + mockInnerBlkNearTip := snowmanmock.NewBlock(ctrl) mockInnerBlkNearTip.EXPECT().Height().Return(uint64(1)).Times(2) mockInnerBlkNearTip.EXPECT().Bytes().Return(blkNearTipInnerBytes).Times(1) @@ -1983,8 +1985,8 @@ func TestVMInnerBlkCache(t *testing.T) { } type blockWithVerifyContext struct { - *snowmantest.MockBlock - *block.MockWithVerifyContext + *snowmanmock.Block + *blockmock.WithVerifyContext } // Ensures that we call [VerifyWithContext] rather than [Verify] on blocks that @@ -1995,7 +1997,7 @@ func TestVM_VerifyBlockWithContext(t *testing.T) { ctrl := gomock.NewController(t) // Create a VM - innerVM := block.NewMockChainVM(ctrl) + innerVM := blockmock.NewChainVM(ctrl) vm := New( innerVM, Config{ @@ -2025,7 +2027,7 @@ func TestVM_VerifyBlockWithContext(t *testing.T) { innerVM.EXPECT().Shutdown(gomock.Any()).Return(nil) { - innerBlk := snowmantest.NewMockBlock(ctrl) + innerBlk := snowmanmock.NewBlock(ctrl) innerBlkID := ids.GenerateTestID() innerVM.EXPECT().LastAccepted(gomock.Any()).Return(innerBlkID, nil) innerVM.EXPECT().GetBlock(gomock.Any(), innerBlkID).Return(innerBlk, nil) @@ -2052,18 +2054,18 @@ func TestVM_VerifyBlockWithContext(t *testing.T) { { pChainHeight := uint64(0) innerBlk := blockWithVerifyContext{ - MockBlock: snowmantest.NewMockBlock(ctrl), - MockWithVerifyContext: block.NewMockWithVerifyContext(ctrl), + Block: snowmanmock.NewBlock(ctrl), + WithVerifyContext: blockmock.NewWithVerifyContext(ctrl), } - innerBlk.MockWithVerifyContext.EXPECT().ShouldVerifyWithContext(gomock.Any()).Return(true, nil).Times(2) - innerBlk.MockWithVerifyContext.EXPECT().VerifyWithContext(context.Background(), + innerBlk.WithVerifyContext.EXPECT().ShouldVerifyWithContext(gomock.Any()).Return(true, nil).Times(2) + innerBlk.WithVerifyContext.EXPECT().VerifyWithContext(context.Background(), &block.Context{ PChainHeight: pChainHeight, }, ).Return(nil) - innerBlk.MockBlock.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() - innerBlk.MockBlock.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() - innerBlk.MockBlock.EXPECT().Bytes().Return(utils.RandomBytes(1024)).AnyTimes() + innerBlk.Block.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() + innerBlk.Block.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() + innerBlk.Block.EXPECT().Bytes().Return(utils.RandomBytes(1024)).AnyTimes() blk := NewMockPostForkBlock(ctrl) blk.EXPECT().getInnerBlk().Return(innerBlk).AnyTimes() @@ -2081,7 +2083,7 @@ func TestVM_VerifyBlockWithContext(t *testing.T) { // Call VerifyWithContext again but with a different P-Chain height blk.EXPECT().setInnerBlk(innerBlk).AnyTimes() pChainHeight++ - innerBlk.MockWithVerifyContext.EXPECT().VerifyWithContext(context.Background(), + innerBlk.WithVerifyContext.EXPECT().VerifyWithContext(context.Background(), &block.Context{ PChainHeight: pChainHeight, }, @@ -2100,13 +2102,13 @@ func TestVM_VerifyBlockWithContext(t *testing.T) { // Ensure we call Verify on a block that returns // false for ShouldVerifyWithContext innerBlk := blockWithVerifyContext{ - MockBlock: snowmantest.NewMockBlock(ctrl), - MockWithVerifyContext: block.NewMockWithVerifyContext(ctrl), + Block: snowmanmock.NewBlock(ctrl), + WithVerifyContext: blockmock.NewWithVerifyContext(ctrl), } - innerBlk.MockWithVerifyContext.EXPECT().ShouldVerifyWithContext(gomock.Any()).Return(false, nil) - innerBlk.MockBlock.EXPECT().Verify(gomock.Any()).Return(nil) - innerBlk.MockBlock.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() - innerBlk.MockBlock.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() + innerBlk.WithVerifyContext.EXPECT().ShouldVerifyWithContext(gomock.Any()).Return(false, nil) + innerBlk.Block.EXPECT().Verify(gomock.Any()).Return(nil) + innerBlk.Block.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() + innerBlk.Block.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() blk := NewMockPostForkBlock(ctrl) blk.EXPECT().getInnerBlk().Return(innerBlk).AnyTimes() blkID := ids.GenerateTestID() @@ -2123,12 +2125,12 @@ func TestVM_VerifyBlockWithContext(t *testing.T) { { // Ensure we call Verify on a block that doesn't have a valid context innerBlk := blockWithVerifyContext{ - MockBlock: snowmantest.NewMockBlock(ctrl), - MockWithVerifyContext: block.NewMockWithVerifyContext(ctrl), + Block: snowmanmock.NewBlock(ctrl), + WithVerifyContext: blockmock.NewWithVerifyContext(ctrl), } - innerBlk.MockBlock.EXPECT().Verify(gomock.Any()).Return(nil) - innerBlk.MockBlock.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() - innerBlk.MockBlock.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() + innerBlk.Block.EXPECT().Verify(gomock.Any()).Return(nil) + innerBlk.Block.EXPECT().Parent().Return(ids.GenerateTestID()).AnyTimes() + innerBlk.Block.EXPECT().ID().Return(ids.GenerateTestID()).AnyTimes() blk := NewMockPostForkBlock(ctrl) blk.EXPECT().getInnerBlk().Return(innerBlk).AnyTimes() blkID := ids.GenerateTestID() diff --git a/vms/registry/mock_vm_getter.go b/vms/registry/mock_vm_getter.go deleted file mode 100644 index 30c38f1b6a74..000000000000 --- a/vms/registry/mock_vm_getter.go +++ /dev/null @@ -1,57 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/registry (interfaces: VMGetter) -// -// Generated by this command: -// -// mockgen -package=registry -destination=vms/registry/mock_vm_getter.go github.com/ava-labs/avalanchego/vms/registry VMGetter -// - -// Package registry is a generated GoMock package. -package registry - -import ( - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - vms "github.com/ava-labs/avalanchego/vms" - gomock "go.uber.org/mock/gomock" -) - -// MockVMGetter is a mock of VMGetter interface. -type MockVMGetter struct { - ctrl *gomock.Controller - recorder *MockVMGetterMockRecorder -} - -// MockVMGetterMockRecorder is the mock recorder for MockVMGetter. -type MockVMGetterMockRecorder struct { - mock *MockVMGetter -} - -// NewMockVMGetter creates a new mock instance. -func NewMockVMGetter(ctrl *gomock.Controller) *MockVMGetter { - mock := &MockVMGetter{ctrl: ctrl} - mock.recorder = &MockVMGetterMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVMGetter) EXPECT() *MockVMGetterMockRecorder { - return m.recorder -} - -// Get mocks base method. -func (m *MockVMGetter) Get() (map[ids.ID]vms.Factory, map[ids.ID]vms.Factory, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Get") - ret0, _ := ret[0].(map[ids.ID]vms.Factory) - ret1, _ := ret[1].(map[ids.ID]vms.Factory) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// Get indicates an expected call of Get. -func (mr *MockVMGetterMockRecorder) Get() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockVMGetter)(nil).Get)) -} diff --git a/vms/registry/mock_vm_registry.go b/vms/registry/mock_vm_registry.go deleted file mode 100644 index 43efd85a6015..000000000000 --- a/vms/registry/mock_vm_registry.go +++ /dev/null @@ -1,57 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/registry (interfaces: VMRegistry) -// -// Generated by this command: -// -// mockgen -package=registry -destination=vms/registry/mock_vm_registry.go github.com/ava-labs/avalanchego/vms/registry VMRegistry -// - -// Package registry is a generated GoMock package. -package registry - -import ( - context "context" - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - gomock "go.uber.org/mock/gomock" -) - -// MockVMRegistry is a mock of VMRegistry interface. -type MockVMRegistry struct { - ctrl *gomock.Controller - recorder *MockVMRegistryMockRecorder -} - -// MockVMRegistryMockRecorder is the mock recorder for MockVMRegistry. -type MockVMRegistryMockRecorder struct { - mock *MockVMRegistry -} - -// NewMockVMRegistry creates a new mock instance. -func NewMockVMRegistry(ctrl *gomock.Controller) *MockVMRegistry { - mock := &MockVMRegistry{ctrl: ctrl} - mock.recorder = &MockVMRegistryMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockVMRegistry) EXPECT() *MockVMRegistryMockRecorder { - return m.recorder -} - -// Reload mocks base method. -func (m *MockVMRegistry) Reload(arg0 context.Context) ([]ids.ID, map[ids.ID]error, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Reload", arg0) - ret0, _ := ret[0].([]ids.ID) - ret1, _ := ret[1].(map[ids.ID]error) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// Reload indicates an expected call of Reload. -func (mr *MockVMRegistryMockRecorder) Reload(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reload", reflect.TypeOf((*MockVMRegistry)(nil).Reload), arg0) -} diff --git a/vms/registry/registrymock/vm_getter.go b/vms/registry/registrymock/vm_getter.go new file mode 100644 index 000000000000..655db298542e --- /dev/null +++ b/vms/registry/registrymock/vm_getter.go @@ -0,0 +1,57 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/registry (interfaces: VMGetter) +// +// Generated by this command: +// +// mockgen -package=registrymock -destination=vms/registry/registrymock/vm_getter.go -mock_names=VMGetter=VMGetter github.com/ava-labs/avalanchego/vms/registry VMGetter +// + +// Package registrymock is a generated GoMock package. +package registrymock + +import ( + reflect "reflect" + + ids "github.com/ava-labs/avalanchego/ids" + vms "github.com/ava-labs/avalanchego/vms" + gomock "go.uber.org/mock/gomock" +) + +// VMGetter is a mock of VMGetter interface. +type VMGetter struct { + ctrl *gomock.Controller + recorder *VMGetterMockRecorder +} + +// VMGetterMockRecorder is the mock recorder for VMGetter. +type VMGetterMockRecorder struct { + mock *VMGetter +} + +// NewVMGetter creates a new mock instance. +func NewVMGetter(ctrl *gomock.Controller) *VMGetter { + mock := &VMGetter{ctrl: ctrl} + mock.recorder = &VMGetterMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *VMGetter) EXPECT() *VMGetterMockRecorder { + return m.recorder +} + +// Get mocks base method. +func (m *VMGetter) Get() (map[ids.ID]vms.Factory, map[ids.ID]vms.Factory, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get") + ret0, _ := ret[0].(map[ids.ID]vms.Factory) + ret1, _ := ret[1].(map[ids.ID]vms.Factory) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// Get indicates an expected call of Get. +func (mr *VMGetterMockRecorder) Get() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*VMGetter)(nil).Get)) +} diff --git a/vms/registry/registrymock/vm_registry.go b/vms/registry/registrymock/vm_registry.go new file mode 100644 index 000000000000..3176b71de8fb --- /dev/null +++ b/vms/registry/registrymock/vm_registry.go @@ -0,0 +1,57 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms/registry (interfaces: VMRegistry) +// +// Generated by this command: +// +// mockgen -package=registrymock -destination=vms/registry/registrymock/vm_registry.go -mock_names=VMRegistry=VMRegistry github.com/ava-labs/avalanchego/vms/registry VMRegistry +// + +// Package registrymock is a generated GoMock package. +package registrymock + +import ( + context "context" + reflect "reflect" + + ids "github.com/ava-labs/avalanchego/ids" + gomock "go.uber.org/mock/gomock" +) + +// VMRegistry is a mock of VMRegistry interface. +type VMRegistry struct { + ctrl *gomock.Controller + recorder *VMRegistryMockRecorder +} + +// VMRegistryMockRecorder is the mock recorder for VMRegistry. +type VMRegistryMockRecorder struct { + mock *VMRegistry +} + +// NewVMRegistry creates a new mock instance. +func NewVMRegistry(ctrl *gomock.Controller) *VMRegistry { + mock := &VMRegistry{ctrl: ctrl} + mock.recorder = &VMRegistryMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *VMRegistry) EXPECT() *VMRegistryMockRecorder { + return m.recorder +} + +// Reload mocks base method. +func (m *VMRegistry) Reload(arg0 context.Context) ([]ids.ID, map[ids.ID]error, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Reload", arg0) + ret0, _ := ret[0].([]ids.ID) + ret1, _ := ret[1].(map[ids.ID]error) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// Reload indicates an expected call of Reload. +func (mr *VMRegistryMockRecorder) Reload(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reload", reflect.TypeOf((*VMRegistry)(nil).Reload), arg0) +} diff --git a/vms/registry/vm_getter_test.go b/vms/registry/vm_getter_test.go index fd42ee4c312a..92599b8bc881 100644 --- a/vms/registry/vm_getter_test.go +++ b/vms/registry/vm_getter_test.go @@ -15,9 +15,11 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/filesystem" + "github.com/ava-labs/avalanchego/utils/filesystem/filesystemmock" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/resource" "github.com/ava-labs/avalanchego/vms" + "github.com/ava-labs/avalanchego/vms/vmsmock" ) var ( @@ -108,7 +110,7 @@ func TestGet_Success(t *testing.T) { registeredVMId := ids.GenerateTestID() unregisteredVMId := ids.GenerateTestID() - registeredVMFactory := vms.NewMockFactory(resources.ctrl) + registeredVMFactory := vmsmock.NewFactory(resources.ctrl) resources.mockReader.EXPECT().ReadDir(pluginDir).Times(1).Return(twoValidVMs, nil) resources.mockManager.EXPECT().Lookup(registeredVMName).Times(1).Return(registeredVMId, nil) @@ -130,16 +132,16 @@ func TestGet_Success(t *testing.T) { type vmGetterTestResources struct { ctrl *gomock.Controller - mockReader *filesystem.MockReader - mockManager *vms.MockManager + mockReader *filesystemmock.Reader + mockManager *vmsmock.Manager getter VMGetter } func initVMGetterTest(t *testing.T) *vmGetterTestResources { ctrl := gomock.NewController(t) - mockReader := filesystem.NewMockReader(ctrl) - mockManager := vms.NewMockManager(ctrl) + mockReader := filesystemmock.NewReader(ctrl) + mockManager := vmsmock.NewManager(ctrl) mockRegistry := prometheus.NewRegistry() mockCPUTracker, err := resource.NewManager( logging.NoLog{}, diff --git a/vms/registry/vm_registry_test.go b/vms/registry/vm_registry_test.go index abe6ba67a6e0..f7622516c28c 100644 --- a/vms/registry/vm_registry_test.go +++ b/vms/registry/vm_registry_test.go @@ -12,6 +12,8 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/vms" + "github.com/ava-labs/avalanchego/vms/registry/registrymock" + "github.com/ava-labs/avalanchego/vms/vmsmock" ) var ( @@ -27,10 +29,10 @@ func TestReload_Success(t *testing.T) { resources := initVMRegistryTest(t) - factory1 := vms.NewMockFactory(resources.ctrl) - factory2 := vms.NewMockFactory(resources.ctrl) - factory3 := vms.NewMockFactory(resources.ctrl) - factory4 := vms.NewMockFactory(resources.ctrl) + factory1 := vmsmock.NewFactory(resources.ctrl) + factory2 := vmsmock.NewFactory(resources.ctrl) + factory3 := vmsmock.NewFactory(resources.ctrl) + factory4 := vmsmock.NewFactory(resources.ctrl) registeredVms := map[ids.ID]vms.Factory{ id1: factory1, @@ -81,10 +83,10 @@ func TestReload_PartialRegisterFailure(t *testing.T) { resources := initVMRegistryTest(t) - factory1 := vms.NewMockFactory(resources.ctrl) - factory2 := vms.NewMockFactory(resources.ctrl) - factory3 := vms.NewMockFactory(resources.ctrl) - factory4 := vms.NewMockFactory(resources.ctrl) + factory1 := vmsmock.NewFactory(resources.ctrl) + factory2 := vmsmock.NewFactory(resources.ctrl) + factory3 := vmsmock.NewFactory(resources.ctrl) + factory4 := vmsmock.NewFactory(resources.ctrl) registeredVms := map[ids.ID]vms.Factory{ id1: factory1, @@ -119,16 +121,16 @@ func TestReload_PartialRegisterFailure(t *testing.T) { type registryTestResources struct { ctrl *gomock.Controller - mockVMGetter *MockVMGetter - mockVMManager *vms.MockManager + mockVMGetter *registrymock.VMGetter + mockVMManager *vmsmock.Manager vmRegistry VMRegistry } func initVMRegistryTest(t *testing.T) *registryTestResources { ctrl := gomock.NewController(t) - mockVMGetter := NewMockVMGetter(ctrl) - mockVMManager := vms.NewMockManager(ctrl) + mockVMGetter := registrymock.NewVMGetter(ctrl) + mockVMManager := vmsmock.NewManager(ctrl) vmRegistry := NewVMRegistry( VMRegistryConfig{ diff --git a/vms/rpcchainvm/batched_vm_test.go b/vms/rpcchainvm/batched_vm_test.go index e476222f0493..274cecc845bf 100644 --- a/vms/rpcchainvm/batched_vm_test.go +++ b/vms/rpcchainvm/batched_vm_test.go @@ -13,8 +13,9 @@ import ( "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" + "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmanmock" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/vms/components/chain" ) @@ -36,11 +37,11 @@ func batchedParseBlockCachingTestPlugin(t *testing.T, loadExpectations bool) blo // create mock ctrl := gomock.NewController(t) - vm := block.NewMockChainVM(ctrl) + vm := blockmock.NewChainVM(ctrl) if loadExpectations { - blk1 := snowmantest.NewMockBlock(ctrl) - blk2 := snowmantest.NewMockBlock(ctrl) + blk1 := snowmanmock.NewBlock(ctrl) + blk2 := snowmanmock.NewBlock(ctrl) gomock.InOrder( // Initialize vm.EXPECT().Initialize( diff --git a/vms/rpcchainvm/state_syncable_vm_test.go b/vms/rpcchainvm/state_syncable_vm_test.go index f987424cdc36..879848accc3b 100644 --- a/vms/rpcchainvm/state_syncable_vm_test.go +++ b/vms/rpcchainvm/state_syncable_vm_test.go @@ -19,6 +19,7 @@ import ( "github.com/ava-labs/avalanchego/snow" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/utils/logging" @@ -66,8 +67,8 @@ var ( ) type StateSyncEnabledMock struct { - *block.MockChainVM - *block.MockStateSyncableVM + *blockmock.ChainVM + *blockmock.StateSyncableVM } func stateSyncEnabledTestPlugin(t *testing.T, loadExpectations bool) block.ChainVM { @@ -76,16 +77,16 @@ func stateSyncEnabledTestPlugin(t *testing.T, loadExpectations bool) block.Chain // create mock ctrl := gomock.NewController(t) ssVM := StateSyncEnabledMock{ - MockChainVM: block.NewMockChainVM(ctrl), - MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), + StateSyncableVM: blockmock.NewStateSyncableVM(ctrl), } if loadExpectations { gomock.InOrder( - ssVM.MockStateSyncableVM.EXPECT().StateSyncEnabled(gomock.Any()).Return(false, block.ErrStateSyncableVMNotImplemented).Times(1), - ssVM.MockStateSyncableVM.EXPECT().StateSyncEnabled(gomock.Any()).Return(false, nil).Times(1), - ssVM.MockStateSyncableVM.EXPECT().StateSyncEnabled(gomock.Any()).Return(true, nil).Times(1), - ssVM.MockStateSyncableVM.EXPECT().StateSyncEnabled(gomock.Any()).Return(false, errBrokenConnectionOrSomething).Times(1), + ssVM.StateSyncableVM.EXPECT().StateSyncEnabled(gomock.Any()).Return(false, block.ErrStateSyncableVMNotImplemented).Times(1), + ssVM.StateSyncableVM.EXPECT().StateSyncEnabled(gomock.Any()).Return(false, nil).Times(1), + ssVM.StateSyncableVM.EXPECT().StateSyncEnabled(gomock.Any()).Return(true, nil).Times(1), + ssVM.StateSyncableVM.EXPECT().StateSyncEnabled(gomock.Any()).Return(false, errBrokenConnectionOrSomething).Times(1), ) } @@ -98,15 +99,15 @@ func getOngoingSyncStateSummaryTestPlugin(t *testing.T, loadExpectations bool) b // create mock ctrl := gomock.NewController(t) ssVM := StateSyncEnabledMock{ - MockChainVM: block.NewMockChainVM(ctrl), - MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), + StateSyncableVM: blockmock.NewStateSyncableVM(ctrl), } if loadExpectations { gomock.InOrder( - ssVM.MockStateSyncableVM.EXPECT().GetOngoingSyncStateSummary(gomock.Any()).Return(nil, block.ErrStateSyncableVMNotImplemented).Times(1), - ssVM.MockStateSyncableVM.EXPECT().GetOngoingSyncStateSummary(gomock.Any()).Return(mockedSummary, nil).Times(1), - ssVM.MockStateSyncableVM.EXPECT().GetOngoingSyncStateSummary(gomock.Any()).Return(nil, errBrokenConnectionOrSomething).Times(1), + ssVM.StateSyncableVM.EXPECT().GetOngoingSyncStateSummary(gomock.Any()).Return(nil, block.ErrStateSyncableVMNotImplemented).Times(1), + ssVM.StateSyncableVM.EXPECT().GetOngoingSyncStateSummary(gomock.Any()).Return(mockedSummary, nil).Times(1), + ssVM.StateSyncableVM.EXPECT().GetOngoingSyncStateSummary(gomock.Any()).Return(nil, errBrokenConnectionOrSomething).Times(1), ) } @@ -119,15 +120,15 @@ func getLastStateSummaryTestPlugin(t *testing.T, loadExpectations bool) block.Ch // create mock ctrl := gomock.NewController(t) ssVM := StateSyncEnabledMock{ - MockChainVM: block.NewMockChainVM(ctrl), - MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), + StateSyncableVM: blockmock.NewStateSyncableVM(ctrl), } if loadExpectations { gomock.InOrder( - ssVM.MockStateSyncableVM.EXPECT().GetLastStateSummary(gomock.Any()).Return(nil, block.ErrStateSyncableVMNotImplemented).Times(1), - ssVM.MockStateSyncableVM.EXPECT().GetLastStateSummary(gomock.Any()).Return(mockedSummary, nil).Times(1), - ssVM.MockStateSyncableVM.EXPECT().GetLastStateSummary(gomock.Any()).Return(nil, errBrokenConnectionOrSomething).Times(1), + ssVM.StateSyncableVM.EXPECT().GetLastStateSummary(gomock.Any()).Return(nil, block.ErrStateSyncableVMNotImplemented).Times(1), + ssVM.StateSyncableVM.EXPECT().GetLastStateSummary(gomock.Any()).Return(mockedSummary, nil).Times(1), + ssVM.StateSyncableVM.EXPECT().GetLastStateSummary(gomock.Any()).Return(nil, errBrokenConnectionOrSomething).Times(1), ) } @@ -140,16 +141,16 @@ func parseStateSummaryTestPlugin(t *testing.T, loadExpectations bool) block.Chai // create mock ctrl := gomock.NewController(t) ssVM := StateSyncEnabledMock{ - MockChainVM: block.NewMockChainVM(ctrl), - MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), + StateSyncableVM: blockmock.NewStateSyncableVM(ctrl), } if loadExpectations { gomock.InOrder( - ssVM.MockStateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).Return(nil, block.ErrStateSyncableVMNotImplemented).Times(1), - ssVM.MockStateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).Return(mockedSummary, nil).Times(1), - ssVM.MockStateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).Return(nil, errNothingToParse).Times(1), - ssVM.MockStateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).Return(nil, errBrokenConnectionOrSomething).Times(1), + ssVM.StateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).Return(nil, block.ErrStateSyncableVMNotImplemented).Times(1), + ssVM.StateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).Return(mockedSummary, nil).Times(1), + ssVM.StateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).Return(nil, errNothingToParse).Times(1), + ssVM.StateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).Return(nil, errBrokenConnectionOrSomething).Times(1), ) } @@ -162,15 +163,15 @@ func getStateSummaryTestPlugin(t *testing.T, loadExpectations bool) block.ChainV // create mock ctrl := gomock.NewController(t) ssVM := StateSyncEnabledMock{ - MockChainVM: block.NewMockChainVM(ctrl), - MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), + StateSyncableVM: blockmock.NewStateSyncableVM(ctrl), } if loadExpectations { gomock.InOrder( - ssVM.MockStateSyncableVM.EXPECT().GetStateSummary(gomock.Any(), gomock.Any()).Return(nil, block.ErrStateSyncableVMNotImplemented).Times(1), - ssVM.MockStateSyncableVM.EXPECT().GetStateSummary(gomock.Any(), gomock.Any()).Return(mockedSummary, nil).Times(1), - ssVM.MockStateSyncableVM.EXPECT().GetStateSummary(gomock.Any(), gomock.Any()).Return(nil, errBrokenConnectionOrSomething).Times(1), + ssVM.StateSyncableVM.EXPECT().GetStateSummary(gomock.Any(), gomock.Any()).Return(nil, block.ErrStateSyncableVMNotImplemented).Times(1), + ssVM.StateSyncableVM.EXPECT().GetStateSummary(gomock.Any(), gomock.Any()).Return(mockedSummary, nil).Times(1), + ssVM.StateSyncableVM.EXPECT().GetStateSummary(gomock.Any(), gomock.Any()).Return(nil, errBrokenConnectionOrSomething).Times(1), ) } @@ -183,14 +184,14 @@ func acceptStateSummaryTestPlugin(t *testing.T, loadExpectations bool) block.Cha // create mock ctrl := gomock.NewController(t) ssVM := StateSyncEnabledMock{ - MockChainVM: block.NewMockChainVM(ctrl), - MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), + StateSyncableVM: blockmock.NewStateSyncableVM(ctrl), } if loadExpectations { gomock.InOrder( - ssVM.MockStateSyncableVM.EXPECT().GetStateSummary(gomock.Any(), gomock.Any()).Return(mockedSummary, nil).Times(1), - ssVM.MockStateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).DoAndReturn( + ssVM.StateSyncableVM.EXPECT().GetStateSummary(gomock.Any(), gomock.Any()).Return(mockedSummary, nil).Times(1), + ssVM.StateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).DoAndReturn( func(context.Context, []byte) (block.StateSummary, error) { // setup summary to be accepted before returning it mockedSummary.AcceptF = func(context.Context) (block.StateSyncMode, error) { @@ -199,7 +200,7 @@ func acceptStateSummaryTestPlugin(t *testing.T, loadExpectations bool) block.Cha return mockedSummary, nil }, ).Times(1), - ssVM.MockStateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).DoAndReturn( + ssVM.StateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).DoAndReturn( func(context.Context, []byte) (block.StateSummary, error) { // setup summary to be skipped before returning it mockedSummary.AcceptF = func(context.Context) (block.StateSyncMode, error) { @@ -208,7 +209,7 @@ func acceptStateSummaryTestPlugin(t *testing.T, loadExpectations bool) block.Cha return mockedSummary, nil }, ).Times(1), - ssVM.MockStateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).DoAndReturn( + ssVM.StateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).DoAndReturn( func(context.Context, []byte) (block.StateSummary, error) { // setup summary to fail accept mockedSummary.AcceptF = func(context.Context) (block.StateSyncMode, error) { @@ -229,21 +230,21 @@ func lastAcceptedBlockPostStateSummaryAcceptTestPlugin(t *testing.T, loadExpecta // create mock ctrl := gomock.NewController(t) ssVM := StateSyncEnabledMock{ - MockChainVM: block.NewMockChainVM(ctrl), - MockStateSyncableVM: block.NewMockStateSyncableVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), + StateSyncableVM: blockmock.NewStateSyncableVM(ctrl), } if loadExpectations { gomock.InOrder( - ssVM.MockChainVM.EXPECT().Initialize( + ssVM.ChainVM.EXPECT().Initialize( gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), ).Return(nil).Times(1), - ssVM.MockChainVM.EXPECT().LastAccepted(gomock.Any()).Return(preSummaryBlk.ID(), nil).Times(1), - ssVM.MockChainVM.EXPECT().GetBlock(gomock.Any(), gomock.Any()).Return(preSummaryBlk, nil).Times(1), + ssVM.ChainVM.EXPECT().LastAccepted(gomock.Any()).Return(preSummaryBlk.ID(), nil).Times(1), + ssVM.ChainVM.EXPECT().GetBlock(gomock.Any(), gomock.Any()).Return(preSummaryBlk, nil).Times(1), - ssVM.MockStateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).DoAndReturn( + ssVM.StateSyncableVM.EXPECT().ParseStateSummary(gomock.Any(), gomock.Any()).DoAndReturn( func(context.Context, []byte) (block.StateSummary, error) { // setup summary to be accepted before returning it mockedSummary.AcceptF = func(context.Context) (block.StateSyncMode, error) { @@ -253,9 +254,9 @@ func lastAcceptedBlockPostStateSummaryAcceptTestPlugin(t *testing.T, loadExpecta }, ).Times(2), - ssVM.MockChainVM.EXPECT().SetState(gomock.Any(), gomock.Any()).Return(nil).Times(1), - ssVM.MockChainVM.EXPECT().LastAccepted(gomock.Any()).Return(summaryBlk.ID(), nil).Times(1), - ssVM.MockChainVM.EXPECT().GetBlock(gomock.Any(), gomock.Any()).Return(summaryBlk, nil).Times(1), + ssVM.ChainVM.EXPECT().SetState(gomock.Any(), gomock.Any()).Return(nil).Times(1), + ssVM.ChainVM.EXPECT().LastAccepted(gomock.Any()).Return(summaryBlk.ID(), nil).Times(1), + ssVM.ChainVM.EXPECT().GetBlock(gomock.Any(), gomock.Any()).Return(summaryBlk, nil).Times(1), ) } diff --git a/vms/rpcchainvm/vm_test.go b/vms/rpcchainvm/vm_test.go index 429bc62df0be..6041db3689c8 100644 --- a/vms/rpcchainvm/vm_test.go +++ b/vms/rpcchainvm/vm_test.go @@ -17,6 +17,7 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/rpcchainvm/grpcutils" "github.com/ava-labs/avalanchego/vms/rpcchainvm/runtime" @@ -169,7 +170,7 @@ func TestRuntimeSubprocessBootstrap(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - vm := block.NewMockChainVM(ctrl) + vm := blockmock.NewChainVM(ctrl) listener, err := grpcutils.NewListener() require.NoError(err) diff --git a/vms/rpcchainvm/with_context_vm_test.go b/vms/rpcchainvm/with_context_vm_test.go index 3c256392832f..e96cbf346304 100644 --- a/vms/rpcchainvm/with_context_vm_test.go +++ b/vms/rpcchainvm/with_context_vm_test.go @@ -14,8 +14,9 @@ import ( "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/consensus/snowman" - "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" + "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmanmock" "github.com/ava-labs/avalanchego/snow/engine/snowman/block" + "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blockmock" "github.com/ava-labs/avalanchego/snow/snowtest" ) @@ -36,13 +37,13 @@ var ( ) type ContextEnabledVMMock struct { - *block.MockChainVM - *block.MockBuildBlockWithContextChainVM + *blockmock.ChainVM + *blockmock.BuildBlockWithContextChainVM } type ContextEnabledBlockMock struct { - *snowmantest.MockBlock - *block.MockWithVerifyContext + *snowmanmock.Block + *blockmock.WithVerifyContext } func contextEnabledTestPlugin(t *testing.T, loadExpectations bool) block.ChainVM { @@ -51,38 +52,38 @@ func contextEnabledTestPlugin(t *testing.T, loadExpectations bool) block.ChainVM // create mock ctrl := gomock.NewController(t) ctxVM := ContextEnabledVMMock{ - MockChainVM: block.NewMockChainVM(ctrl), - MockBuildBlockWithContextChainVM: block.NewMockBuildBlockWithContextChainVM(ctrl), + ChainVM: blockmock.NewChainVM(ctrl), + BuildBlockWithContextChainVM: blockmock.NewBuildBlockWithContextChainVM(ctrl), } if loadExpectations { ctxBlock := ContextEnabledBlockMock{ - MockBlock: snowmantest.NewMockBlock(ctrl), - MockWithVerifyContext: block.NewMockWithVerifyContext(ctrl), + Block: snowmanmock.NewBlock(ctrl), + WithVerifyContext: blockmock.NewWithVerifyContext(ctrl), } gomock.InOrder( // Initialize - ctxVM.MockChainVM.EXPECT().Initialize( + ctxVM.ChainVM.EXPECT().Initialize( gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any(), ).Return(nil).Times(1), - ctxVM.MockChainVM.EXPECT().LastAccepted(gomock.Any()).Return(preSummaryBlk.ID(), nil).Times(1), - ctxVM.MockChainVM.EXPECT().GetBlock(gomock.Any(), gomock.Any()).Return(preSummaryBlk, nil).Times(1), + ctxVM.ChainVM.EXPECT().LastAccepted(gomock.Any()).Return(preSummaryBlk.ID(), nil).Times(1), + ctxVM.ChainVM.EXPECT().GetBlock(gomock.Any(), gomock.Any()).Return(preSummaryBlk, nil).Times(1), // BuildBlockWithContext - ctxVM.MockBuildBlockWithContextChainVM.EXPECT().BuildBlockWithContext(gomock.Any(), blockContext).Return(ctxBlock, nil).Times(1), - ctxBlock.MockWithVerifyContext.EXPECT().ShouldVerifyWithContext(gomock.Any()).Return(true, nil).Times(1), - ctxBlock.MockBlock.EXPECT().ID().Return(blkID).Times(1), - ctxBlock.MockBlock.EXPECT().Parent().Return(parentID).Times(1), - ctxBlock.MockBlock.EXPECT().Bytes().Return(blkBytes).Times(1), - ctxBlock.MockBlock.EXPECT().Height().Return(uint64(1)).Times(1), - ctxBlock.MockBlock.EXPECT().Timestamp().Return(time.Now()).Times(1), + ctxVM.BuildBlockWithContextChainVM.EXPECT().BuildBlockWithContext(gomock.Any(), blockContext).Return(ctxBlock, nil).Times(1), + ctxBlock.WithVerifyContext.EXPECT().ShouldVerifyWithContext(gomock.Any()).Return(true, nil).Times(1), + ctxBlock.Block.EXPECT().ID().Return(blkID).Times(1), + ctxBlock.Block.EXPECT().Parent().Return(parentID).Times(1), + ctxBlock.Block.EXPECT().Bytes().Return(blkBytes).Times(1), + ctxBlock.Block.EXPECT().Height().Return(uint64(1)).Times(1), + ctxBlock.Block.EXPECT().Timestamp().Return(time.Now()).Times(1), // VerifyWithContext - ctxVM.MockChainVM.EXPECT().ParseBlock(gomock.Any(), blkBytes).Return(ctxBlock, nil).Times(1), - ctxBlock.MockWithVerifyContext.EXPECT().VerifyWithContext(gomock.Any(), blockContext).Return(nil).Times(1), - ctxBlock.MockBlock.EXPECT().Timestamp().Return(time.Now()).Times(1), + ctxVM.ChainVM.EXPECT().ParseBlock(gomock.Any(), blkBytes).Return(ctxBlock, nil).Times(1), + ctxBlock.WithVerifyContext.EXPECT().VerifyWithContext(gomock.Any(), blockContext).Return(nil).Times(1), + ctxBlock.Block.EXPECT().Timestamp().Return(time.Now()).Times(1), ) } diff --git a/vms/vmsmock/factory.go b/vms/vmsmock/factory.go new file mode 100644 index 000000000000..2b256c365900 --- /dev/null +++ b/vms/vmsmock/factory.go @@ -0,0 +1,55 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms (interfaces: Factory) +// +// Generated by this command: +// +// mockgen -package=vmsmock -destination=vms/vmsmock/factory.go -mock_names=Factory=Factory github.com/ava-labs/avalanchego/vms Factory +// + +// Package vmsmock is a generated GoMock package. +package vmsmock + +import ( + reflect "reflect" + + logging "github.com/ava-labs/avalanchego/utils/logging" + gomock "go.uber.org/mock/gomock" +) + +// Factory is a mock of Factory interface. +type Factory struct { + ctrl *gomock.Controller + recorder *FactoryMockRecorder +} + +// FactoryMockRecorder is the mock recorder for Factory. +type FactoryMockRecorder struct { + mock *Factory +} + +// NewFactory creates a new mock instance. +func NewFactory(ctrl *gomock.Controller) *Factory { + mock := &Factory{ctrl: ctrl} + mock.recorder = &FactoryMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Factory) EXPECT() *FactoryMockRecorder { + return m.recorder +} + +// New mocks base method. +func (m *Factory) New(arg0 logging.Logger) (any, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "New", arg0) + ret0, _ := ret[0].(any) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// New indicates an expected call of New. +func (mr *FactoryMockRecorder) New(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "New", reflect.TypeOf((*Factory)(nil).New), arg0) +} diff --git a/vms/vmsmock/manager.go b/vms/vmsmock/manager.go new file mode 100644 index 000000000000..b6bc2ac0565b --- /dev/null +++ b/vms/vmsmock/manager.go @@ -0,0 +1,186 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: github.com/ava-labs/avalanchego/vms (interfaces: Manager) +// +// Generated by this command: +// +// mockgen -package=vmsmock -destination=vms/vmsmock/manager.go -mock_names=Manager=Manager github.com/ava-labs/avalanchego/vms Manager +// + +// Package vmsmock is a generated GoMock package. +package vmsmock + +import ( + context "context" + reflect "reflect" + + ids "github.com/ava-labs/avalanchego/ids" + vms "github.com/ava-labs/avalanchego/vms" + gomock "go.uber.org/mock/gomock" +) + +// Manager is a mock of Manager interface. +type Manager struct { + ctrl *gomock.Controller + recorder *ManagerMockRecorder +} + +// ManagerMockRecorder is the mock recorder for Manager. +type ManagerMockRecorder struct { + mock *Manager +} + +// NewManager creates a new mock instance. +func NewManager(ctrl *gomock.Controller) *Manager { + mock := &Manager{ctrl: ctrl} + mock.recorder = &ManagerMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Manager) EXPECT() *ManagerMockRecorder { + return m.recorder +} + +// Alias mocks base method. +func (m *Manager) Alias(arg0 ids.ID, arg1 string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Alias", arg0, arg1) + ret0, _ := ret[0].(error) + return ret0 +} + +// Alias indicates an expected call of Alias. +func (mr *ManagerMockRecorder) Alias(arg0, arg1 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Alias", reflect.TypeOf((*Manager)(nil).Alias), arg0, arg1) +} + +// Aliases mocks base method. +func (m *Manager) Aliases(arg0 ids.ID) ([]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Aliases", arg0) + ret0, _ := ret[0].([]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Aliases indicates an expected call of Aliases. +func (mr *ManagerMockRecorder) Aliases(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Aliases", reflect.TypeOf((*Manager)(nil).Aliases), arg0) +} + +// GetFactory mocks base method. +func (m *Manager) GetFactory(arg0 ids.ID) (vms.Factory, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetFactory", arg0) + ret0, _ := ret[0].(vms.Factory) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetFactory indicates an expected call of GetFactory. +func (mr *ManagerMockRecorder) GetFactory(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFactory", reflect.TypeOf((*Manager)(nil).GetFactory), arg0) +} + +// ListFactories mocks base method. +func (m *Manager) ListFactories() ([]ids.ID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ListFactories") + ret0, _ := ret[0].([]ids.ID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// ListFactories indicates an expected call of ListFactories. +func (mr *ManagerMockRecorder) ListFactories() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListFactories", reflect.TypeOf((*Manager)(nil).ListFactories)) +} + +// Lookup mocks base method. +func (m *Manager) Lookup(arg0 string) (ids.ID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Lookup", arg0) + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Lookup indicates an expected call of Lookup. +func (mr *ManagerMockRecorder) Lookup(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Lookup", reflect.TypeOf((*Manager)(nil).Lookup), arg0) +} + +// PrimaryAlias mocks base method. +func (m *Manager) PrimaryAlias(arg0 ids.ID) (string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PrimaryAlias", arg0) + ret0, _ := ret[0].(string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// PrimaryAlias indicates an expected call of PrimaryAlias. +func (mr *ManagerMockRecorder) PrimaryAlias(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrimaryAlias", reflect.TypeOf((*Manager)(nil).PrimaryAlias), arg0) +} + +// PrimaryAliasOrDefault mocks base method. +func (m *Manager) PrimaryAliasOrDefault(arg0 ids.ID) string { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "PrimaryAliasOrDefault", arg0) + ret0, _ := ret[0].(string) + return ret0 +} + +// PrimaryAliasOrDefault indicates an expected call of PrimaryAliasOrDefault. +func (mr *ManagerMockRecorder) PrimaryAliasOrDefault(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PrimaryAliasOrDefault", reflect.TypeOf((*Manager)(nil).PrimaryAliasOrDefault), arg0) +} + +// RegisterFactory mocks base method. +func (m *Manager) RegisterFactory(arg0 context.Context, arg1 ids.ID, arg2 vms.Factory) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RegisterFactory", arg0, arg1, arg2) + ret0, _ := ret[0].(error) + return ret0 +} + +// RegisterFactory indicates an expected call of RegisterFactory. +func (mr *ManagerMockRecorder) RegisterFactory(arg0, arg1, arg2 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RegisterFactory", reflect.TypeOf((*Manager)(nil).RegisterFactory), arg0, arg1, arg2) +} + +// RemoveAliases mocks base method. +func (m *Manager) RemoveAliases(arg0 ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "RemoveAliases", arg0) +} + +// RemoveAliases indicates an expected call of RemoveAliases. +func (mr *ManagerMockRecorder) RemoveAliases(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveAliases", reflect.TypeOf((*Manager)(nil).RemoveAliases), arg0) +} + +// Versions mocks base method. +func (m *Manager) Versions() (map[string]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Versions") + ret0, _ := ret[0].(map[string]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Versions indicates an expected call of Versions. +func (mr *ManagerMockRecorder) Versions() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Versions", reflect.TypeOf((*Manager)(nil).Versions)) +} diff --git a/x/merkledb/mock_db.go b/x/merkledb/mock_db.go index d43e276103f7..c3bf69cf22f6 100644 --- a/x/merkledb/mock_db.go +++ b/x/merkledb/mock_db.go @@ -3,7 +3,7 @@ // // Generated by this command: // -// mockgen -source=x/merkledb/db.go -destination=x/merkledb/mock_db.go -package=merkledb -exclude_interfaces=ChangeProofer,RangeProofer,Clearer,Prefetcher +// mockgen -source=x/merkledb/db.go -destination=x/merkledb/mock_db.go -package=merkledb -exclude_interfaces=ChangeProofer,RangeProofer,Clearer,Prefetcher -mock_names=MockMerkleDB=MockMerkleDB // // Package merkledb is a generated GoMock package. diff --git a/x/sync/client_test.go b/x/sync/client_test.go index fed60e93c1fa..5c5304a2e64f 100644 --- a/x/sync/client_test.go +++ b/x/sync/client_test.go @@ -17,11 +17,12 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/database/memdb" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/common/commonmock" "github.com/ava-labs/avalanchego/trace" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/maybe" "github.com/ava-labs/avalanchego/x/merkledb" + "github.com/ava-labs/avalanchego/x/sync/syncmock" pb "github.com/ava-labs/avalanchego/proto/pb/sync" ) @@ -62,7 +63,7 @@ func sendRangeProofRequest( numAttempts int // Sends messages from server to client. - sender = common.NewMockSender(ctrl) + sender = commonmock.NewSender(ctrl) // Serves the range proof. server = NewNetworkServer(sender, serverDB, logging.NoLog{}) @@ -73,7 +74,7 @@ func sendRangeProofRequest( // "receives" the response from the server. In reality, // it just invokes the server's method and receives // the response on [serverResponseChan]. - networkClient = NewMockNetworkClient(ctrl) + networkClient = syncmock.NewNetworkClient(ctrl) serverResponseChan = make(chan []byte, 1) @@ -361,7 +362,7 @@ func sendChangeProofRequest( numAttempts int // Sends messages from server to client. - sender = common.NewMockSender(ctrl) + sender = commonmock.NewSender(ctrl) // Serves the change proof. server = NewNetworkServer(sender, serverDB, logging.NoLog{}) @@ -372,7 +373,7 @@ func sendChangeProofRequest( // "receives" the response from the server. In reality, // it just invokes the server's method and receives // the response on [serverResponseChan]. - networkClient = NewMockNetworkClient(ctrl) + networkClient = syncmock.NewNetworkClient(ctrl) serverResponseChan = make(chan []byte, 1) @@ -744,7 +745,7 @@ func TestAppRequestSendFailed(t *testing.T) { ctrl := gomock.NewController(t) defer ctrl.Finish() - networkClient := NewMockNetworkClient(ctrl) + networkClient := syncmock.NewNetworkClient(ctrl) client, err := NewClient( &ClientConfig{ diff --git a/x/sync/mock_client.go b/x/sync/mock_client.go index 98fa6d69fd9f..8ffd6f62a1c5 100644 --- a/x/sync/mock_client.go +++ b/x/sync/mock_client.go @@ -1,9 +1,9 @@ // Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/x/sync (interfaces: Client) +// Source: x/sync/client.go // // Generated by this command: // -// mockgen -package=sync -destination=x/sync/mock_client.go github.com/ava-labs/avalanchego/x/sync Client +// mockgen -source=x/sync/client.go -destination=x/sync/mock_client.go -package=sync -exclude_interfaces= -mock_names=MockClient=MockClient // // Package sync is a generated GoMock package. @@ -42,31 +42,31 @@ func (m *MockClient) EXPECT() *MockClientMockRecorder { } // GetChangeProof mocks base method. -func (m *MockClient) GetChangeProof(arg0 context.Context, arg1 *sync.SyncGetChangeProofRequest, arg2 DB) (*merkledb.ChangeOrRangeProof, error) { +func (m *MockClient) GetChangeProof(ctx context.Context, request *sync.SyncGetChangeProofRequest, verificationDB DB) (*merkledb.ChangeOrRangeProof, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetChangeProof", arg0, arg1, arg2) + ret := m.ctrl.Call(m, "GetChangeProof", ctx, request, verificationDB) ret0, _ := ret[0].(*merkledb.ChangeOrRangeProof) ret1, _ := ret[1].(error) return ret0, ret1 } // GetChangeProof indicates an expected call of GetChangeProof. -func (mr *MockClientMockRecorder) GetChangeProof(arg0, arg1, arg2 any) *gomock.Call { +func (mr *MockClientMockRecorder) GetChangeProof(ctx, request, verificationDB any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChangeProof", reflect.TypeOf((*MockClient)(nil).GetChangeProof), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChangeProof", reflect.TypeOf((*MockClient)(nil).GetChangeProof), ctx, request, verificationDB) } // GetRangeProof mocks base method. -func (m *MockClient) GetRangeProof(arg0 context.Context, arg1 *sync.SyncGetRangeProofRequest) (*merkledb.RangeProof, error) { +func (m *MockClient) GetRangeProof(ctx context.Context, request *sync.SyncGetRangeProofRequest) (*merkledb.RangeProof, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetRangeProof", arg0, arg1) + ret := m.ctrl.Call(m, "GetRangeProof", ctx, request) ret0, _ := ret[0].(*merkledb.RangeProof) ret1, _ := ret[1].(error) return ret0, ret1 } // GetRangeProof indicates an expected call of GetRangeProof. -func (mr *MockClientMockRecorder) GetRangeProof(arg0, arg1 any) *gomock.Call { +func (mr *MockClientMockRecorder) GetRangeProof(ctx, request any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRangeProof", reflect.TypeOf((*MockClient)(nil).GetRangeProof), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRangeProof", reflect.TypeOf((*MockClient)(nil).GetRangeProof), ctx, request) } diff --git a/x/sync/network_server_test.go b/x/sync/network_server_test.go index 3d39addd1e55..3970588b8d46 100644 --- a/x/sync/network_server_test.go +++ b/x/sync/network_server_test.go @@ -15,7 +15,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/common/commonmock" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/x/merkledb" @@ -105,7 +105,7 @@ func Test_Server_GetRangeProof(t *testing.T) { t.Run(name, func(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) - sender := common.NewMockSender(ctrl) + sender := commonmock.NewSender(ctrl) var proof *merkledb.RangeProof sender.EXPECT().SendAppResponse( gomock.Any(), // ctx @@ -299,7 +299,7 @@ func Test_Server_GetChangeProof(t *testing.T) { // Store proof returned by server in [proofResult] var proofResult *pb.SyncGetChangeProofResponse var proofBytes []byte - sender := common.NewMockSender(ctrl) + sender := commonmock.NewSender(ctrl) sender.EXPECT().SendAppResponse( gomock.Any(), // ctx gomock.Any(), // nodeID @@ -386,7 +386,7 @@ func TestAppRequestErrAppSendFailed(t *testing.T) { }, }, handlerFunc: func(ctrl *gomock.Controller) *NetworkServer { - sender := common.NewMockSender(ctrl) + sender := commonmock.NewSender(ctrl) sender.EXPECT().SendAppResponse( gomock.Any(), gomock.Any(), @@ -422,7 +422,7 @@ func TestAppRequestErrAppSendFailed(t *testing.T) { }, }, handlerFunc: func(ctrl *gomock.Controller) *NetworkServer { - sender := common.NewMockSender(ctrl) + sender := commonmock.NewSender(ctrl) sender.EXPECT().SendAppResponse( gomock.Any(), gomock.Any(), diff --git a/x/sync/mock_network_client.go b/x/sync/syncmock/network_client.go similarity index 50% rename from x/sync/mock_network_client.go rename to x/sync/syncmock/network_client.go index 3156d145d82b..0df263196f14 100644 --- a/x/sync/mock_network_client.go +++ b/x/sync/syncmock/network_client.go @@ -3,11 +3,11 @@ // // Generated by this command: // -// mockgen -package=sync -destination=x/sync/mock_network_client.go github.com/ava-labs/avalanchego/x/sync NetworkClient +// mockgen -package=syncmock -destination=x/sync/syncmock/network_client.go -mock_names=NetworkClient=NetworkClient github.com/ava-labs/avalanchego/x/sync NetworkClient // -// Package sync is a generated GoMock package. -package sync +// Package syncmock is a generated GoMock package. +package syncmock import ( context "context" @@ -18,31 +18,31 @@ import ( gomock "go.uber.org/mock/gomock" ) -// MockNetworkClient is a mock of NetworkClient interface. -type MockNetworkClient struct { +// NetworkClient is a mock of NetworkClient interface. +type NetworkClient struct { ctrl *gomock.Controller - recorder *MockNetworkClientMockRecorder + recorder *NetworkClientMockRecorder } -// MockNetworkClientMockRecorder is the mock recorder for MockNetworkClient. -type MockNetworkClientMockRecorder struct { - mock *MockNetworkClient +// NetworkClientMockRecorder is the mock recorder for NetworkClient. +type NetworkClientMockRecorder struct { + mock *NetworkClient } -// NewMockNetworkClient creates a new mock instance. -func NewMockNetworkClient(ctrl *gomock.Controller) *MockNetworkClient { - mock := &MockNetworkClient{ctrl: ctrl} - mock.recorder = &MockNetworkClientMockRecorder{mock} +// NewNetworkClient creates a new mock instance. +func NewNetworkClient(ctrl *gomock.Controller) *NetworkClient { + mock := &NetworkClient{ctrl: ctrl} + mock.recorder = &NetworkClientMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockNetworkClient) EXPECT() *MockNetworkClientMockRecorder { +func (m *NetworkClient) EXPECT() *NetworkClientMockRecorder { return m.recorder } // AppRequestFailed mocks base method. -func (m *MockNetworkClient) AppRequestFailed(arg0 context.Context, arg1 ids.NodeID, arg2 uint32) error { +func (m *NetworkClient) AppRequestFailed(arg0 context.Context, arg1 ids.NodeID, arg2 uint32) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppRequestFailed", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -50,13 +50,13 @@ func (m *MockNetworkClient) AppRequestFailed(arg0 context.Context, arg1 ids.Node } // AppRequestFailed indicates an expected call of AppRequestFailed. -func (mr *MockNetworkClientMockRecorder) AppRequestFailed(arg0, arg1, arg2 any) *gomock.Call { +func (mr *NetworkClientMockRecorder) AppRequestFailed(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequestFailed", reflect.TypeOf((*MockNetworkClient)(nil).AppRequestFailed), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppRequestFailed", reflect.TypeOf((*NetworkClient)(nil).AppRequestFailed), arg0, arg1, arg2) } // AppResponse mocks base method. -func (m *MockNetworkClient) AppResponse(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 []byte) error { +func (m *NetworkClient) AppResponse(arg0 context.Context, arg1 ids.NodeID, arg2 uint32, arg3 []byte) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "AppResponse", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) @@ -64,13 +64,13 @@ func (m *MockNetworkClient) AppResponse(arg0 context.Context, arg1 ids.NodeID, a } // AppResponse indicates an expected call of AppResponse. -func (mr *MockNetworkClientMockRecorder) AppResponse(arg0, arg1, arg2, arg3 any) *gomock.Call { +func (mr *NetworkClientMockRecorder) AppResponse(arg0, arg1, arg2, arg3 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppResponse", reflect.TypeOf((*MockNetworkClient)(nil).AppResponse), arg0, arg1, arg2, arg3) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AppResponse", reflect.TypeOf((*NetworkClient)(nil).AppResponse), arg0, arg1, arg2, arg3) } // Connected mocks base method. -func (m *MockNetworkClient) Connected(arg0 context.Context, arg1 ids.NodeID, arg2 *version.Application) error { +func (m *NetworkClient) Connected(arg0 context.Context, arg1 ids.NodeID, arg2 *version.Application) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Connected", arg0, arg1, arg2) ret0, _ := ret[0].(error) @@ -78,13 +78,13 @@ func (m *MockNetworkClient) Connected(arg0 context.Context, arg1 ids.NodeID, arg } // Connected indicates an expected call of Connected. -func (mr *MockNetworkClientMockRecorder) Connected(arg0, arg1, arg2 any) *gomock.Call { +func (mr *NetworkClientMockRecorder) Connected(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connected", reflect.TypeOf((*MockNetworkClient)(nil).Connected), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Connected", reflect.TypeOf((*NetworkClient)(nil).Connected), arg0, arg1, arg2) } // Disconnected mocks base method. -func (m *MockNetworkClient) Disconnected(arg0 context.Context, arg1 ids.NodeID) error { +func (m *NetworkClient) Disconnected(arg0 context.Context, arg1 ids.NodeID) error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Disconnected", arg0, arg1) ret0, _ := ret[0].(error) @@ -92,13 +92,13 @@ func (m *MockNetworkClient) Disconnected(arg0 context.Context, arg1 ids.NodeID) } // Disconnected indicates an expected call of Disconnected. -func (mr *MockNetworkClientMockRecorder) Disconnected(arg0, arg1 any) *gomock.Call { +func (mr *NetworkClientMockRecorder) Disconnected(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnected", reflect.TypeOf((*MockNetworkClient)(nil).Disconnected), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Disconnected", reflect.TypeOf((*NetworkClient)(nil).Disconnected), arg0, arg1) } // Request mocks base method. -func (m *MockNetworkClient) Request(arg0 context.Context, arg1 ids.NodeID, arg2 []byte) ([]byte, error) { +func (m *NetworkClient) Request(arg0 context.Context, arg1 ids.NodeID, arg2 []byte) ([]byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Request", arg0, arg1, arg2) ret0, _ := ret[0].([]byte) @@ -107,13 +107,13 @@ func (m *MockNetworkClient) Request(arg0 context.Context, arg1 ids.NodeID, arg2 } // Request indicates an expected call of Request. -func (mr *MockNetworkClientMockRecorder) Request(arg0, arg1, arg2 any) *gomock.Call { +func (mr *NetworkClientMockRecorder) Request(arg0, arg1, arg2 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Request", reflect.TypeOf((*MockNetworkClient)(nil).Request), arg0, arg1, arg2) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Request", reflect.TypeOf((*NetworkClient)(nil).Request), arg0, arg1, arg2) } // RequestAny mocks base method. -func (m *MockNetworkClient) RequestAny(arg0 context.Context, arg1 []byte) (ids.NodeID, []byte, error) { +func (m *NetworkClient) RequestAny(arg0 context.Context, arg1 []byte) (ids.NodeID, []byte, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "RequestAny", arg0, arg1) ret0, _ := ret[0].(ids.NodeID) @@ -123,7 +123,7 @@ func (m *MockNetworkClient) RequestAny(arg0 context.Context, arg1 []byte) (ids.N } // RequestAny indicates an expected call of RequestAny. -func (mr *MockNetworkClientMockRecorder) RequestAny(arg0, arg1 any) *gomock.Call { +func (mr *NetworkClientMockRecorder) RequestAny(arg0, arg1 any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RequestAny", reflect.TypeOf((*MockNetworkClient)(nil).RequestAny), arg0, arg1) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RequestAny", reflect.TypeOf((*NetworkClient)(nil).RequestAny), arg0, arg1) } From 2661b7128d92edbb76d0e3de48ba415aaf6deb20 Mon Sep 17 00:00:00 2001 From: marun Date: Thu, 22 Aug 2024 11:04:50 -0700 Subject: [PATCH 40/69] [e2e] Simplify pre-funded key usage (#3011) --- tests/e2e/banff/suites.go | 2 +- tests/e2e/c/interchain_workflow.go | 2 +- tests/e2e/p/elastic_subnets.go | 27 ++-- tests/e2e/p/interchain_workflow.go | 16 ++- tests/e2e/p/owner_retrieval.go | 8 +- tests/e2e/p/staking_rewards.go | 2 +- tests/e2e/p/validator_sets.go | 2 +- tests/e2e/p/workflow.go | 26 +++- tests/e2e/x/interchain_workflow.go | 15 ++- tests/e2e/x/transfer/virtuous.go | 44 ++++++- tests/fixture/e2e/env.go | 50 ++++---- tests/fixture/test_data_server.go | 167 ------------------------- tests/fixture/test_data_server_test.go | 76 ----------- 13 files changed, 136 insertions(+), 301 deletions(-) delete mode 100644 tests/fixture/test_data_server.go delete mode 100644 tests/fixture/test_data_server_test.go diff --git a/tests/e2e/banff/suites.go b/tests/e2e/banff/suites.go index b117080453ae..2790077a1a04 100644 --- a/tests/e2e/banff/suites.go +++ b/tests/e2e/banff/suites.go @@ -25,7 +25,7 @@ var _ = ginkgo.Describe("[Banff]", func() { ginkgo.It("can send custom assets X->P and P->X", func() { env := e2e.GetEnv(tc) - keychain := env.NewKeychain(1) + keychain := env.NewKeychain() wallet := e2e.NewWallet(tc, keychain, env.GetRandomNodeURI()) // Get the P-chain and the X-chain wallets diff --git a/tests/e2e/c/interchain_workflow.go b/tests/e2e/c/interchain_workflow.go index c50f75df34de..613020700454 100644 --- a/tests/e2e/c/interchain_workflow.go +++ b/tests/e2e/c/interchain_workflow.go @@ -39,7 +39,7 @@ var _ = e2e.DescribeCChain("[Interchain Workflow]", func() { tc.By("allocating a pre-funded key to send from and a recipient key to deliver to") var ( - senderKey = env.AllocatePreFundedKey() + senderKey = env.PreFundedKey senderEthAddress = evm.GetEthAddress(senderKey) recipientKey = e2e.NewPrivateKey(tc) recipientEthAddress = evm.GetEthAddress(recipientKey) diff --git a/tests/e2e/p/elastic_subnets.go b/tests/e2e/p/elastic_subnets.go index b49c3dff1492..100ff81780ce 100644 --- a/tests/e2e/p/elastic_subnets.go +++ b/tests/e2e/p/elastic_subnets.go @@ -46,7 +46,7 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { ginkgo.Skip("Etna is activated. Elastic Subnets are disabled post-Etna, skipping test.") } - keychain := env.NewKeychain(1) + keychain := env.NewKeychain() baseWallet := e2e.NewWallet(tc, keychain, nodeURI) pWallet := baseWallet.P() @@ -76,12 +76,15 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { owner, tc.WithDefaultContext(), ) - - subnetID = subnetTx.ID() require.NoError(err) + subnetID = subnetTx.ID() require.NotEqual(subnetID, constants.PrimaryNetworkID) }) + validatorWeight := units.Avax + initialSupply := 2 * validatorWeight + maxSupply := 2 * initialSupply + var subnetAssetID ids.ID tc.By("create a custom asset for the permissionless subnet", func() { subnetAssetTx, err := xWallet.IssueCreateAssetTx( @@ -91,7 +94,7 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { map[uint32][]verify.State{ 0: { &secp256k1fx.TransferOutput{ - Amt: 100 * units.MegaAvax, + Amt: maxSupply, OutputOwners: *owner, }, }, @@ -102,7 +105,7 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { subnetAssetID = subnetAssetTx.ID() }) - tc.By(fmt.Sprintf("Send 100 MegaAvax of asset %s to the P-chain", subnetAssetID), func() { + tc.By(fmt.Sprintf("Send %d of asset %s to the P-chain", maxSupply, subnetAssetID), func() { _, err := xWallet.IssueExportTx( constants.PlatformChainID, []*avax.TransferableOutput{ @@ -111,7 +114,7 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { ID: subnetAssetID, }, Out: &secp256k1fx.TransferOutput{ - Amt: 100 * units.MegaAvax, + Amt: maxSupply, OutputOwners: *owner, }, }, @@ -121,7 +124,7 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { require.NoError(err) }) - tc.By(fmt.Sprintf("Import the 100 MegaAvax of asset %s from the X-chain into the P-chain", subnetAssetID), func() { + tc.By(fmt.Sprintf("Import the %d of asset %s from the X-chain into the P-chain", maxSupply, subnetAssetID), func() { _, err := pWallet.IssueImportTx( xChainID, owner, @@ -134,12 +137,12 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { _, err := pWallet.IssueTransformSubnetTx( subnetID, subnetAssetID, - 50*units.MegaAvax, - 100*units.MegaAvax, + initialSupply, + maxSupply, reward.PercentDenominator, reward.PercentDenominator, 1, - 100*units.MegaAvax, + maxSupply, time.Second, 365*24*time.Hour, 0, @@ -158,7 +161,7 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { Validator: txs.Validator{ NodeID: validatorID, End: uint64(endTime.Unix()), - Wght: 25 * units.MegaAvax, + Wght: validatorWeight, }, Subnet: subnetID, }, @@ -178,7 +181,7 @@ var _ = e2e.DescribePChain("[Elastic Subnets]", func() { Validator: txs.Validator{ NodeID: validatorID, End: uint64(endTime.Unix()), - Wght: 25 * units.MegaAvax, + Wght: validatorWeight, }, Subnet: subnetID, }, diff --git a/tests/e2e/p/interchain_workflow.go b/tests/e2e/p/interchain_workflow.go index fae886168103..e612658bb8fe 100644 --- a/tests/e2e/p/interchain_workflow.go +++ b/tests/e2e/p/interchain_workflow.go @@ -52,7 +52,7 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL tc.By("creating wallet with a funded key to send from and recipient key to deliver to") recipientKey := e2e.NewPrivateKey(tc) - keychain := env.NewKeychain(1) + keychain := env.NewKeychain() keychain.Add(recipientKey) var ( @@ -100,6 +100,14 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL }, }, } + // Ensure the change is returned to the pre-funded key + // TODO(marun) Remove when the wallet does this automatically + changeOwner := common.WithChangeOwner(&secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + keychain.Keys[0].Address(), + }, + }) tc.By("adding new node and waiting for it to report healthy") node := e2e.AddEphemeralNode(tc, network, tmpnet.FlagsMap{}) @@ -144,6 +152,7 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL }, delegationShare, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -170,6 +179,7 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL Addrs: []ids.ShortID{rewardAddr}, }, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -179,6 +189,7 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL xContext.BlockchainID, exportOutputs, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -188,6 +199,7 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL constants.PlatformChainID, &recipientOwner, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -205,6 +217,7 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL cContext.BlockchainID, exportOutputs, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -218,6 +231,7 @@ var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL recipientEthAddress, tc.WithDefaultContext(), e2e.WithSuggestedGasPrice(tc, ethClient), + changeOwner, ) require.NoError(err) }) diff --git a/tests/e2e/p/owner_retrieval.go b/tests/e2e/p/owner_retrieval.go index 6ce2dbe3dd08..2e0b08ac2c46 100644 --- a/tests/e2e/p/owner_retrieval.go +++ b/tests/e2e/p/owner_retrieval.go @@ -25,7 +25,7 @@ var _ = e2e.DescribePChain("[P-Chain Wallet]", func() { nodeURI := env.GetRandomNodeURI() pChainClient := platformvm.NewClient(nodeURI.URI) - keychain := env.NewKeychain(1) + keychain := env.NewKeychain() baseWallet := e2e.NewWallet(tc, keychain, nodeURI) pWallet := baseWallet.P() @@ -41,8 +41,8 @@ var _ = e2e.DescribePChain("[P-Chain Wallet]", func() { owner, tc.WithDefaultContext(), ) - subnetID := subnetTx.ID() require.NoError(err) + subnetID := subnetTx.ID() require.NotEqual(subnetID, constants.PrimaryNetworkID) tc.By("verifying owner", func() { @@ -61,11 +61,11 @@ var _ = e2e.DescribePChain("[P-Chain Wallet]", func() { require.Equal(owner.Addrs, subnetOwner.Addrs) }) - newKeychain := env.NewKeychain(1) + newOwnerKey := e2e.NewPrivateKey(tc) newOwner := &secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ - newKeychain.Keys[0].Address(), + newOwnerKey.Address(), }, } diff --git a/tests/e2e/p/staking_rewards.go b/tests/e2e/p/staking_rewards.go index 049f9ee14e35..3f6023780f22 100644 --- a/tests/e2e/p/staking_rewards.go +++ b/tests/e2e/p/staking_rewards.go @@ -94,7 +94,7 @@ var _ = ginkgo.Describe("[Staking Rewards]", func() { deltaDelegationRewardKey, } - keychain = env.NewKeychain(1) + keychain = env.NewKeychain() nodeURI = tmpnet.NodeURI{ NodeID: alphaNodeID, URI: alphaNode.URI, diff --git a/tests/e2e/p/validator_sets.go b/tests/e2e/p/validator_sets.go index 5dc7345cadd6..81c6ab8178a9 100644 --- a/tests/e2e/p/validator_sets.go +++ b/tests/e2e/p/validator_sets.go @@ -35,7 +35,7 @@ var _ = e2e.DescribePChain("[Validator Sets]", func() { tc.By("creating wallet with a funded key to source delegated funds from") var ( - keychain = env.NewKeychain(1) + keychain = env.NewKeychain() nodeURI = env.GetRandomNodeURI() baseWallet = e2e.NewWallet(tc, keychain, nodeURI) pWallet = baseWallet.P() diff --git a/tests/e2e/p/workflow.go b/tests/e2e/p/workflow.go index 333b0c013705..34e4145608d7 100644 --- a/tests/e2e/p/workflow.go +++ b/tests/e2e/p/workflow.go @@ -19,6 +19,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ginkgo "github.com/onsi/ginkgo/v2" ) @@ -42,11 +43,15 @@ var _ = e2e.DescribePChain("[Workflow]", func() { delegationFeeShares uint32 = 20000 // TODO: retrieve programmatically ) - var ( - env = e2e.GetEnv(tc) + env := e2e.GetEnv(tc) + + // Use a pre-funded key for the P-Chain + keychain := env.NewKeychain() + // Use a new key for the X-Chain + keychain.Add(e2e.NewPrivateKey(tc)) - nodeURI = env.GetRandomNodeURI() - keychain = env.NewKeychain(2) + var ( + nodeURI = env.GetRandomNodeURI() rewardAddr = keychain.Keys[0].Address() rewardOwner = &secp256k1fx.OutputOwners{ @@ -60,6 +65,15 @@ var _ = e2e.DescribePChain("[Workflow]", func() { Addrs: []ids.ShortID{transferAddr}, } + // Ensure the change is returned to the pre-funded key + // TODO(marun) Remove when the wallet does this automatically + changeOwner = common.WithChangeOwner(&secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + keychain.Keys[0].Address(), + }, + }) + baseWallet = e2e.NewWallet(tc, keychain, nodeURI) pWallet = baseWallet.P() @@ -111,6 +125,7 @@ var _ = e2e.DescribePChain("[Workflow]", func() { rewardOwner, delegationFeeShares, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -121,6 +136,7 @@ var _ = e2e.DescribePChain("[Workflow]", func() { avaxAssetID, rewardOwner, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -146,6 +162,7 @@ var _ = e2e.DescribePChain("[Workflow]", func() { }, }, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) @@ -172,6 +189,7 @@ var _ = e2e.DescribePChain("[Workflow]", func() { constants.PlatformChainID, &transferOwner, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) diff --git a/tests/e2e/x/interchain_workflow.go b/tests/e2e/x/interchain_workflow.go index 6918a56ebe64..e1d5e5dbb8e5 100644 --- a/tests/e2e/x/interchain_workflow.go +++ b/tests/e2e/x/interchain_workflow.go @@ -34,7 +34,7 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL tc.By("creating wallet with a funded key to send from and recipient key to deliver to") recipientKey := e2e.NewPrivateKey(tc) - keychain := env.NewKeychain(1) + keychain := env.NewKeychain() keychain.Add(recipientKey) baseWallet := e2e.NewWallet(tc, keychain, nodeURI) xWallet := baseWallet.X() @@ -72,6 +72,14 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL }, }, } + // Ensure the change is returned to the pre-funded key + // TODO(marun) Remove when the wallet does this automatically + changeOwner := common.WithChangeOwner(&secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + keychain.Keys[0].Address(), + }, + }) tc.By("sending funds from one address to another on the X-Chain", func() { _, err := xWallet.IssueBaseTx( @@ -85,6 +93,7 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL }, }}, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -102,6 +111,7 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL cContext.BlockchainID, exportOutputs, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -115,6 +125,7 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL recipientEthAddress, tc.WithDefaultContext(), e2e.WithSuggestedGasPrice(tc, ethClient), + changeOwner, ) require.NoError(err) }) @@ -131,6 +142,7 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL constants.PlatformChainID, exportOutputs, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) @@ -140,6 +152,7 @@ var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainL xContext.BlockchainID, &recipientOwner, tc.WithDefaultContext(), + changeOwner, ) require.NoError(err) }) diff --git a/tests/e2e/x/transfer/virtuous.go b/tests/e2e/x/transfer/virtuous.go index db9c1508c1d2..5c59b599ba40 100644 --- a/tests/e2e/x/transfer/virtuous.go +++ b/tests/e2e/x/transfer/virtuous.go @@ -16,7 +16,10 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/tests" "github.com/ava-labs/avalanchego/tests/fixture/e2e" + "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" + "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/set" + "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/avm" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -76,7 +79,42 @@ var _ = e2e.DescribeXChainSerial("[Virtuous Transfer Tx AVAX]", func() { // Ensure the same set of 10 keys is used for all tests // by retrieving them outside of runFunc. - testKeys := env.AllocatePreFundedKeys(10) + testKeys := []*secp256k1.PrivateKey{ + // The funded key will be the source of funds for the new keys + env.PreFundedKey, + } + newKeys, err := tmpnet.NewPrivateKeys(9) + require.NoError(err) + testKeys = append(testKeys, newKeys...) + + const transferPerRound = units.MilliAvax + + tc.By("Funding new keys") + fundingWallet := e2e.NewWallet(tc, env.NewKeychain(), env.GetRandomNodeURI()) + fundingOutputs := make([]*avax.TransferableOutput, len(newKeys)) + fundingAssetID := fundingWallet.X().Builder().Context().AVAXAssetID + for i, key := range newKeys { + fundingOutputs[i] = &avax.TransferableOutput{ + Asset: avax.Asset{ + ID: fundingAssetID, + }, + Out: &secp256k1fx.TransferOutput{ + // Enough for 1 transfer per round + Amt: totalRounds * transferPerRound, + OutputOwners: secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + key.Address(), + }, + }, + }, + } + } + _, err = fundingWallet.X().IssueBaseTx( + fundingOutputs, + tc.WithDefaultContext(), + ) + require.NoError(err) runFunc := func(round int) { tc.Outf("{{green}}\n\n\n\n\n\n---\n[ROUND #%02d]:{{/}}\n", round) @@ -158,9 +196,7 @@ var _ = e2e.DescribeXChainSerial("[Virtuous Transfer Tx AVAX]", func() { senderOrigBal := testBalances[fromIdx] receiverOrigBal := testBalances[toIdx] - - amountToTransfer := senderOrigBal / 10 - + amountToTransfer := transferPerRound senderNewBal := senderOrigBal - amountToTransfer - xContext.BaseTxFee receiverNewBal := receiverOrigBal + amountToTransfer diff --git a/tests/fixture/e2e/env.go b/tests/fixture/e2e/env.go index 59ad8c4a67bf..a8b10c19c9fa 100644 --- a/tests/fixture/e2e/env.go +++ b/tests/fixture/e2e/env.go @@ -15,10 +15,11 @@ import ( "github.com/ava-labs/avalanchego/api/info" "github.com/ava-labs/avalanchego/config" "github.com/ava-labs/avalanchego/tests" - "github.com/ava-labs/avalanchego/tests/fixture" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + + ginkgo "github.com/onsi/ginkgo/v2" ) // Env is used to access shared test fixture. Intended to be @@ -31,6 +32,13 @@ func InitSharedTestEnvironment(t require.TestingT, envBytes []byte) { require.Nil(env, "env already initialized") env = &TestEnvironment{} require.NoError(json.Unmarshal(envBytes, env)) + + // Ginkgo parallelization is at the process level, so a given key + // can safely be used by all tests in a given process without fear + // of conflicting usage. + network := env.GetNetwork() + env.PreFundedKey = network.PreFundedKeys[ginkgo.GinkgoParallelProcess()] + require.NotNil(env.PreFundedKey) } type TestEnvironment struct { @@ -38,8 +46,8 @@ type TestEnvironment struct { NetworkDir string // URIs used to access the API endpoints of nodes of the network URIs []tmpnet.NodeURI - // The URI used to access the http server that allocates test data - TestDataServerURI string + // Pre-funded key for this ginkgo process + PreFundedKey *secp256k1.PrivateKey // The duration to wait before shutting down private networks. A // non-zero value may be useful to ensure all metrics can be // scraped before shutdown. @@ -53,7 +61,7 @@ func GetEnv(tc tests.TestContext) *TestEnvironment { return &TestEnvironment{ NetworkDir: env.NetworkDir, URIs: env.URIs, - TestDataServerURI: env.TestDataServerURI, + PreFundedKey: env.PreFundedKey, PrivateNetworkShutdownDelay: env.PrivateNetworkShutdownDelay, testContext: tc, } @@ -148,20 +156,20 @@ func NewTestEnvironment(tc tests.TestContext, flagVars *FlagVars, desiredNetwork }, DefaultTimeout, DefaultPollingInterval, "failed to see all chains bootstrap before timeout") } + suiteConfig, _ := ginkgo.GinkgoConfiguration() + require.Greater( + len(network.PreFundedKeys), + suiteConfig.ParallelTotal, + "not enough pre-funded keys for the requested number of parallel test processes", + ) + uris := network.GetNodeURIs() require.NotEmpty(uris, "network contains no nodes") tc.Outf("{{green}}network URIs: {{/}} %+v\n", uris) - testDataServerURI, err := fixture.ServeTestData(fixture.TestData{ - PreFundedKeys: network.PreFundedKeys, - }) - tc.Outf("{{green}}test data server URI: {{/}} %+v\n", testDataServerURI) - require.NoError(err) - return &TestEnvironment{ NetworkDir: network.Dir, URIs: uris, - TestDataServerURI: testDataServerURI, PrivateNetworkShutdownDelay: flagVars.NetworkShutdownDelay(), testContext: tc, } @@ -183,23 +191,9 @@ func (te *TestEnvironment) GetNetwork() *tmpnet.Network { return network } -// Retrieve the specified number of funded keys allocated for the caller's exclusive use. -func (te *TestEnvironment) AllocatePreFundedKeys(count int) []*secp256k1.PrivateKey { - keys, err := fixture.AllocatePreFundedKeys(te.TestDataServerURI, count) - require.NoError(te.testContext, err) - te.testContext.Outf("{{blue}} allocated pre-funded key(s): %+v{{/}}\n", keys) - return keys -} - -// Retrieve a funded key allocated for the caller's exclusive use. -func (te *TestEnvironment) AllocatePreFundedKey() *secp256k1.PrivateKey { - return te.AllocatePreFundedKeys(1)[0] -} - -// Create a new keychain with the specified number of test keys. -func (te *TestEnvironment) NewKeychain(count int) *secp256k1fx.Keychain { - keys := te.AllocatePreFundedKeys(count) - return secp256k1fx.NewKeychain(keys...) +// Create a new keychain with the process's pre-funded key. +func (te *TestEnvironment) NewKeychain() *secp256k1fx.Keychain { + return secp256k1fx.NewKeychain(te.PreFundedKey) } // Create a new private network that is not shared with other tests. diff --git a/tests/fixture/test_data_server.go b/tests/fixture/test_data_server.go deleted file mode 100644 index b79dcc2bb26b..000000000000 --- a/tests/fixture/test_data_server.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package fixture - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - "github.com/ava-labs/avalanchego/utils" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" -) - -const ( - allocateKeysPath = "/allocateKeys" - keyCountParameterName = "count" - requestedKeyCountExceedsAvailable = "requested key count exceeds available allocation" -) - -var ( - errRequestedKeyCountExceedsAvailable = errors.New(requestedKeyCountExceedsAvailable) - errInvalidKeyCount = errors.New("key count must be greater than zero") -) - -type TestData struct { - PreFundedKeys []*secp256k1.PrivateKey -} - -// http server allocating resources to tests potentially executing in parallel -type testDataServer struct { - // Synchronizes access to test data - lock sync.Mutex - TestData -} - -// Type used to marshal/unmarshal a set of test keys for transmission over http. -type keysDocument struct { - Keys []*secp256k1.PrivateKey `json:"keys"` -} - -func (s *testDataServer) allocateKeys(w http.ResponseWriter, r *http.Request) { - // Attempt to parse the count parameter - rawKeyCount := r.URL.Query().Get(keyCountParameterName) - if len(rawKeyCount) == 0 { - msg := fmt.Sprintf("missing %q parameter", keyCountParameterName) - http.Error(w, msg, http.StatusBadRequest) - return - } - keyCount, err := strconv.Atoi(rawKeyCount) - if err != nil { - msg := fmt.Sprintf("unable to parse %q parameter: %v", keyCountParameterName, err) - http.Error(w, msg, http.StatusBadRequest) - return - } - - // Ensure a key will be allocated at most once - s.lock.Lock() - defer s.lock.Unlock() - - // Only fulfill requests for available keys - if keyCount > len(s.PreFundedKeys) { - http.Error(w, requestedKeyCountExceedsAvailable, http.StatusInternalServerError) - return - } - - // Allocate the requested number of keys - remainingKeys := len(s.PreFundedKeys) - keyCount - allocatedKeys := s.PreFundedKeys[remainingKeys:] - - keysDoc := &keysDocument{ - Keys: allocatedKeys, - } - if err := json.NewEncoder(w).Encode(keysDoc); err != nil { - msg := fmt.Sprintf("failed to encode test keys: %v", err) - http.Error(w, msg, http.StatusInternalServerError) - return - } - - // Forget the allocated keys - utils.ZeroSlice(allocatedKeys) - s.PreFundedKeys = s.PreFundedKeys[:remainingKeys] -} - -// Serve test data via http to ensure allocation is synchronized even when -// ginkgo specs are executing in parallel. Returns the URI to access the server. -func ServeTestData(testData TestData) (string, error) { - // Listen on a dynamic port to avoid conflicting with other applications - listener, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - return "", fmt.Errorf("failed to initialize listener for test data server: %w", err) - } - address := fmt.Sprintf("http://%s", listener.Addr()) - - s := &testDataServer{ - TestData: testData, - } - mux := http.NewServeMux() - mux.HandleFunc(allocateKeysPath, s.allocateKeys) - - httpServer := &http.Server{ - Handler: mux, - ReadHeaderTimeout: 3 * time.Second, - } - - go func() { - // Serve always returns a non-nil error and closes l. - if err := httpServer.Serve(listener); err != http.ErrServerClosed { - panic(fmt.Sprintf("unexpected error closing test data server: %v", err)) - } - }() - - return address, nil -} - -// Retrieve the specified number of pre-funded test keys from the provided URI. A given -// key is allocated at most once during the life of the test data server. -func AllocatePreFundedKeys(baseURI string, count int) ([]*secp256k1.PrivateKey, error) { - if count <= 0 { - return nil, errInvalidKeyCount - } - - uri, err := url.Parse(baseURI) - if err != nil { - return nil, fmt.Errorf("failed to parse uri: %w", err) - } - uri.RawQuery = url.Values{ - keyCountParameterName: {strconv.Itoa(count)}, - }.Encode() - uri.Path = allocateKeysPath - req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, uri.String(), nil) - if err != nil { - return nil, fmt.Errorf("failed to construct request: %w", err) - } - - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, fmt.Errorf("failed to request pre-funded keys: %w", err) - } - defer resp.Body.Close() - - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("failed to read response for pre-funded keys: %w", err) - } - if resp.StatusCode != http.StatusOK { - if strings.TrimSpace(string(body)) == requestedKeyCountExceedsAvailable { - return nil, errRequestedKeyCountExceedsAvailable - } - return nil, fmt.Errorf("test data server returned unexpected status code %d: %v", resp.StatusCode, body) - } - - keysDoc := &keysDocument{} - if err := json.Unmarshal(body, keysDoc); err != nil { - return nil, fmt.Errorf("failed to unmarshal pre-funded keys: %w", err) - } - return keysDoc.Keys, nil -} diff --git a/tests/fixture/test_data_server_test.go b/tests/fixture/test_data_server_test.go deleted file mode 100644 index 7191ae75efaa..000000000000 --- a/tests/fixture/test_data_server_test.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package fixture - -import ( - "testing" - - "github.com/stretchr/testify/require" - - "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" -) - -// Check that funded test keys can be served from an http server to -// ensure at-most-once allocation when tests are executed in parallel. -func TestAllocatePreFundedKeys(t *testing.T) { - keys := make([]*secp256k1.PrivateKey, 5) - for i := range keys { - key, err := secp256k1.NewPrivateKey() - require.NoError(t, err) - keys[i] = key - } - - uri, err := ServeTestData(TestData{ - PreFundedKeys: keys, - }) - require.NoError(t, err) - - testCases := []struct { - name string - count int - expectedAddresses []ids.ShortID - expectedError error - }{ - { - name: "single key", - count: 1, - expectedAddresses: []ids.ShortID{ - keys[4].Address(), - }, - expectedError: nil, - }, - { - name: "multiple keys", - count: 4, - expectedAddresses: []ids.ShortID{ - keys[0].Address(), - keys[1].Address(), - keys[2].Address(), - keys[3].Address(), - }, - expectedError: nil, - }, - { - name: "insufficient keys available", - count: 1, - expectedAddresses: []ids.ShortID{}, - expectedError: errRequestedKeyCountExceedsAvailable, - }, - } - for _, tc := range testCases { - t.Run(tc.name, func(t *testing.T) { - require := require.New(t) - - keys, err := AllocatePreFundedKeys(uri, tc.count) - require.ErrorIs(err, tc.expectedError) - - addresses := make([]ids.ShortID, len(keys)) - for i, key := range keys { - addresses[i] = key.Address() - } - require.Equal(tc.expectedAddresses, addresses) - }) - } -} From bb9f77ecf42a3abe0098bf928196984ad6d3a10a Mon Sep 17 00:00:00 2001 From: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> Date: Thu, 22 Aug 2024 14:36:27 -0400 Subject: [PATCH 41/69] Move iterator implementations to `utils` pkg (#3320) --- scripts/mocks.mockgen.source.txt | 4 +- scripts/mocks.mockgen.txt | 2 - utils/iterator/empty.go | 21 + utils/iterator/empty_test.go | 24 + utils/iterator/filter.go | 38 ++ .../iterator/filter_test.go | 19 +- utils/iterator/iterator.go | 19 + utils/iterator/iteratormock/iterator.go | 79 +++ .../iterator/merge.go | 55 +- .../iterator/merge_test.go | 93 +-- utils/iterator/slice.go | 31 + utils/iterator/tree.go | 63 ++ .../iterator/tree_test.go | 26 +- vms/platformvm/block/builder/builder_test.go | 28 +- .../block/executor/acceptor_test.go | 29 +- vms/platformvm/block/executor/backend_test.go | 3 +- .../block/executor/proposal_block_test.go | 12 +- .../block/executor/standard_block_test.go | 10 +- .../block/executor/verifier_test.go | 33 +- vms/platformvm/state/diff.go | 13 +- vms/platformvm/state/diff_test.go | 5 +- vms/platformvm/state/empty_iterator.go | 19 - vms/platformvm/state/empty_iterator_test.go | 20 - vms/platformvm/state/masked_iterator.go | 40 -- vms/platformvm/state/mock_chain.go | 526 +++++++++++++++++ vms/platformvm/state/mock_diff.go | 540 ++++++++++++++++++ vms/platformvm/state/mock_staker_iterator.go | 79 --- vms/platformvm/state/mock_state.go | 17 +- vms/platformvm/state/slice_iterator_test.go | 31 - vms/platformvm/state/staker.go | 15 - vms/platformvm/state/staker_diff_iterator.go | 13 +- .../state/staker_diff_iterator_test.go | 7 +- vms/platformvm/state/stakers.go | 53 +- vms/platformvm/state/stakers_test.go | 39 +- vms/platformvm/state/state.go | 16 +- vms/platformvm/state/state_test.go | 7 +- vms/platformvm/state/statemock/chain.go | 526 ----------------- vms/platformvm/state/statemock/diff.go | 540 ------------------ vms/platformvm/state/tree_iterator.go | 65 --- .../executor/staker_tx_verification_test.go | 39 +- .../txs/executor/standard_tx_executor_test.go | 29 +- 41 files changed, 1630 insertions(+), 1598 deletions(-) create mode 100644 utils/iterator/empty.go create mode 100644 utils/iterator/empty_test.go create mode 100644 utils/iterator/filter.go rename vms/platformvm/state/masked_iterator_test.go => utils/iterator/filter_test.go (66%) create mode 100644 utils/iterator/iterator.go create mode 100644 utils/iterator/iteratormock/iterator.go rename vms/platformvm/state/merged_iterator.go => utils/iterator/merge.go (54%) rename vms/platformvm/state/merged_iterator_test.go => utils/iterator/merge_test.go (63%) create mode 100644 utils/iterator/slice.go create mode 100644 utils/iterator/tree.go rename vms/platformvm/state/tree_iterator_test.go => utils/iterator/tree_test.go (68%) delete mode 100644 vms/platformvm/state/empty_iterator.go delete mode 100644 vms/platformvm/state/empty_iterator_test.go delete mode 100644 vms/platformvm/state/masked_iterator.go create mode 100644 vms/platformvm/state/mock_chain.go create mode 100644 vms/platformvm/state/mock_diff.go delete mode 100644 vms/platformvm/state/mock_staker_iterator.go delete mode 100644 vms/platformvm/state/slice_iterator_test.go delete mode 100644 vms/platformvm/state/statemock/chain.go delete mode 100644 vms/platformvm/state/statemock/diff.go delete mode 100644 vms/platformvm/state/tree_iterator.go diff --git a/scripts/mocks.mockgen.source.txt b/scripts/mocks.mockgen.source.txt index 465e8ea5d888..1862ac015866 100644 --- a/scripts/mocks.mockgen.source.txt +++ b/scripts/mocks.mockgen.source.txt @@ -1,14 +1,16 @@ snow/engine/common/sender.go=StateSummarySender,AcceptedStateSummarySender,FrontierSender,AcceptedSender,FetchSender,AppSender,QuerySender,Gossiper=Sender=snow/engine/common/commonmock/sender.go snow/networking/router/router.go=InternalHandler=Router=snow/networking/router/routermock/router.go snow/networking/sender/external_sender.go==ExternalSender=snow/networking/sender/sendermock/external_sender.go +utils/iterator/iterator.go==Iterator=utils/iterator/iteratormock/iterator.go vms/avm/block/block.go==MockBlock=vms/avm/block/mock_block.go vms/avm/block/executor/manager.go==Manager=vms/avm/block/executor/executormock/manager.go vms/avm/txs/tx.go==UnsignedTx=vms/avm/txs/txsmock/tx.go vms/platformvm/block/block.go=BanffBlock=MockBlock=vms/platformvm/block/mock_block.go vms/platformvm/block/executor/manager.go==Manager=vms/platformvm/block/executor/executormock/manager.go vms/platformvm/signer/signer.go==Signer=vms/platformvm/signer/signermock/signer.go -vms/platformvm/state/staker.go==MockStakerIterator=vms/platformvm/state/mock_staker_iterator.go +vms/platformvm/state/diff.go==MockDiff=vms/platformvm/state/mock_diff.go vms/platformvm/state/state.go=Chain=MockState=vms/platformvm/state/mock_state.go +vms/platformvm/state/state.go=State=MockChain=vms/platformvm/state/mock_chain.go vms/platformvm/txs/unsigned_tx.go==UnsignedTx=vms/platformvm/txs/txsmock/unsigned_tx.go vms/proposervm/block.go=Block=MockPostForkBlock=vms/proposervm/mock_post_fork_block.go x/merkledb/db.go=ChangeProofer,RangeProofer,Clearer,Prefetcher=MockMerkleDB=x/merkledb/mock_db.go diff --git a/scripts/mocks.mockgen.txt b/scripts/mocks.mockgen.txt index 7763fa06e6e3..256fcf1a11d9 100644 --- a/scripts/mocks.mockgen.txt +++ b/scripts/mocks.mockgen.txt @@ -30,8 +30,6 @@ github.com/ava-labs/avalanchego/vms/avm/txs/mempool=Mempool=vms/avm/txs/mempool/ github.com/ava-labs/avalanchego/vms/components/avax=TransferableIn=vms/components/avax/avaxmock/transferable_in.go github.com/ava-labs/avalanchego/vms/components/verify=Verifiable=vms/components/verify/verifymock/verifiable.go github.com/ava-labs/avalanchego/vms/platformvm/fx=Fx=vms/platformvm/fx/fxmock/fx.go -github.com/ava-labs/avalanchego/vms/platformvm/state=Chain=vms/platformvm/state/statemock/chain.go -github.com/ava-labs/avalanchego/vms/platformvm/state=Diff=vms/platformvm/state/statemock/diff.go github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool=Mempool=vms/platformvm/txs/mempool/mempoolmock/mempool.go github.com/ava-labs/avalanchego/vms/platformvm/utxo=Verifier=vms/platformvm/utxo/utxomock/verifier.go github.com/ava-labs/avalanchego/vms/proposervm/proposer=Windower=vms/proposervm/proposer/proposermock/windower.go diff --git a/utils/iterator/empty.go b/utils/iterator/empty.go new file mode 100644 index 000000000000..883647529246 --- /dev/null +++ b/utils/iterator/empty.go @@ -0,0 +1,21 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package iterator + +import "github.com/ava-labs/avalanchego/utils" + +var _ Iterator[any] = Empty[any]{} + +// Empty is an iterator with no elements. +type Empty[T any] struct{} + +func (Empty[_]) Next() bool { + return false +} + +func (Empty[T]) Value() T { + return utils.Zero[T]() +} + +func (Empty[_]) Release() {} diff --git a/utils/iterator/empty_test.go b/utils/iterator/empty_test.go new file mode 100644 index 000000000000..bb1861c8548b --- /dev/null +++ b/utils/iterator/empty_test.go @@ -0,0 +1,24 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package iterator + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestEmpty(t *testing.T) { + var ( + require = require.New(t) + empty = Empty[*int]{} + ) + + require.False(empty.Next()) + + empty.Release() + + require.False(empty.Next()) + require.Nil(empty.Value()) +} diff --git a/utils/iterator/filter.go b/utils/iterator/filter.go new file mode 100644 index 000000000000..e8a11464457d --- /dev/null +++ b/utils/iterator/filter.go @@ -0,0 +1,38 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package iterator + +var _ Iterator[any] = (*filtered[any])(nil) + +type filtered[T any] struct { + it Iterator[T] + filter func(T) bool +} + +// Filter returns an iterator that skips the elements in [it] that return true +// from [filter]. +func Filter[T any](it Iterator[T], filter func(T) bool) Iterator[T] { + return &filtered[T]{ + it: it, + filter: filter, + } +} + +func (i *filtered[_]) Next() bool { + for i.it.Next() { + element := i.it.Value() + if !i.filter(element) { + return true + } + } + return false +} + +func (i *filtered[T]) Value() T { + return i.it.Value() +} + +func (i *filtered[_]) Release() { + i.it.Release() +} diff --git a/vms/platformvm/state/masked_iterator_test.go b/utils/iterator/filter_test.go similarity index 66% rename from vms/platformvm/state/masked_iterator_test.go rename to utils/iterator/filter_test.go index ccc37d6ffb3d..bf523017fe92 100644 --- a/vms/platformvm/state/masked_iterator_test.go +++ b/utils/iterator/filter_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package state +package iterator_test import ( "testing" @@ -10,11 +10,13 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/iterator" + "github.com/ava-labs/avalanchego/vms/platformvm/state" ) -func TestMaskedIterator(t *testing.T) { +func TestFilter(t *testing.T) { require := require.New(t) - stakers := []*Staker{ + stakers := []*state.Staker{ { TxID: ids.GenerateTestID(), NextTime: time.Unix(0, 0), @@ -32,15 +34,18 @@ func TestMaskedIterator(t *testing.T) { NextTime: time.Unix(3, 0), }, } - maskedStakers := map[ids.ID]*Staker{ + maskedStakers := map[ids.ID]*state.Staker{ stakers[0].TxID: stakers[0], stakers[2].TxID: stakers[2], stakers[3].TxID: stakers[3], } - it := NewMaskedIterator( - NewSliceIterator(stakers[:3]...), - maskedStakers, + it := iterator.Filter( + iterator.FromSlice(stakers[:3]...), + func(staker *state.Staker) bool { + _, ok := maskedStakers[staker.TxID] + return ok + }, ) require.True(it.Next()) diff --git a/utils/iterator/iterator.go b/utils/iterator/iterator.go new file mode 100644 index 000000000000..2bb7a14fd6e5 --- /dev/null +++ b/utils/iterator/iterator.go @@ -0,0 +1,19 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package iterator + +// Iterator defines an interface for iterating over a set. +type Iterator[T any] interface { + // Next attempts to move the iterator to the next element in the set. It + // returns false once there are no more elements to return. + Next() bool + + // Value returns the value of the current element. Value should only be called + // after a call to Next which returned true. + Value() T + + // Release any resources associated with the iterator. This must be called + // after the iterator is no longer needed. + Release() +} diff --git a/utils/iterator/iteratormock/iterator.go b/utils/iterator/iteratormock/iterator.go new file mode 100644 index 000000000000..bb24bc14ac9c --- /dev/null +++ b/utils/iterator/iteratormock/iterator.go @@ -0,0 +1,79 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: utils/iterator/iterator.go +// +// Generated by this command: +// +// mockgen -source=utils/iterator/iterator.go -destination=utils/iterator/iteratormock/iterator.go -package=iteratormock -exclude_interfaces= -mock_names=Iterator=Iterator +// + +// Package iteratormock is a generated GoMock package. +package iteratormock + +import ( + reflect "reflect" + + gomock "go.uber.org/mock/gomock" +) + +// Iterator is a mock of Iterator interface. +type Iterator[T any] struct { + ctrl *gomock.Controller + recorder *IteratorMockRecorder[T] +} + +// IteratorMockRecorder is the mock recorder for Iterator. +type IteratorMockRecorder[T any] struct { + mock *Iterator[T] +} + +// NewIterator creates a new mock instance. +func NewIterator[T any](ctrl *gomock.Controller) *Iterator[T] { + mock := &Iterator[T]{ctrl: ctrl} + mock.recorder = &IteratorMockRecorder[T]{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *Iterator[T]) EXPECT() *IteratorMockRecorder[T] { + return m.recorder +} + +// Next mocks base method. +func (m *Iterator[T]) Next() bool { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Next") + ret0, _ := ret[0].(bool) + return ret0 +} + +// Next indicates an expected call of Next. +func (mr *IteratorMockRecorder[T]) Next() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Next", reflect.TypeOf((*Iterator[T])(nil).Next)) +} + +// Release mocks base method. +func (m *Iterator[T]) Release() { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Release") +} + +// Release indicates an expected call of Release. +func (mr *IteratorMockRecorder[T]) Release() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Release", reflect.TypeOf((*Iterator[T])(nil).Release)) +} + +// Value mocks base method. +func (m *Iterator[T]) Value() T { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Value") + ret0, _ := ret[0].(T) + return ret0 +} + +// Value indicates an expected call of Value. +func (mr *IteratorMockRecorder[T]) Value() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Value", reflect.TypeOf((*Iterator[T])(nil).Value)) +} diff --git a/vms/platformvm/state/merged_iterator.go b/utils/iterator/merge.go similarity index 54% rename from vms/platformvm/state/merged_iterator.go rename to utils/iterator/merge.go index 059001b3144f..9c0b72a81060 100644 --- a/vms/platformvm/state/merged_iterator.go +++ b/utils/iterator/merge.go @@ -1,50 +1,55 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package state +package iterator -import "github.com/ava-labs/avalanchego/utils/heap" +import ( + "github.com/google/btree" -var _ StakerIterator = (*mergedIterator)(nil) + "github.com/ava-labs/avalanchego/utils/heap" +) -type mergedIterator struct { +var _ Iterator[any] = (*merged[any])(nil) + +type merged[T any] struct { initialized bool // heap only contains iterators that have been initialized and are not // exhausted. - heap heap.Queue[StakerIterator] + heap heap.Queue[Iterator[T]] } -// Returns an iterator that returns all of the elements of [stakers] in order. -func NewMergedIterator(stakers ...StakerIterator) StakerIterator { +// Merge returns an iterator that returns all of the elements of [iterators] in +// order. +func Merge[T any](less btree.LessFunc[T], iterators ...Iterator[T]) Iterator[T] { // Filter out iterators that are already exhausted. i := 0 - for i < len(stakers) { - staker := stakers[i] - if staker.Next() { + for i < len(iterators) { + it := iterators[i] + if it.Next() { i++ continue } - staker.Release() + it.Release() - newLength := len(stakers) - 1 - stakers[i] = stakers[newLength] - stakers[newLength] = nil - stakers = stakers[:newLength] + newLength := len(iterators) - 1 + iterators[i] = iterators[newLength] + iterators[newLength] = nil + iterators = iterators[:newLength] } - it := &mergedIterator{ + it := &merged[T]{ heap: heap.QueueOf( - func(a, b StakerIterator) bool { - return a.Value().Less(b.Value()) + func(a, b Iterator[T]) bool { + return less(a.Value(), b.Value()) }, - stakers..., + iterators..., ), } return it } -func (it *mergedIterator) Next() bool { +func (it *merged[_]) Next() bool { if it.heap.Len() == 0 { return false } @@ -52,7 +57,7 @@ func (it *mergedIterator) Next() bool { if !it.initialized { // Note that on the first call to Next() (i.e. here) we don't call // Next() on the current iterator. This is because we already called - // Next() on each iterator in NewMergedIterator. + // Next() on each iterator in Merge. it.initialized = true return true } @@ -71,18 +76,14 @@ func (it *mergedIterator) Next() bool { return it.heap.Len() > 0 } -func (it *mergedIterator) Value() *Staker { +func (it *merged[T]) Value() T { peek, _ := it.heap.Peek() return peek.Value() } -func (it *mergedIterator) Release() { +func (it *merged[_]) Release() { for it.heap.Len() > 0 { removed, _ := it.heap.Pop() removed.Release() } } - -func (it *mergedIterator) Len() int { - return it.heap.Len() -} diff --git a/vms/platformvm/state/merged_iterator_test.go b/utils/iterator/merge_test.go similarity index 63% rename from vms/platformvm/state/merged_iterator_test.go rename to utils/iterator/merge_test.go index e6cd52451f73..5be57f90ee63 100644 --- a/vms/platformvm/state/merged_iterator_test.go +++ b/utils/iterator/merge_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package state +package iterator_test import ( "testing" @@ -10,52 +10,54 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/iterator" + "github.com/ava-labs/avalanchego/vms/platformvm/state" ) -func TestMergedIterator(t *testing.T) { +func TestMerge(t *testing.T) { type test struct { name string - iterators []StakerIterator - expected []*Staker + iterators []iterator.Iterator[*state.Staker] + expected []*state.Staker } txID := ids.GenerateTestID() tests := []test{ { name: "no iterators", - iterators: []StakerIterator{}, - expected: []*Staker{}, + iterators: []iterator.Iterator[*state.Staker]{}, + expected: []*state.Staker{}, }, { name: "one empty iterator", - iterators: []StakerIterator{EmptyIterator}, - expected: []*Staker{}, + iterators: []iterator.Iterator[*state.Staker]{iterator.Empty[*state.Staker]{}}, + expected: []*state.Staker{}, }, { name: "multiple empty iterator", - iterators: []StakerIterator{EmptyIterator, EmptyIterator, EmptyIterator}, - expected: []*Staker{}, + iterators: []iterator.Iterator[*state.Staker]{iterator.Empty[*state.Staker]{}, iterator.Empty[*state.Staker]{}, iterator.Empty[*state.Staker]{}}, + expected: []*state.Staker{}, }, { name: "mixed empty iterators", - iterators: []StakerIterator{EmptyIterator, NewSliceIterator()}, - expected: []*Staker{}, + iterators: []iterator.Iterator[*state.Staker]{iterator.Empty[*state.Staker]{}, iterator.FromSlice[*state.Staker]()}, + expected: []*state.Staker{}, }, { name: "single iterator", - iterators: []StakerIterator{ - NewSliceIterator( - &Staker{ + iterators: []iterator.Iterator[*state.Staker]{ + iterator.FromSlice[*state.Staker]( + &state.Staker{ TxID: txID, NextTime: time.Unix(0, 0), }, - &Staker{ + &state.Staker{ TxID: txID, NextTime: time.Unix(1, 0), }, ), }, - expected: []*Staker{ + expected: []*state.Staker{ { TxID: txID, NextTime: time.Unix(0, 0), @@ -68,29 +70,29 @@ func TestMergedIterator(t *testing.T) { }, { name: "multiple iterators", - iterators: []StakerIterator{ - NewSliceIterator( - &Staker{ + iterators: []iterator.Iterator[*state.Staker]{ + iterator.FromSlice[*state.Staker]( + &state.Staker{ TxID: txID, NextTime: time.Unix(0, 0), }, - &Staker{ + &state.Staker{ TxID: txID, NextTime: time.Unix(2, 0), }, ), - NewSliceIterator( - &Staker{ + iterator.FromSlice[*state.Staker]( + &state.Staker{ TxID: txID, NextTime: time.Unix(1, 0), }, - &Staker{ + &state.Staker{ TxID: txID, NextTime: time.Unix(3, 0), }, ), }, - expected: []*Staker{ + expected: []*state.Staker{ { TxID: txID, NextTime: time.Unix(0, 0), @@ -111,37 +113,37 @@ func TestMergedIterator(t *testing.T) { }, { name: "multiple iterators different lengths", - iterators: []StakerIterator{ - NewSliceIterator( - &Staker{ + iterators: []iterator.Iterator[*state.Staker]{ + iterator.FromSlice[*state.Staker]( + &state.Staker{ TxID: txID, NextTime: time.Unix(0, 0), }, - &Staker{ + &state.Staker{ TxID: txID, NextTime: time.Unix(2, 0), }, ), - NewSliceIterator( - &Staker{ + iterator.FromSlice[*state.Staker]( + &state.Staker{ TxID: txID, NextTime: time.Unix(1, 0), }, - &Staker{ + &state.Staker{ TxID: txID, NextTime: time.Unix(3, 0), }, - &Staker{ + &state.Staker{ TxID: txID, NextTime: time.Unix(4, 0), }, - &Staker{ + &state.Staker{ TxID: txID, NextTime: time.Unix(5, 0), }, ), }, - expected: []*Staker{ + expected: []*state.Staker{ { TxID: txID, NextTime: time.Unix(0, 0), @@ -173,7 +175,7 @@ func TestMergedIterator(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { require := require.New(t) - it := NewMergedIterator(tt.iterators...) + it := iterator.Merge[*state.Staker]((*state.Staker).Less, tt.iterators...) for _, expected := range tt.expected { require.True(it.Next()) require.Equal(expected, it.Value()) @@ -185,9 +187,9 @@ func TestMergedIterator(t *testing.T) { } } -func TestMergedIteratorEarlyRelease(t *testing.T) { +func TestMergedEarlyRelease(t *testing.T) { require := require.New(t) - stakers0 := []*Staker{ + stakers0 := []*state.Staker{ { TxID: ids.GenerateTestID(), NextTime: time.Unix(0, 0), @@ -198,7 +200,7 @@ func TestMergedIteratorEarlyRelease(t *testing.T) { }, } - stakers1 := []*Staker{ + stakers1 := []*state.Staker{ { TxID: ids.GenerateTestID(), NextTime: time.Unix(1, 0), @@ -209,12 +211,13 @@ func TestMergedIteratorEarlyRelease(t *testing.T) { }, } - it := NewMergedIterator( - EmptyIterator, - NewSliceIterator(stakers0...), - EmptyIterator, - NewSliceIterator(stakers1...), - EmptyIterator, + it := iterator.Merge( + (*state.Staker).Less, + iterator.Empty[*state.Staker]{}, + iterator.FromSlice(stakers0...), + iterator.Empty[*state.Staker]{}, + iterator.FromSlice(stakers1...), + iterator.Empty[*state.Staker]{}, ) require.True(it.Next()) it.Release() diff --git a/utils/iterator/slice.go b/utils/iterator/slice.go new file mode 100644 index 000000000000..d195a1adc14c --- /dev/null +++ b/utils/iterator/slice.go @@ -0,0 +1,31 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package iterator + +var _ Iterator[any] = (*slice[any])(nil) + +type slice[T any] struct { + index int + elements []T +} + +// FromSlice returns an iterator that contains [elements] in order. Doesn't sort +// by anything. +func FromSlice[T any](elements ...T) Iterator[T] { + return &slice[T]{ + index: -1, + elements: elements, + } +} + +func (i *slice[_]) Next() bool { + i.index++ + return i.index < len(i.elements) +} + +func (i *slice[T]) Value() T { + return i.elements[i.index] +} + +func (*slice[_]) Release() {} diff --git a/utils/iterator/tree.go b/utils/iterator/tree.go new file mode 100644 index 000000000000..a27206af7a2e --- /dev/null +++ b/utils/iterator/tree.go @@ -0,0 +1,63 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package iterator + +import ( + "sync" + + "github.com/google/btree" +) + +var _ Iterator[any] = (*tree[any])(nil) + +type tree[T any] struct { + current T + next chan T + releaseOnce sync.Once + release chan struct{} + wg sync.WaitGroup +} + +// FromTree returns a new iterator of the stakers in [tree] in ascending order. +// Note that it isn't safe to modify [tree] while iterating over it. +func FromTree[T any](btree *btree.BTreeG[T]) Iterator[T] { + if btree == nil { + return Empty[T]{} + } + it := &tree[T]{ + next: make(chan T), + release: make(chan struct{}), + } + it.wg.Add(1) + go func() { + defer it.wg.Done() + btree.Ascend(func(i T) bool { + select { + case it.next <- i: + return true + case <-it.release: + return false + } + }) + close(it.next) + }() + return it +} + +func (i *tree[_]) Next() bool { + next, ok := <-i.next + i.current = next + return ok +} + +func (i *tree[T]) Value() T { + return i.current +} + +func (i *tree[_]) Release() { + i.releaseOnce.Do(func() { + close(i.release) + }) + i.wg.Wait() +} diff --git a/vms/platformvm/state/tree_iterator_test.go b/utils/iterator/tree_test.go similarity index 68% rename from vms/platformvm/state/tree_iterator_test.go rename to utils/iterator/tree_test.go index ddb0e4e8b08d..126fab368256 100644 --- a/vms/platformvm/state/tree_iterator_test.go +++ b/utils/iterator/tree_test.go @@ -1,7 +1,7 @@ // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. // See the file LICENSE for licensing terms. -package state +package iterator_test import ( "testing" @@ -11,11 +11,15 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/iterator" + "github.com/ava-labs/avalanchego/vms/platformvm/state" ) -func TestTreeIterator(t *testing.T) { +var defaultTreeDegree = 2 + +func TestTree(t *testing.T) { require := require.New(t) - stakers := []*Staker{ + stakers := []*state.Staker{ { TxID: ids.GenerateTestID(), NextTime: time.Unix(0, 0), @@ -30,12 +34,12 @@ func TestTreeIterator(t *testing.T) { }, } - tree := btree.NewG(defaultTreeDegree, (*Staker).Less) + tree := btree.NewG(defaultTreeDegree, (*state.Staker).Less) for _, staker := range stakers { require.Nil(tree.ReplaceOrInsert(staker)) } - it := NewTreeIterator(tree) + it := iterator.FromTree(tree) for _, staker := range stakers { require.True(it.Next()) require.Equal(staker, it.Value()) @@ -44,15 +48,15 @@ func TestTreeIterator(t *testing.T) { it.Release() } -func TestTreeIteratorNil(t *testing.T) { - it := NewTreeIterator(nil) +func TestTreeNil(t *testing.T) { + it := iterator.FromTree[*state.Staker](nil) require.False(t, it.Next()) it.Release() } -func TestTreeIteratorEarlyRelease(t *testing.T) { +func TestTreeEarlyRelease(t *testing.T) { require := require.New(t) - stakers := []*Staker{ + stakers := []*state.Staker{ { TxID: ids.GenerateTestID(), NextTime: time.Unix(0, 0), @@ -67,12 +71,12 @@ func TestTreeIteratorEarlyRelease(t *testing.T) { }, } - tree := btree.NewG(defaultTreeDegree, (*Staker).Less) + tree := btree.NewG(defaultTreeDegree, (*state.Staker).Less) for _, staker := range stakers { require.Nil(tree.ReplaceOrInsert(staker)) } - it := NewTreeIterator(tree) + it := iterator.FromTree(tree) require.True(it.Next()) it.Release() require.False(it.Next()) diff --git a/vms/platformvm/block/builder/builder_test.go b/vms/platformvm/block/builder/builder_test.go index df5def70a850..7c8213124d50 100644 --- a/vms/platformvm/block/builder/builder_test.go +++ b/vms/platformvm/block/builder/builder_test.go @@ -17,13 +17,13 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/iterator/iteratormock" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" @@ -496,7 +496,7 @@ func TestGetNextStakerToReward(t *testing.T) { name: "end of time", timestamp: mockable.MaxTime, stateF: func(ctrl *gomock.Controller) state.Chain { - return statemock.NewChain(ctrl) + return state.NewMockChain(ctrl) }, expectedErr: ErrEndOfTime, }, @@ -504,11 +504,11 @@ func TestGetNextStakerToReward(t *testing.T) { name: "no stakers", timestamp: now, stateF: func(ctrl *gomock.Controller) state.Chain { - currentStakerIter := state.NewMockStakerIterator(ctrl) + currentStakerIter := iteratormock.NewIterator[*state.Staker](ctrl) currentStakerIter.EXPECT().Next().Return(false) currentStakerIter.EXPECT().Release() - s := statemock.NewChain(ctrl) + s := state.NewMockChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -518,7 +518,7 @@ func TestGetNextStakerToReward(t *testing.T) { name: "expired subnet validator/delegator", timestamp: now, stateF: func(ctrl *gomock.Controller) state.Chain { - currentStakerIter := state.NewMockStakerIterator(ctrl) + currentStakerIter := iteratormock.NewIterator[*state.Staker](ctrl) currentStakerIter.EXPECT().Next().Return(true) currentStakerIter.EXPECT().Value().Return(&state.Staker{ @@ -533,7 +533,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := statemock.NewChain(ctrl) + s := state.NewMockChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -545,7 +545,7 @@ func TestGetNextStakerToReward(t *testing.T) { name: "expired primary network validator after subnet expired subnet validator", timestamp: now, stateF: func(ctrl *gomock.Controller) state.Chain { - currentStakerIter := state.NewMockStakerIterator(ctrl) + currentStakerIter := iteratormock.NewIterator[*state.Staker](ctrl) currentStakerIter.EXPECT().Next().Return(true) currentStakerIter.EXPECT().Value().Return(&state.Staker{ @@ -560,7 +560,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := statemock.NewChain(ctrl) + s := state.NewMockChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -572,7 +572,7 @@ func TestGetNextStakerToReward(t *testing.T) { name: "expired primary network delegator after subnet expired subnet validator", timestamp: now, stateF: func(ctrl *gomock.Controller) state.Chain { - currentStakerIter := state.NewMockStakerIterator(ctrl) + currentStakerIter := iteratormock.NewIterator[*state.Staker](ctrl) currentStakerIter.EXPECT().Next().Return(true) currentStakerIter.EXPECT().Value().Return(&state.Staker{ @@ -587,7 +587,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := statemock.NewChain(ctrl) + s := state.NewMockChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -599,7 +599,7 @@ func TestGetNextStakerToReward(t *testing.T) { name: "non-expired primary network delegator", timestamp: now, stateF: func(ctrl *gomock.Controller) state.Chain { - currentStakerIter := state.NewMockStakerIterator(ctrl) + currentStakerIter := iteratormock.NewIterator[*state.Staker](ctrl) currentStakerIter.EXPECT().Next().Return(true) currentStakerIter.EXPECT().Value().Return(&state.Staker{ @@ -609,7 +609,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := statemock.NewChain(ctrl) + s := state.NewMockChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s @@ -621,7 +621,7 @@ func TestGetNextStakerToReward(t *testing.T) { name: "non-expired primary network validator", timestamp: now, stateF: func(ctrl *gomock.Controller) state.Chain { - currentStakerIter := state.NewMockStakerIterator(ctrl) + currentStakerIter := iteratormock.NewIterator[*state.Staker](ctrl) currentStakerIter.EXPECT().Next().Return(true) currentStakerIter.EXPECT().Value().Return(&state.Staker{ @@ -631,7 +631,7 @@ func TestGetNextStakerToReward(t *testing.T) { }) currentStakerIter.EXPECT().Release() - s := statemock.NewChain(ctrl) + s := state.NewMockChain(ctrl) s.EXPECT().GetCurrentStakerIterator().Return(currentStakerIter, nil) return s diff --git a/vms/platformvm/block/executor/acceptor_test.go b/vms/platformvm/block/executor/acceptor_test.go index 68a25295fb63..6f23961b7452 100644 --- a/vms/platformvm/block/executor/acceptor_test.go +++ b/vms/platformvm/block/executor/acceptor_test.go @@ -22,7 +22,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/validators" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -124,7 +123,7 @@ func TestAcceptorVisitAtomicBlock(t *testing.T) { require.ErrorIs(err, errMissingBlockState) // Set [blk]'s state in the map as though it had been verified. - onAcceptState := statemock.NewDiff(ctrl) + onAcceptState := state.NewMockDiff(ctrl) childID := ids.GenerateTestID() atomicRequests := make(map[ids.ID]*atomic.Requests) acceptor.backend.blkIDToState[blk.ID()] = &blockState{ @@ -132,9 +131,9 @@ func TestAcceptorVisitAtomicBlock(t *testing.T) { atomicRequests: atomicRequests, } // Give [blk] a child. - childOnAcceptState := statemock.NewDiff(ctrl) - childOnAbortState := statemock.NewDiff(ctrl) - childOnCommitState := statemock.NewDiff(ctrl) + childOnAcceptState := state.NewMockDiff(ctrl) + childOnAbortState := state.NewMockDiff(ctrl) + childOnCommitState := state.NewMockDiff(ctrl) childState := &blockState{ onAcceptState: childOnAcceptState, proposalBlockState: proposalBlockState{ @@ -207,7 +206,7 @@ func TestAcceptorVisitStandardBlock(t *testing.T) { require.ErrorIs(err, errMissingBlockState) // Set [blk]'s state in the map as though it had been verified. - onAcceptState := statemock.NewDiff(ctrl) + onAcceptState := state.NewMockDiff(ctrl) childID := ids.GenerateTestID() atomicRequests := make(map[ids.ID]*atomic.Requests) calledOnAcceptFunc := false @@ -220,9 +219,9 @@ func TestAcceptorVisitStandardBlock(t *testing.T) { atomicRequests: atomicRequests, } // Give [blk] a child. - childOnAcceptState := statemock.NewDiff(ctrl) - childOnAbortState := statemock.NewDiff(ctrl) - childOnCommitState := statemock.NewDiff(ctrl) + childOnAcceptState := state.NewMockDiff(ctrl) + childOnAbortState := state.NewMockDiff(ctrl) + childOnCommitState := state.NewMockDiff(ctrl) childState := &blockState{ onAcceptState: childOnAcceptState, proposalBlockState: proposalBlockState{ @@ -278,9 +277,9 @@ func TestAcceptorVisitCommitBlock(t *testing.T) { require.ErrorIs(err, state.ErrMissingParentState) // Set [blk]'s parent in the state map. - parentOnAcceptState := statemock.NewDiff(ctrl) - parentOnAbortState := statemock.NewDiff(ctrl) - parentOnCommitState := statemock.NewDiff(ctrl) + parentOnAcceptState := state.NewMockDiff(ctrl) + parentOnAbortState := state.NewMockDiff(ctrl) + parentOnCommitState := state.NewMockDiff(ctrl) parentStatelessBlk := block.NewMockBlock(ctrl) calledOnAcceptFunc := false atomicRequests := make(map[ids.ID]*atomic.Requests) @@ -388,9 +387,9 @@ func TestAcceptorVisitAbortBlock(t *testing.T) { require.ErrorIs(err, state.ErrMissingParentState) // Set [blk]'s parent in the state map. - parentOnAcceptState := statemock.NewDiff(ctrl) - parentOnAbortState := statemock.NewDiff(ctrl) - parentOnCommitState := statemock.NewDiff(ctrl) + parentOnAcceptState := state.NewMockDiff(ctrl) + parentOnAbortState := state.NewMockDiff(ctrl) + parentOnCommitState := state.NewMockDiff(ctrl) parentStatelessBlk := block.NewMockBlock(ctrl) calledOnAcceptFunc := false atomicRequests := make(map[ids.ID]*atomic.Requests) diff --git a/vms/platformvm/block/executor/backend_test.go b/vms/platformvm/block/executor/backend_test.go index 543da45179d2..a37823da7507 100644 --- a/vms/platformvm/block/executor/backend_test.go +++ b/vms/platformvm/block/executor/backend_test.go @@ -14,7 +14,6 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" ) func TestGetState(t *testing.T) { @@ -23,7 +22,7 @@ func TestGetState(t *testing.T) { var ( mockState = state.NewMockState(ctrl) - onAcceptState = statemock.NewDiff(ctrl) + onAcceptState = state.NewMockDiff(ctrl) blkID1 = ids.GenerateTestID() blkID2 = ids.GenerateTestID() b = &backend{ diff --git a/vms/platformvm/block/executor/proposal_block_test.go b/vms/platformvm/block/executor/proposal_block_test.go index 124049a26d5c..db7d5b44c532 100644 --- a/vms/platformvm/block/executor/proposal_block_test.go +++ b/vms/platformvm/block/executor/proposal_block_test.go @@ -20,13 +20,13 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" + "github.com/ava-labs/avalanchego/utils/iterator/iteratormock" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" @@ -54,7 +54,7 @@ func TestApricotProposalBlockTimeVerification(t *testing.T) { parentID := apricotParentBlk.ID() // store parent block, with relevant quantities - onParentAccept := statemock.NewDiff(ctrl) + onParentAccept := state.NewMockDiff(ctrl) env.blkManager.(*manager).blkIDToState[parentID] = &blockState{ statelessBlock: apricotParentBlk, onAcceptState: onParentAccept, @@ -91,7 +91,7 @@ func TestApricotProposalBlockTimeVerification(t *testing.T) { onParentAccept.EXPECT().GetTimestamp().Return(chainTime).AnyTimes() onParentAccept.EXPECT().GetFeeState().Return(gas.State{}).AnyTimes() - currentStakersIt := state.NewMockStakerIterator(ctrl) + currentStakersIt := iteratormock.NewIterator[*state.Staker](ctrl) currentStakersIt.EXPECT().Next().Return(true) currentStakersIt.EXPECT().Value().Return(&state.Staker{ TxID: addValTx.ID(), @@ -158,7 +158,7 @@ func TestBanffProposalBlockTimeVerification(t *testing.T) { // store parent block, with relevant quantities chainTime := parentTime - onParentAccept := statemock.NewDiff(ctrl) + onParentAccept := state.NewMockDiff(ctrl) onParentAccept.EXPECT().GetTimestamp().Return(parentTime).AnyTimes() onParentAccept.EXPECT().GetFeeState().Return(gas.State{}).AnyTimes() onParentAccept.EXPECT().GetCurrentSupply(constants.PrimaryNetworkID).Return(uint64(1000), nil).AnyTimes() @@ -202,7 +202,7 @@ func TestBanffProposalBlockTimeVerification(t *testing.T) { nextStakerTxID := nextStakerTx.ID() onParentAccept.EXPECT().GetTx(nextStakerTxID).Return(nextStakerTx, status.Processing, nil) - currentStakersIt := state.NewMockStakerIterator(ctrl) + currentStakersIt := iteratormock.NewIterator[*state.Staker](ctrl) currentStakersIt.EXPECT().Next().Return(true).AnyTimes() currentStakersIt.EXPECT().Value().Return(&state.Staker{ TxID: nextStakerTxID, @@ -215,7 +215,7 @@ func TestBanffProposalBlockTimeVerification(t *testing.T) { onParentAccept.EXPECT().GetDelegateeReward(constants.PrimaryNetworkID, unsignedNextStakerTx.NodeID()).Return(uint64(0), nil).AnyTimes() - pendingStakersIt := state.NewMockStakerIterator(ctrl) + pendingStakersIt := iteratormock.NewIterator[*state.Staker](ctrl) pendingStakersIt.EXPECT().Next().Return(false).AnyTimes() // no pending stakers pendingStakersIt.EXPECT().Release().AnyTimes() onParentAccept.EXPECT().GetPendingStakerIterator().Return(pendingStakersIt, nil).AnyTimes() diff --git a/vms/platformvm/block/executor/standard_block_test.go b/vms/platformvm/block/executor/standard_block_test.go index a84b7efc246d..e0154b8c9ef0 100644 --- a/vms/platformvm/block/executor/standard_block_test.go +++ b/vms/platformvm/block/executor/standard_block_test.go @@ -17,11 +17,11 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" + "github.com/ava-labs/avalanchego/utils/iterator/iteratormock" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" @@ -49,7 +49,7 @@ func TestApricotStandardBlockTimeVerification(t *testing.T) { parentID := apricotParentBlk.ID() // store parent block, with relevant quantities - onParentAccept := statemock.NewDiff(ctrl) + onParentAccept := state.NewMockDiff(ctrl) env.blkManager.(*manager).blkIDToState[parentID] = &blockState{ statelessBlock: apricotParentBlk, onAcceptState: onParentAccept, @@ -105,7 +105,7 @@ func TestBanffStandardBlockTimeVerification(t *testing.T) { parentID := banffParentBlk.ID() // store parent block, with relevant quantities - onParentAccept := statemock.NewDiff(ctrl) + onParentAccept := state.NewMockDiff(ctrl) chainTime := env.clk.Time().Truncate(time.Second) env.blkManager.(*manager).blkIDToState[parentID] = &blockState{ statelessBlock: banffParentBlk, @@ -117,7 +117,7 @@ func TestBanffStandardBlockTimeVerification(t *testing.T) { nextStakerTime := chainTime.Add(executor.SyncBound).Add(-1 * time.Second) // store just once current staker to mark next staker time. - currentStakerIt := state.NewMockStakerIterator(ctrl) + currentStakerIt := iteratormock.NewIterator[*state.Staker](ctrl) currentStakerIt.EXPECT().Next().Return(true).AnyTimes() currentStakerIt.EXPECT().Value().Return( &state.Staker{ @@ -129,7 +129,7 @@ func TestBanffStandardBlockTimeVerification(t *testing.T) { onParentAccept.EXPECT().GetCurrentStakerIterator().Return(currentStakerIt, nil).AnyTimes() // no pending stakers - pendingIt := state.NewMockStakerIterator(ctrl) + pendingIt := iteratormock.NewIterator[*state.Staker](ctrl) pendingIt.EXPECT().Next().Return(false).AnyTimes() pendingIt.EXPECT().Release().Return().AnyTimes() onParentAccept.EXPECT().GetPendingStakerIterator().Return(pendingIt, nil).AnyTimes() diff --git a/vms/platformvm/block/executor/verifier_test.go b/vms/platformvm/block/executor/verifier_test.go index e8f9f478c29a..73bef61aa9f7 100644 --- a/vms/platformvm/block/executor/verifier_test.go +++ b/vms/platformvm/block/executor/verifier_test.go @@ -24,7 +24,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" @@ -40,7 +39,7 @@ func TestVerifierVisitProposalBlock(t *testing.T) { mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentOnAcceptState := statemock.NewDiff(ctrl) + parentOnAcceptState := state.NewMockDiff(ctrl) timestamp := time.Now() // One call for each of onCommitState and onAbortState. parentOnAcceptState.EXPECT().GetTimestamp().Return(timestamp).Times(2) @@ -125,7 +124,7 @@ func TestVerifierVisitAtomicBlock(t *testing.T) { parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) grandparentID := ids.GenerateTestID() - parentState := statemock.NewDiff(ctrl) + parentState := state.NewMockDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -150,7 +149,7 @@ func TestVerifierVisitAtomicBlock(t *testing.T) { backend: backend, } - onAccept := statemock.NewDiff(ctrl) + onAccept := state.NewMockDiff(ctrl) blkTx := txsmock.NewUnsignedTx(ctrl) inputs := set.Of(ids.GenerateTestID()) blkTx.EXPECT().Visit(gomock.AssignableToTypeOf(&executor.AtomicTxExecutor{})).DoAndReturn( @@ -207,7 +206,7 @@ func TestVerifierVisitStandardBlock(t *testing.T) { mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentState := statemock.NewDiff(ctrl) + parentState := state.NewMockDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -302,9 +301,9 @@ func TestVerifierVisitCommitBlock(t *testing.T) { mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentOnDecisionState := statemock.NewDiff(ctrl) - parentOnCommitState := statemock.NewDiff(ctrl) - parentOnAbortState := statemock.NewDiff(ctrl) + parentOnDecisionState := state.NewMockDiff(ctrl) + parentOnCommitState := state.NewMockDiff(ctrl) + parentOnAbortState := state.NewMockDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -369,9 +368,9 @@ func TestVerifierVisitAbortBlock(t *testing.T) { mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentOnDecisionState := statemock.NewDiff(ctrl) - parentOnCommitState := statemock.NewDiff(ctrl) - parentOnAbortState := statemock.NewDiff(ctrl) + parentOnDecisionState := state.NewMockDiff(ctrl) + parentOnCommitState := state.NewMockDiff(ctrl) + parentOnAbortState := state.NewMockDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -670,10 +669,10 @@ func TestVerifierVisitStandardBlockWithDuplicateInputs(t *testing.T) { grandParentID := ids.GenerateTestID() grandParentStatelessBlk := block.NewMockBlock(ctrl) - grandParentState := statemock.NewDiff(ctrl) + grandParentState := state.NewMockDiff(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentState := statemock.NewDiff(ctrl) + parentState := state.NewMockDiff(ctrl) atomicInputs := set.Of(ids.GenerateTestID()) backend := &backend{ @@ -764,8 +763,8 @@ func TestVerifierVisitApricotStandardBlockWithProposalBlockParent(t *testing.T) mempool := mempoolmock.NewMempool(ctrl) parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) - parentOnCommitState := statemock.NewDiff(ctrl) - parentOnAbortState := statemock.NewDiff(ctrl) + parentOnCommitState := state.NewMockDiff(ctrl) + parentOnAbortState := state.NewMockDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ @@ -821,8 +820,8 @@ func TestVerifierVisitBanffStandardBlockWithProposalBlockParent(t *testing.T) { parentID := ids.GenerateTestID() parentStatelessBlk := block.NewMockBlock(ctrl) parentTime := time.Now() - parentOnCommitState := statemock.NewDiff(ctrl) - parentOnAbortState := statemock.NewDiff(ctrl) + parentOnCommitState := state.NewMockDiff(ctrl) + parentOnAbortState := state.NewMockDiff(ctrl) backend := &backend{ blkIDToState: map[ids.ID]*blockState{ diff --git a/vms/platformvm/state/diff.go b/vms/platformvm/state/diff.go index 8c530c75f045..66477823673a 100644 --- a/vms/platformvm/state/diff.go +++ b/vms/platformvm/state/diff.go @@ -10,6 +10,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/iterator" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/fx" @@ -187,7 +188,7 @@ func (d *diff) DeleteCurrentValidator(staker *Staker) { d.currentStakerDiffs.DeleteValidator(staker) } -func (d *diff) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) { +func (d *diff) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { parentState, ok := d.stateVersions.GetState(d.parentID) if !ok { return nil, fmt.Errorf("%w: %s", ErrMissingParentState, d.parentID) @@ -209,7 +210,7 @@ func (d *diff) DeleteCurrentDelegator(staker *Staker) { d.currentStakerDiffs.DeleteDelegator(staker) } -func (d *diff) GetCurrentStakerIterator() (StakerIterator, error) { +func (d *diff) GetCurrentStakerIterator() (iterator.Iterator[*Staker], error) { parentState, ok := d.stateVersions.GetState(d.parentID) if !ok { return nil, fmt.Errorf("%w: %s", ErrMissingParentState, d.parentID) @@ -250,7 +251,7 @@ func (d *diff) DeletePendingValidator(staker *Staker) { d.pendingStakerDiffs.DeleteValidator(staker) } -func (d *diff) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) { +func (d *diff) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { parentState, ok := d.stateVersions.GetState(d.parentID) if !ok { return nil, fmt.Errorf("%w: %s", ErrMissingParentState, d.parentID) @@ -272,7 +273,7 @@ func (d *diff) DeletePendingDelegator(staker *Staker) { d.pendingStakerDiffs.DeleteDelegator(staker) } -func (d *diff) GetPendingStakerIterator() (StakerIterator, error) { +func (d *diff) GetPendingStakerIterator() (iterator.Iterator[*Staker], error) { parentState, ok := d.stateVersions.GetState(d.parentID) if !ok { return nil, fmt.Errorf("%w: %s", ErrMissingParentState, d.parentID) @@ -448,7 +449,7 @@ func (d *diff) Apply(baseState Chain) error { baseState.DeleteCurrentValidator(validatorDiff.validator) } - addedDelegatorIterator := NewTreeIterator(validatorDiff.addedDelegators) + addedDelegatorIterator := iterator.FromTree(validatorDiff.addedDelegators) for addedDelegatorIterator.Next() { baseState.PutCurrentDelegator(addedDelegatorIterator.Value()) } @@ -475,7 +476,7 @@ func (d *diff) Apply(baseState Chain) error { baseState.DeletePendingValidator(validatorDiff.validator) } - addedDelegatorIterator := NewTreeIterator(validatorDiff.addedDelegators) + addedDelegatorIterator := iterator.FromTree(validatorDiff.addedDelegators) for addedDelegatorIterator.Next() { baseState.PutPendingDelegator(addedDelegatorIterator.Value()) } diff --git a/vms/platformvm/state/diff_test.go b/vms/platformvm/state/diff_test.go index cf3b2793ad8d..82525e087593 100644 --- a/vms/platformvm/state/diff_test.go +++ b/vms/platformvm/state/diff_test.go @@ -15,6 +15,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/utils/iterator/iteratormock" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/fx/fxmock" @@ -183,7 +184,7 @@ func TestDiffCurrentDelegator(t *testing.T) { // Assert that we get the current delegator back // Mock iterator for [state] returns no delegators. - stateCurrentDelegatorIter := NewMockStakerIterator(ctrl) + stateCurrentDelegatorIter := iteratormock.NewIterator[*Staker](ctrl) stateCurrentDelegatorIter.EXPECT().Next().Return(false).Times(2) stateCurrentDelegatorIter.EXPECT().Release().Times(2) state.EXPECT().GetCurrentDelegatorIterator( @@ -229,7 +230,7 @@ func TestDiffPendingDelegator(t *testing.T) { // Assert that we get the pending delegator back // Mock iterator for [state] returns no delegators. - statePendingDelegatorIter := NewMockStakerIterator(ctrl) + statePendingDelegatorIter := iteratormock.NewIterator[*Staker](ctrl) statePendingDelegatorIter.EXPECT().Next().Return(false).Times(2) statePendingDelegatorIter.EXPECT().Release().Times(2) state.EXPECT().GetPendingDelegatorIterator( diff --git a/vms/platformvm/state/empty_iterator.go b/vms/platformvm/state/empty_iterator.go deleted file mode 100644 index 3ec5f04f82a9..000000000000 --- a/vms/platformvm/state/empty_iterator.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package state - -// EmptyIterator contains no stakers. -var EmptyIterator StakerIterator = emptyIterator{} - -type emptyIterator struct{} - -func (emptyIterator) Next() bool { - return false -} - -func (emptyIterator) Value() *Staker { - return nil -} - -func (emptyIterator) Release() {} diff --git a/vms/platformvm/state/empty_iterator_test.go b/vms/platformvm/state/empty_iterator_test.go deleted file mode 100644 index 19cd4f06dc06..000000000000 --- a/vms/platformvm/state/empty_iterator_test.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package state - -import ( - "testing" - - "github.com/stretchr/testify/require" -) - -func TestEmptyIterator(t *testing.T) { - require := require.New(t) - require.False(EmptyIterator.Next()) - - EmptyIterator.Release() - - require.False(EmptyIterator.Next()) - require.Nil(EmptyIterator.Value()) -} diff --git a/vms/platformvm/state/masked_iterator.go b/vms/platformvm/state/masked_iterator.go deleted file mode 100644 index 9ceee9712b40..000000000000 --- a/vms/platformvm/state/masked_iterator.go +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package state - -import "github.com/ava-labs/avalanchego/ids" - -var _ StakerIterator = (*maskedIterator)(nil) - -type maskedIterator struct { - parentIterator StakerIterator - maskedStakers map[ids.ID]*Staker -} - -// NewMaskedIterator returns a new iterator that skips the stakers in -// [parentIterator] that are present in [maskedStakers]. -func NewMaskedIterator(parentIterator StakerIterator, maskedStakers map[ids.ID]*Staker) StakerIterator { - return &maskedIterator{ - parentIterator: parentIterator, - maskedStakers: maskedStakers, - } -} - -func (i *maskedIterator) Next() bool { - for i.parentIterator.Next() { - staker := i.parentIterator.Value() - if _, ok := i.maskedStakers[staker.TxID]; !ok { - return true - } - } - return false -} - -func (i *maskedIterator) Value() *Staker { - return i.parentIterator.Value() -} - -func (i *maskedIterator) Release() { - i.parentIterator.Release() -} diff --git a/vms/platformvm/state/mock_chain.go b/vms/platformvm/state/mock_chain.go new file mode 100644 index 000000000000..13adc2d2cc86 --- /dev/null +++ b/vms/platformvm/state/mock_chain.go @@ -0,0 +1,526 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: vms/platformvm/state/state.go +// +// Generated by this command: +// +// mockgen -source=vms/platformvm/state/state.go -destination=vms/platformvm/state/mock_chain.go -package=state -exclude_interfaces=State -mock_names=MockChain=MockChain +// + +// Package state is a generated GoMock package. +package state + +import ( + reflect "reflect" + time "time" + + ids "github.com/ava-labs/avalanchego/ids" + iterator "github.com/ava-labs/avalanchego/utils/iterator" + avax "github.com/ava-labs/avalanchego/vms/components/avax" + gas "github.com/ava-labs/avalanchego/vms/components/gas" + fx "github.com/ava-labs/avalanchego/vms/platformvm/fx" + status "github.com/ava-labs/avalanchego/vms/platformvm/status" + txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" + gomock "go.uber.org/mock/gomock" +) + +// MockChain is a mock of Chain interface. +type MockChain struct { + ctrl *gomock.Controller + recorder *MockChainMockRecorder +} + +// MockChainMockRecorder is the mock recorder for MockChain. +type MockChainMockRecorder struct { + mock *MockChain +} + +// NewMockChain creates a new mock instance. +func NewMockChain(ctrl *gomock.Controller) *MockChain { + mock := &MockChain{ctrl: ctrl} + mock.recorder = &MockChainMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockChain) EXPECT() *MockChainMockRecorder { + return m.recorder +} + +// AddChain mocks base method. +func (m *MockChain) AddChain(createChainTx *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddChain", createChainTx) +} + +// AddChain indicates an expected call of AddChain. +func (mr *MockChainMockRecorder) AddChain(createChainTx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*MockChain)(nil).AddChain), createChainTx) +} + +// AddRewardUTXO mocks base method. +func (m *MockChain) AddRewardUTXO(txID ids.ID, utxo *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddRewardUTXO", txID, utxo) +} + +// AddRewardUTXO indicates an expected call of AddRewardUTXO. +func (mr *MockChainMockRecorder) AddRewardUTXO(txID, utxo any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*MockChain)(nil).AddRewardUTXO), txID, utxo) +} + +// AddSubnet mocks base method. +func (m *MockChain) AddSubnet(subnetID ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddSubnet", subnetID) +} + +// AddSubnet indicates an expected call of AddSubnet. +func (mr *MockChainMockRecorder) AddSubnet(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*MockChain)(nil).AddSubnet), subnetID) +} + +// AddSubnetTransformation mocks base method. +func (m *MockChain) AddSubnetTransformation(transformSubnetTx *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddSubnetTransformation", transformSubnetTx) +} + +// AddSubnetTransformation indicates an expected call of AddSubnetTransformation. +func (mr *MockChainMockRecorder) AddSubnetTransformation(transformSubnetTx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*MockChain)(nil).AddSubnetTransformation), transformSubnetTx) +} + +// AddTx mocks base method. +func (m *MockChain) AddTx(tx *txs.Tx, status status.Status) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddTx", tx, status) +} + +// AddTx indicates an expected call of AddTx. +func (mr *MockChainMockRecorder) AddTx(tx, status any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockChain)(nil).AddTx), tx, status) +} + +// AddUTXO mocks base method. +func (m *MockChain) AddUTXO(utxo *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddUTXO", utxo) +} + +// AddUTXO indicates an expected call of AddUTXO. +func (mr *MockChainMockRecorder) AddUTXO(utxo any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockChain)(nil).AddUTXO), utxo) +} + +// DeleteCurrentDelegator mocks base method. +func (m *MockChain) DeleteCurrentDelegator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteCurrentDelegator", staker) +} + +// DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. +func (mr *MockChainMockRecorder) DeleteCurrentDelegator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*MockChain)(nil).DeleteCurrentDelegator), staker) +} + +// DeleteCurrentValidator mocks base method. +func (m *MockChain) DeleteCurrentValidator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteCurrentValidator", staker) +} + +// DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. +func (mr *MockChainMockRecorder) DeleteCurrentValidator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*MockChain)(nil).DeleteCurrentValidator), staker) +} + +// DeletePendingDelegator mocks base method. +func (m *MockChain) DeletePendingDelegator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeletePendingDelegator", staker) +} + +// DeletePendingDelegator indicates an expected call of DeletePendingDelegator. +func (mr *MockChainMockRecorder) DeletePendingDelegator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*MockChain)(nil).DeletePendingDelegator), staker) +} + +// DeletePendingValidator mocks base method. +func (m *MockChain) DeletePendingValidator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeletePendingValidator", staker) +} + +// DeletePendingValidator indicates an expected call of DeletePendingValidator. +func (mr *MockChainMockRecorder) DeletePendingValidator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*MockChain)(nil).DeletePendingValidator), staker) +} + +// DeleteUTXO mocks base method. +func (m *MockChain) DeleteUTXO(utxoID ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteUTXO", utxoID) +} + +// DeleteUTXO indicates an expected call of DeleteUTXO. +func (mr *MockChainMockRecorder) DeleteUTXO(utxoID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockChain)(nil).DeleteUTXO), utxoID) +} + +// GetCurrentDelegatorIterator mocks base method. +func (m *MockChain) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", subnetID, nodeID) + ret0, _ := ret[0].(iterator.Iterator[*Staker]) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. +func (mr *MockChainMockRecorder) GetCurrentDelegatorIterator(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*MockChain)(nil).GetCurrentDelegatorIterator), subnetID, nodeID) +} + +// GetCurrentStakerIterator mocks base method. +func (m *MockChain) GetCurrentStakerIterator() (iterator.Iterator[*Staker], error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentStakerIterator") + ret0, _ := ret[0].(iterator.Iterator[*Staker]) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentStakerIterator indicates an expected call of GetCurrentStakerIterator. +func (mr *MockChainMockRecorder) GetCurrentStakerIterator() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentStakerIterator", reflect.TypeOf((*MockChain)(nil).GetCurrentStakerIterator)) +} + +// GetCurrentSupply mocks base method. +func (m *MockChain) GetCurrentSupply(subnetID ids.ID) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentSupply", subnetID) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentSupply indicates an expected call of GetCurrentSupply. +func (mr *MockChainMockRecorder) GetCurrentSupply(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*MockChain)(nil).GetCurrentSupply), subnetID) +} + +// GetCurrentValidator mocks base method. +func (m *MockChain) GetCurrentValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentValidator", subnetID, nodeID) + ret0, _ := ret[0].(*Staker) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentValidator indicates an expected call of GetCurrentValidator. +func (mr *MockChainMockRecorder) GetCurrentValidator(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*MockChain)(nil).GetCurrentValidator), subnetID, nodeID) +} + +// GetDelegateeReward mocks base method. +func (m *MockChain) GetDelegateeReward(subnetID ids.ID, nodeID ids.NodeID) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetDelegateeReward", subnetID, nodeID) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetDelegateeReward indicates an expected call of GetDelegateeReward. +func (mr *MockChainMockRecorder) GetDelegateeReward(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*MockChain)(nil).GetDelegateeReward), subnetID, nodeID) +} + +// GetFeeState mocks base method. +func (m *MockChain) GetFeeState() gas.State { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetFeeState") + ret0, _ := ret[0].(gas.State) + return ret0 +} + +// GetFeeState indicates an expected call of GetFeeState. +func (mr *MockChainMockRecorder) GetFeeState() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeeState", reflect.TypeOf((*MockChain)(nil).GetFeeState)) +} + +// GetPendingDelegatorIterator mocks base method. +func (m *MockChain) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", subnetID, nodeID) + ret0, _ := ret[0].(iterator.Iterator[*Staker]) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. +func (mr *MockChainMockRecorder) GetPendingDelegatorIterator(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*MockChain)(nil).GetPendingDelegatorIterator), subnetID, nodeID) +} + +// GetPendingStakerIterator mocks base method. +func (m *MockChain) GetPendingStakerIterator() (iterator.Iterator[*Staker], error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingStakerIterator") + ret0, _ := ret[0].(iterator.Iterator[*Staker]) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingStakerIterator indicates an expected call of GetPendingStakerIterator. +func (mr *MockChainMockRecorder) GetPendingStakerIterator() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingStakerIterator", reflect.TypeOf((*MockChain)(nil).GetPendingStakerIterator)) +} + +// GetPendingValidator mocks base method. +func (m *MockChain) GetPendingValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingValidator", subnetID, nodeID) + ret0, _ := ret[0].(*Staker) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingValidator indicates an expected call of GetPendingValidator. +func (mr *MockChainMockRecorder) GetPendingValidator(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*MockChain)(nil).GetPendingValidator), subnetID, nodeID) +} + +// GetSubnetManager mocks base method. +func (m *MockChain) GetSubnetManager(subnetID ids.ID) (ids.ID, []byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetManager", subnetID) + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].([]byte) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetSubnetManager indicates an expected call of GetSubnetManager. +func (mr *MockChainMockRecorder) GetSubnetManager(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*MockChain)(nil).GetSubnetManager), subnetID) +} + +// GetSubnetOwner mocks base method. +func (m *MockChain) GetSubnetOwner(subnetID ids.ID) (fx.Owner, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetOwner", subnetID) + ret0, _ := ret[0].(fx.Owner) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSubnetOwner indicates an expected call of GetSubnetOwner. +func (mr *MockChainMockRecorder) GetSubnetOwner(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*MockChain)(nil).GetSubnetOwner), subnetID) +} + +// GetSubnetTransformation mocks base method. +func (m *MockChain) GetSubnetTransformation(subnetID ids.ID) (*txs.Tx, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetTransformation", subnetID) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSubnetTransformation indicates an expected call of GetSubnetTransformation. +func (mr *MockChainMockRecorder) GetSubnetTransformation(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*MockChain)(nil).GetSubnetTransformation), subnetID) +} + +// GetTimestamp mocks base method. +func (m *MockChain) GetTimestamp() time.Time { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTimestamp") + ret0, _ := ret[0].(time.Time) + return ret0 +} + +// GetTimestamp indicates an expected call of GetTimestamp. +func (mr *MockChainMockRecorder) GetTimestamp() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*MockChain)(nil).GetTimestamp)) +} + +// GetTx mocks base method. +func (m *MockChain) GetTx(txID ids.ID) (*txs.Tx, status.Status, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTx", txID) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(status.Status) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetTx indicates an expected call of GetTx. +func (mr *MockChainMockRecorder) GetTx(txID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockChain)(nil).GetTx), txID) +} + +// GetUTXO mocks base method. +func (m *MockChain) GetUTXO(utxoID ids.ID) (*avax.UTXO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUTXO", utxoID) + ret0, _ := ret[0].(*avax.UTXO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUTXO indicates an expected call of GetUTXO. +func (mr *MockChainMockRecorder) GetUTXO(utxoID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockChain)(nil).GetUTXO), utxoID) +} + +// PutCurrentDelegator mocks base method. +func (m *MockChain) PutCurrentDelegator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutCurrentDelegator", staker) +} + +// PutCurrentDelegator indicates an expected call of PutCurrentDelegator. +func (mr *MockChainMockRecorder) PutCurrentDelegator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*MockChain)(nil).PutCurrentDelegator), staker) +} + +// PutCurrentValidator mocks base method. +func (m *MockChain) PutCurrentValidator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutCurrentValidator", staker) +} + +// PutCurrentValidator indicates an expected call of PutCurrentValidator. +func (mr *MockChainMockRecorder) PutCurrentValidator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*MockChain)(nil).PutCurrentValidator), staker) +} + +// PutPendingDelegator mocks base method. +func (m *MockChain) PutPendingDelegator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutPendingDelegator", staker) +} + +// PutPendingDelegator indicates an expected call of PutPendingDelegator. +func (mr *MockChainMockRecorder) PutPendingDelegator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*MockChain)(nil).PutPendingDelegator), staker) +} + +// PutPendingValidator mocks base method. +func (m *MockChain) PutPendingValidator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutPendingValidator", staker) +} + +// PutPendingValidator indicates an expected call of PutPendingValidator. +func (mr *MockChainMockRecorder) PutPendingValidator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*MockChain)(nil).PutPendingValidator), staker) +} + +// SetCurrentSupply mocks base method. +func (m *MockChain) SetCurrentSupply(subnetID ids.ID, cs uint64) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetCurrentSupply", subnetID, cs) +} + +// SetCurrentSupply indicates an expected call of SetCurrentSupply. +func (mr *MockChainMockRecorder) SetCurrentSupply(subnetID, cs any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*MockChain)(nil).SetCurrentSupply), subnetID, cs) +} + +// SetDelegateeReward mocks base method. +func (m *MockChain) SetDelegateeReward(subnetID ids.ID, nodeID ids.NodeID, amount uint64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetDelegateeReward", subnetID, nodeID, amount) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetDelegateeReward indicates an expected call of SetDelegateeReward. +func (mr *MockChainMockRecorder) SetDelegateeReward(subnetID, nodeID, amount any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*MockChain)(nil).SetDelegateeReward), subnetID, nodeID, amount) +} + +// SetFeeState mocks base method. +func (m *MockChain) SetFeeState(f gas.State) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetFeeState", f) +} + +// SetFeeState indicates an expected call of SetFeeState. +func (mr *MockChainMockRecorder) SetFeeState(f any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*MockChain)(nil).SetFeeState), f) +} + +// SetSubnetManager mocks base method. +func (m *MockChain) SetSubnetManager(subnetID, chainID ids.ID, addr []byte) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetSubnetManager", subnetID, chainID, addr) +} + +// SetSubnetManager indicates an expected call of SetSubnetManager. +func (mr *MockChainMockRecorder) SetSubnetManager(subnetID, chainID, addr any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*MockChain)(nil).SetSubnetManager), subnetID, chainID, addr) +} + +// SetSubnetOwner mocks base method. +func (m *MockChain) SetSubnetOwner(subnetID ids.ID, owner fx.Owner) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetSubnetOwner", subnetID, owner) +} + +// SetSubnetOwner indicates an expected call of SetSubnetOwner. +func (mr *MockChainMockRecorder) SetSubnetOwner(subnetID, owner any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*MockChain)(nil).SetSubnetOwner), subnetID, owner) +} + +// SetTimestamp mocks base method. +func (m *MockChain) SetTimestamp(tm time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetTimestamp", tm) +} + +// SetTimestamp indicates an expected call of SetTimestamp. +func (mr *MockChainMockRecorder) SetTimestamp(tm any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockChain)(nil).SetTimestamp), tm) +} diff --git a/vms/platformvm/state/mock_diff.go b/vms/platformvm/state/mock_diff.go new file mode 100644 index 000000000000..8bfd09c44d9c --- /dev/null +++ b/vms/platformvm/state/mock_diff.go @@ -0,0 +1,540 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: vms/platformvm/state/diff.go +// +// Generated by this command: +// +// mockgen -source=vms/platformvm/state/diff.go -destination=vms/platformvm/state/mock_diff.go -package=state -exclude_interfaces= -mock_names=MockDiff=MockDiff +// + +// Package state is a generated GoMock package. +package state + +import ( + reflect "reflect" + time "time" + + ids "github.com/ava-labs/avalanchego/ids" + iterator "github.com/ava-labs/avalanchego/utils/iterator" + avax "github.com/ava-labs/avalanchego/vms/components/avax" + gas "github.com/ava-labs/avalanchego/vms/components/gas" + fx "github.com/ava-labs/avalanchego/vms/platformvm/fx" + status "github.com/ava-labs/avalanchego/vms/platformvm/status" + txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" + gomock "go.uber.org/mock/gomock" +) + +// MockDiff is a mock of Diff interface. +type MockDiff struct { + ctrl *gomock.Controller + recorder *MockDiffMockRecorder +} + +// MockDiffMockRecorder is the mock recorder for MockDiff. +type MockDiffMockRecorder struct { + mock *MockDiff +} + +// NewMockDiff creates a new mock instance. +func NewMockDiff(ctrl *gomock.Controller) *MockDiff { + mock := &MockDiff{ctrl: ctrl} + mock.recorder = &MockDiffMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockDiff) EXPECT() *MockDiffMockRecorder { + return m.recorder +} + +// AddChain mocks base method. +func (m *MockDiff) AddChain(createChainTx *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddChain", createChainTx) +} + +// AddChain indicates an expected call of AddChain. +func (mr *MockDiffMockRecorder) AddChain(createChainTx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*MockDiff)(nil).AddChain), createChainTx) +} + +// AddRewardUTXO mocks base method. +func (m *MockDiff) AddRewardUTXO(txID ids.ID, utxo *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddRewardUTXO", txID, utxo) +} + +// AddRewardUTXO indicates an expected call of AddRewardUTXO. +func (mr *MockDiffMockRecorder) AddRewardUTXO(txID, utxo any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*MockDiff)(nil).AddRewardUTXO), txID, utxo) +} + +// AddSubnet mocks base method. +func (m *MockDiff) AddSubnet(subnetID ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddSubnet", subnetID) +} + +// AddSubnet indicates an expected call of AddSubnet. +func (mr *MockDiffMockRecorder) AddSubnet(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*MockDiff)(nil).AddSubnet), subnetID) +} + +// AddSubnetTransformation mocks base method. +func (m *MockDiff) AddSubnetTransformation(transformSubnetTx *txs.Tx) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddSubnetTransformation", transformSubnetTx) +} + +// AddSubnetTransformation indicates an expected call of AddSubnetTransformation. +func (mr *MockDiffMockRecorder) AddSubnetTransformation(transformSubnetTx any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*MockDiff)(nil).AddSubnetTransformation), transformSubnetTx) +} + +// AddTx mocks base method. +func (m *MockDiff) AddTx(tx *txs.Tx, status status.Status) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddTx", tx, status) +} + +// AddTx indicates an expected call of AddTx. +func (mr *MockDiffMockRecorder) AddTx(tx, status any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*MockDiff)(nil).AddTx), tx, status) +} + +// AddUTXO mocks base method. +func (m *MockDiff) AddUTXO(utxo *avax.UTXO) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddUTXO", utxo) +} + +// AddUTXO indicates an expected call of AddUTXO. +func (mr *MockDiffMockRecorder) AddUTXO(utxo any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*MockDiff)(nil).AddUTXO), utxo) +} + +// Apply mocks base method. +func (m *MockDiff) Apply(arg0 Chain) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Apply", arg0) + ret0, _ := ret[0].(error) + return ret0 +} + +// Apply indicates an expected call of Apply. +func (mr *MockDiffMockRecorder) Apply(arg0 any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*MockDiff)(nil).Apply), arg0) +} + +// DeleteCurrentDelegator mocks base method. +func (m *MockDiff) DeleteCurrentDelegator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteCurrentDelegator", staker) +} + +// DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. +func (mr *MockDiffMockRecorder) DeleteCurrentDelegator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*MockDiff)(nil).DeleteCurrentDelegator), staker) +} + +// DeleteCurrentValidator mocks base method. +func (m *MockDiff) DeleteCurrentValidator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteCurrentValidator", staker) +} + +// DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. +func (mr *MockDiffMockRecorder) DeleteCurrentValidator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*MockDiff)(nil).DeleteCurrentValidator), staker) +} + +// DeletePendingDelegator mocks base method. +func (m *MockDiff) DeletePendingDelegator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeletePendingDelegator", staker) +} + +// DeletePendingDelegator indicates an expected call of DeletePendingDelegator. +func (mr *MockDiffMockRecorder) DeletePendingDelegator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*MockDiff)(nil).DeletePendingDelegator), staker) +} + +// DeletePendingValidator mocks base method. +func (m *MockDiff) DeletePendingValidator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeletePendingValidator", staker) +} + +// DeletePendingValidator indicates an expected call of DeletePendingValidator. +func (mr *MockDiffMockRecorder) DeletePendingValidator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*MockDiff)(nil).DeletePendingValidator), staker) +} + +// DeleteUTXO mocks base method. +func (m *MockDiff) DeleteUTXO(utxoID ids.ID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "DeleteUTXO", utxoID) +} + +// DeleteUTXO indicates an expected call of DeleteUTXO. +func (mr *MockDiffMockRecorder) DeleteUTXO(utxoID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*MockDiff)(nil).DeleteUTXO), utxoID) +} + +// GetCurrentDelegatorIterator mocks base method. +func (m *MockDiff) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", subnetID, nodeID) + ret0, _ := ret[0].(iterator.Iterator[*Staker]) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. +func (mr *MockDiffMockRecorder) GetCurrentDelegatorIterator(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*MockDiff)(nil).GetCurrentDelegatorIterator), subnetID, nodeID) +} + +// GetCurrentStakerIterator mocks base method. +func (m *MockDiff) GetCurrentStakerIterator() (iterator.Iterator[*Staker], error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentStakerIterator") + ret0, _ := ret[0].(iterator.Iterator[*Staker]) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentStakerIterator indicates an expected call of GetCurrentStakerIterator. +func (mr *MockDiffMockRecorder) GetCurrentStakerIterator() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentStakerIterator", reflect.TypeOf((*MockDiff)(nil).GetCurrentStakerIterator)) +} + +// GetCurrentSupply mocks base method. +func (m *MockDiff) GetCurrentSupply(subnetID ids.ID) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentSupply", subnetID) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentSupply indicates an expected call of GetCurrentSupply. +func (mr *MockDiffMockRecorder) GetCurrentSupply(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*MockDiff)(nil).GetCurrentSupply), subnetID) +} + +// GetCurrentValidator mocks base method. +func (m *MockDiff) GetCurrentValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetCurrentValidator", subnetID, nodeID) + ret0, _ := ret[0].(*Staker) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetCurrentValidator indicates an expected call of GetCurrentValidator. +func (mr *MockDiffMockRecorder) GetCurrentValidator(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*MockDiff)(nil).GetCurrentValidator), subnetID, nodeID) +} + +// GetDelegateeReward mocks base method. +func (m *MockDiff) GetDelegateeReward(subnetID ids.ID, nodeID ids.NodeID) (uint64, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetDelegateeReward", subnetID, nodeID) + ret0, _ := ret[0].(uint64) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetDelegateeReward indicates an expected call of GetDelegateeReward. +func (mr *MockDiffMockRecorder) GetDelegateeReward(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*MockDiff)(nil).GetDelegateeReward), subnetID, nodeID) +} + +// GetFeeState mocks base method. +func (m *MockDiff) GetFeeState() gas.State { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetFeeState") + ret0, _ := ret[0].(gas.State) + return ret0 +} + +// GetFeeState indicates an expected call of GetFeeState. +func (mr *MockDiffMockRecorder) GetFeeState() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeeState", reflect.TypeOf((*MockDiff)(nil).GetFeeState)) +} + +// GetPendingDelegatorIterator mocks base method. +func (m *MockDiff) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", subnetID, nodeID) + ret0, _ := ret[0].(iterator.Iterator[*Staker]) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. +func (mr *MockDiffMockRecorder) GetPendingDelegatorIterator(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*MockDiff)(nil).GetPendingDelegatorIterator), subnetID, nodeID) +} + +// GetPendingStakerIterator mocks base method. +func (m *MockDiff) GetPendingStakerIterator() (iterator.Iterator[*Staker], error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingStakerIterator") + ret0, _ := ret[0].(iterator.Iterator[*Staker]) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingStakerIterator indicates an expected call of GetPendingStakerIterator. +func (mr *MockDiffMockRecorder) GetPendingStakerIterator() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingStakerIterator", reflect.TypeOf((*MockDiff)(nil).GetPendingStakerIterator)) +} + +// GetPendingValidator mocks base method. +func (m *MockDiff) GetPendingValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPendingValidator", subnetID, nodeID) + ret0, _ := ret[0].(*Staker) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPendingValidator indicates an expected call of GetPendingValidator. +func (mr *MockDiffMockRecorder) GetPendingValidator(subnetID, nodeID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*MockDiff)(nil).GetPendingValidator), subnetID, nodeID) +} + +// GetSubnetManager mocks base method. +func (m *MockDiff) GetSubnetManager(subnetID ids.ID) (ids.ID, []byte, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetManager", subnetID) + ret0, _ := ret[0].(ids.ID) + ret1, _ := ret[1].([]byte) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetSubnetManager indicates an expected call of GetSubnetManager. +func (mr *MockDiffMockRecorder) GetSubnetManager(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*MockDiff)(nil).GetSubnetManager), subnetID) +} + +// GetSubnetOwner mocks base method. +func (m *MockDiff) GetSubnetOwner(subnetID ids.ID) (fx.Owner, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetOwner", subnetID) + ret0, _ := ret[0].(fx.Owner) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSubnetOwner indicates an expected call of GetSubnetOwner. +func (mr *MockDiffMockRecorder) GetSubnetOwner(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*MockDiff)(nil).GetSubnetOwner), subnetID) +} + +// GetSubnetTransformation mocks base method. +func (m *MockDiff) GetSubnetTransformation(subnetID ids.ID) (*txs.Tx, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetSubnetTransformation", subnetID) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetSubnetTransformation indicates an expected call of GetSubnetTransformation. +func (mr *MockDiffMockRecorder) GetSubnetTransformation(subnetID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*MockDiff)(nil).GetSubnetTransformation), subnetID) +} + +// GetTimestamp mocks base method. +func (m *MockDiff) GetTimestamp() time.Time { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTimestamp") + ret0, _ := ret[0].(time.Time) + return ret0 +} + +// GetTimestamp indicates an expected call of GetTimestamp. +func (mr *MockDiffMockRecorder) GetTimestamp() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*MockDiff)(nil).GetTimestamp)) +} + +// GetTx mocks base method. +func (m *MockDiff) GetTx(txID ids.ID) (*txs.Tx, status.Status, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetTx", txID) + ret0, _ := ret[0].(*txs.Tx) + ret1, _ := ret[1].(status.Status) + ret2, _ := ret[2].(error) + return ret0, ret1, ret2 +} + +// GetTx indicates an expected call of GetTx. +func (mr *MockDiffMockRecorder) GetTx(txID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*MockDiff)(nil).GetTx), txID) +} + +// GetUTXO mocks base method. +func (m *MockDiff) GetUTXO(utxoID ids.ID) (*avax.UTXO, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUTXO", utxoID) + ret0, _ := ret[0].(*avax.UTXO) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUTXO indicates an expected call of GetUTXO. +func (mr *MockDiffMockRecorder) GetUTXO(utxoID any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*MockDiff)(nil).GetUTXO), utxoID) +} + +// PutCurrentDelegator mocks base method. +func (m *MockDiff) PutCurrentDelegator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutCurrentDelegator", staker) +} + +// PutCurrentDelegator indicates an expected call of PutCurrentDelegator. +func (mr *MockDiffMockRecorder) PutCurrentDelegator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*MockDiff)(nil).PutCurrentDelegator), staker) +} + +// PutCurrentValidator mocks base method. +func (m *MockDiff) PutCurrentValidator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutCurrentValidator", staker) +} + +// PutCurrentValidator indicates an expected call of PutCurrentValidator. +func (mr *MockDiffMockRecorder) PutCurrentValidator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*MockDiff)(nil).PutCurrentValidator), staker) +} + +// PutPendingDelegator mocks base method. +func (m *MockDiff) PutPendingDelegator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutPendingDelegator", staker) +} + +// PutPendingDelegator indicates an expected call of PutPendingDelegator. +func (mr *MockDiffMockRecorder) PutPendingDelegator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*MockDiff)(nil).PutPendingDelegator), staker) +} + +// PutPendingValidator mocks base method. +func (m *MockDiff) PutPendingValidator(staker *Staker) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PutPendingValidator", staker) +} + +// PutPendingValidator indicates an expected call of PutPendingValidator. +func (mr *MockDiffMockRecorder) PutPendingValidator(staker any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*MockDiff)(nil).PutPendingValidator), staker) +} + +// SetCurrentSupply mocks base method. +func (m *MockDiff) SetCurrentSupply(subnetID ids.ID, cs uint64) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetCurrentSupply", subnetID, cs) +} + +// SetCurrentSupply indicates an expected call of SetCurrentSupply. +func (mr *MockDiffMockRecorder) SetCurrentSupply(subnetID, cs any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*MockDiff)(nil).SetCurrentSupply), subnetID, cs) +} + +// SetDelegateeReward mocks base method. +func (m *MockDiff) SetDelegateeReward(subnetID ids.ID, nodeID ids.NodeID, amount uint64) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetDelegateeReward", subnetID, nodeID, amount) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetDelegateeReward indicates an expected call of SetDelegateeReward. +func (mr *MockDiffMockRecorder) SetDelegateeReward(subnetID, nodeID, amount any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*MockDiff)(nil).SetDelegateeReward), subnetID, nodeID, amount) +} + +// SetFeeState mocks base method. +func (m *MockDiff) SetFeeState(f gas.State) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetFeeState", f) +} + +// SetFeeState indicates an expected call of SetFeeState. +func (mr *MockDiffMockRecorder) SetFeeState(f any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*MockDiff)(nil).SetFeeState), f) +} + +// SetSubnetManager mocks base method. +func (m *MockDiff) SetSubnetManager(subnetID, chainID ids.ID, addr []byte) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetSubnetManager", subnetID, chainID, addr) +} + +// SetSubnetManager indicates an expected call of SetSubnetManager. +func (mr *MockDiffMockRecorder) SetSubnetManager(subnetID, chainID, addr any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*MockDiff)(nil).SetSubnetManager), subnetID, chainID, addr) +} + +// SetSubnetOwner mocks base method. +func (m *MockDiff) SetSubnetOwner(subnetID ids.ID, owner fx.Owner) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetSubnetOwner", subnetID, owner) +} + +// SetSubnetOwner indicates an expected call of SetSubnetOwner. +func (mr *MockDiffMockRecorder) SetSubnetOwner(subnetID, owner any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*MockDiff)(nil).SetSubnetOwner), subnetID, owner) +} + +// SetTimestamp mocks base method. +func (m *MockDiff) SetTimestamp(tm time.Time) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetTimestamp", tm) +} + +// SetTimestamp indicates an expected call of SetTimestamp. +func (mr *MockDiffMockRecorder) SetTimestamp(tm any) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*MockDiff)(nil).SetTimestamp), tm) +} diff --git a/vms/platformvm/state/mock_staker_iterator.go b/vms/platformvm/state/mock_staker_iterator.go deleted file mode 100644 index 0129198c1f57..000000000000 --- a/vms/platformvm/state/mock_staker_iterator.go +++ /dev/null @@ -1,79 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: vms/platformvm/state/staker.go -// -// Generated by this command: -// -// mockgen -source=vms/platformvm/state/staker.go -destination=vms/platformvm/state/mock_staker_iterator.go -package=state -exclude_interfaces= -mock_names=MockStakerIterator=MockStakerIterator -// - -// Package state is a generated GoMock package. -package state - -import ( - reflect "reflect" - - gomock "go.uber.org/mock/gomock" -) - -// MockStakerIterator is a mock of StakerIterator interface. -type MockStakerIterator struct { - ctrl *gomock.Controller - recorder *MockStakerIteratorMockRecorder -} - -// MockStakerIteratorMockRecorder is the mock recorder for MockStakerIterator. -type MockStakerIteratorMockRecorder struct { - mock *MockStakerIterator -} - -// NewMockStakerIterator creates a new mock instance. -func NewMockStakerIterator(ctrl *gomock.Controller) *MockStakerIterator { - mock := &MockStakerIterator{ctrl: ctrl} - mock.recorder = &MockStakerIteratorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *MockStakerIterator) EXPECT() *MockStakerIteratorMockRecorder { - return m.recorder -} - -// Next mocks base method. -func (m *MockStakerIterator) Next() bool { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Next") - ret0, _ := ret[0].(bool) - return ret0 -} - -// Next indicates an expected call of Next. -func (mr *MockStakerIteratorMockRecorder) Next() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Next", reflect.TypeOf((*MockStakerIterator)(nil).Next)) -} - -// Release mocks base method. -func (m *MockStakerIterator) Release() { - m.ctrl.T.Helper() - m.ctrl.Call(m, "Release") -} - -// Release indicates an expected call of Release. -func (mr *MockStakerIteratorMockRecorder) Release() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Release", reflect.TypeOf((*MockStakerIterator)(nil).Release)) -} - -// Value mocks base method. -func (m *MockStakerIterator) Value() *Staker { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Value") - ret0, _ := ret[0].(*Staker) - return ret0 -} - -// Value indicates an expected call of Value. -func (mr *MockStakerIteratorMockRecorder) Value() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Value", reflect.TypeOf((*MockStakerIterator)(nil).Value)) -} diff --git a/vms/platformvm/state/mock_state.go b/vms/platformvm/state/mock_state.go index a565ce2ff4f7..9bc07c2333fe 100644 --- a/vms/platformvm/state/mock_state.go +++ b/vms/platformvm/state/mock_state.go @@ -18,6 +18,7 @@ import ( database "github.com/ava-labs/avalanchego/database" ids "github.com/ava-labs/avalanchego/ids" validators "github.com/ava-labs/avalanchego/snow/validators" + iterator "github.com/ava-labs/avalanchego/utils/iterator" logging "github.com/ava-labs/avalanchego/utils/logging" avax "github.com/ava-labs/avalanchego/vms/components/avax" gas "github.com/ava-labs/avalanchego/vms/components/gas" @@ -323,10 +324,10 @@ func (mr *MockStateMockRecorder) GetChains(subnetID any) *gomock.Call { } // GetCurrentDelegatorIterator mocks base method. -func (m *MockState) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) { +func (m *MockState) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", subnetID, nodeID) - ret0, _ := ret[0].(StakerIterator) + ret0, _ := ret[0].(iterator.Iterator[*Staker]) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -338,10 +339,10 @@ func (mr *MockStateMockRecorder) GetCurrentDelegatorIterator(subnetID, nodeID an } // GetCurrentStakerIterator mocks base method. -func (m *MockState) GetCurrentStakerIterator() (StakerIterator, error) { +func (m *MockState) GetCurrentStakerIterator() (iterator.Iterator[*Staker], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetCurrentStakerIterator") - ret0, _ := ret[0].(StakerIterator) + ret0, _ := ret[0].(iterator.Iterator[*Staker]) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -426,10 +427,10 @@ func (mr *MockStateMockRecorder) GetLastAccepted() *gomock.Call { } // GetPendingDelegatorIterator mocks base method. -func (m *MockState) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) { +func (m *MockState) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", subnetID, nodeID) - ret0, _ := ret[0].(StakerIterator) + ret0, _ := ret[0].(iterator.Iterator[*Staker]) ret1, _ := ret[1].(error) return ret0, ret1 } @@ -441,10 +442,10 @@ func (mr *MockStateMockRecorder) GetPendingDelegatorIterator(subnetID, nodeID an } // GetPendingStakerIterator mocks base method. -func (m *MockState) GetPendingStakerIterator() (StakerIterator, error) { +func (m *MockState) GetPendingStakerIterator() (iterator.Iterator[*Staker], error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "GetPendingStakerIterator") - ret0, _ := ret[0].(StakerIterator) + ret0, _ := ret[0].(iterator.Iterator[*Staker]) ret1, _ := ret[1].(error) return ret0, ret1 } diff --git a/vms/platformvm/state/slice_iterator_test.go b/vms/platformvm/state/slice_iterator_test.go deleted file mode 100644 index 408ffe837a27..000000000000 --- a/vms/platformvm/state/slice_iterator_test.go +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package state - -var _ StakerIterator = (*sliceIterator)(nil) - -type sliceIterator struct { - index int - stakers []*Staker -} - -// NewSliceIterator returns an iterator that contains the elements of [stakers] -// in order. Doesn't sort by anything. -func NewSliceIterator(stakers ...*Staker) StakerIterator { - return &sliceIterator{ - index: -1, - stakers: stakers, - } -} - -func (i *sliceIterator) Next() bool { - i.index++ - return i.index < len(i.stakers) -} - -func (i *sliceIterator) Value() *Staker { - return i.stakers[i.index] -} - -func (*sliceIterator) Release() {} diff --git a/vms/platformvm/state/staker.go b/vms/platformvm/state/staker.go index a9ba52595062..1146efe74f8e 100644 --- a/vms/platformvm/state/staker.go +++ b/vms/platformvm/state/staker.go @@ -16,21 +16,6 @@ import ( var _ btree.LessFunc[*Staker] = (*Staker).Less -// StakerIterator defines an interface for iterating over a set of stakers. -type StakerIterator interface { - // Next attempts to move the iterator to the next staker. It returns false - // once there are no more stakers to return. - Next() bool - - // Value returns the current staker. Value should only be called after a - // call to Next which returned true. - Value() *Staker - - // Release any resources associated with the iterator. This must be called - // after the interator is no longer needed. - Release() -} - // Staker contains all information required to represent a validator or // delegator in the current and pending validator sets. // Invariant: Staker's size is bounded to prevent OOM DoS attacks. diff --git a/vms/platformvm/state/staker_diff_iterator.go b/vms/platformvm/state/staker_diff_iterator.go index d47ab49ac572..d8017faff855 100644 --- a/vms/platformvm/state/staker_diff_iterator.go +++ b/vms/platformvm/state/staker_diff_iterator.go @@ -5,12 +5,13 @@ package state import ( "github.com/ava-labs/avalanchego/utils/heap" + "github.com/ava-labs/avalanchego/utils/iterator" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) var ( - _ StakerDiffIterator = (*stakerDiffIterator)(nil) - _ StakerIterator = (*mutableStakerIterator)(nil) + _ StakerDiffIterator = (*stakerDiffIterator)(nil) + _ iterator.Iterator[*Staker] = (*mutableStakerIterator)(nil) ) // StakerDiffIterator is an iterator that iterates over the events that will be @@ -40,13 +41,13 @@ type stakerDiffIterator struct { currentIterator *mutableStakerIterator pendingIteratorExhausted bool - pendingIterator StakerIterator + pendingIterator iterator.Iterator[*Staker] modifiedStaker *Staker isAdded bool } -func NewStakerDiffIterator(currentIterator, pendingIterator StakerIterator) StakerDiffIterator { +func NewStakerDiffIterator(currentIterator, pendingIterator iterator.Iterator[*Staker]) StakerDiffIterator { mutableCurrentIterator := newMutableStakerIterator(currentIterator) return &stakerDiffIterator{ currentIteratorExhausted: !mutableCurrentIterator.Next(), @@ -111,11 +112,11 @@ func (it *stakerDiffIterator) advancePending() { type mutableStakerIterator struct { iteratorExhausted bool - iterator StakerIterator + iterator iterator.Iterator[*Staker] heap heap.Queue[*Staker] } -func newMutableStakerIterator(iterator StakerIterator) *mutableStakerIterator { +func newMutableStakerIterator(iterator iterator.Iterator[*Staker]) *mutableStakerIterator { return &mutableStakerIterator{ iteratorExhausted: !iterator.Next(), iterator: iterator, diff --git a/vms/platformvm/state/staker_diff_iterator_test.go b/vms/platformvm/state/staker_diff_iterator_test.go index 468b8800a23d..ebacbdd18a20 100644 --- a/vms/platformvm/state/staker_diff_iterator_test.go +++ b/vms/platformvm/state/staker_diff_iterator_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/iterator" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) @@ -97,8 +98,8 @@ func TestStakerDiffIterator(t *testing.T) { } it := NewStakerDiffIterator( - NewSliceIterator(currentStakers...), - NewSliceIterator(pendingStakers...), + iterator.FromSlice(currentStakers...), + iterator.FromSlice(pendingStakers...), ) for _, expectedStaker := range stakerDiffs { require.True(it.Next()) @@ -134,7 +135,7 @@ func TestMutableStakerIterator(t *testing.T) { }, } - it := newMutableStakerIterator(NewSliceIterator(initialStakers...)) + it := newMutableStakerIterator(iterator.FromSlice(initialStakers...)) addedStakers := []*Staker{ { diff --git a/vms/platformvm/state/stakers.go b/vms/platformvm/state/stakers.go index f787749f72df..c39d84d48d02 100644 --- a/vms/platformvm/state/stakers.go +++ b/vms/platformvm/state/stakers.go @@ -8,6 +8,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/iterator" ) type Stakers interface { @@ -44,7 +45,7 @@ type CurrentStakers interface { // GetCurrentDelegatorIterator returns the delegators associated with the // validator on [subnetID] with [nodeID]. Delegators are sorted by their // removal from current staker set. - GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) + GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) // PutCurrentDelegator adds the [staker] describing a delegator to the // staker set. @@ -60,7 +61,7 @@ type CurrentStakers interface { // GetCurrentStakerIterator returns stakers in order of their removal from // the current staker set. - GetCurrentStakerIterator() (StakerIterator, error) + GetCurrentStakerIterator() (iterator.Iterator[*Staker], error) } type PendingStakers interface { @@ -80,7 +81,7 @@ type PendingStakers interface { // GetPendingDelegatorIterator returns the delegators associated with the // validator on [subnetID] with [nodeID]. Delegators are sorted by their // removal from pending staker set. - GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) + GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) // PutPendingDelegator adds the [staker] describing a delegator to the // staker set. @@ -92,7 +93,7 @@ type PendingStakers interface { // GetPendingStakerIterator returns stakers in order of their removal from // the pending staker set. - GetPendingStakerIterator() (StakerIterator, error) + GetPendingStakerIterator() (iterator.Iterator[*Staker], error) } type baseStakers struct { @@ -154,16 +155,16 @@ func (v *baseStakers) DeleteValidator(staker *Staker) { v.stakers.Delete(staker) } -func (v *baseStakers) GetDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) StakerIterator { +func (v *baseStakers) GetDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) iterator.Iterator[*Staker] { subnetValidators, ok := v.validators[subnetID] if !ok { - return EmptyIterator + return iterator.Empty[*Staker]{} } validator, ok := subnetValidators[nodeID] if !ok { - return EmptyIterator + return iterator.Empty[*Staker]{} } - return NewTreeIterator(validator.delegators) + return iterator.FromTree(validator.delegators) } func (v *baseStakers) PutDelegator(staker *Staker) { @@ -198,8 +199,8 @@ func (v *baseStakers) DeleteDelegator(staker *Staker) { v.stakers.Delete(staker) } -func (v *baseStakers) GetStakerIterator() StakerIterator { - return NewTreeIterator(v.stakers) +func (v *baseStakers) GetStakerIterator() iterator.Iterator[*Staker] { + return iterator.FromTree(v.stakers) } func (v *baseStakers) getOrCreateValidator(subnetID ids.ID, nodeID ids.NodeID) *baseStaker { @@ -318,27 +319,31 @@ func (s *diffStakers) DeleteValidator(staker *Staker) { } func (s *diffStakers) GetDelegatorIterator( - parentIterator StakerIterator, + parentIterator iterator.Iterator[*Staker], subnetID ids.ID, nodeID ids.NodeID, -) StakerIterator { +) iterator.Iterator[*Staker] { var ( - addedDelegatorIterator = EmptyIterator + addedDelegatorIterator iterator.Iterator[*Staker] = iterator.Empty[*Staker]{} deletedDelegators map[ids.ID]*Staker ) if subnetValidatorDiffs, ok := s.validatorDiffs[subnetID]; ok { if validatorDiff, ok := subnetValidatorDiffs[nodeID]; ok { - addedDelegatorIterator = NewTreeIterator(validatorDiff.addedDelegators) + addedDelegatorIterator = iterator.FromTree(validatorDiff.addedDelegators) deletedDelegators = validatorDiff.deletedDelegators } } - return NewMaskedIterator( - NewMergedIterator( + return iterator.Filter( + iterator.Merge( + (*Staker).Less, parentIterator, addedDelegatorIterator, ), - deletedDelegators, + func(staker *Staker) bool { + _, ok := deletedDelegators[staker.TxID] + return ok + }, ) } @@ -368,13 +373,17 @@ func (s *diffStakers) DeleteDelegator(staker *Staker) { s.deletedStakers[staker.TxID] = staker } -func (s *diffStakers) GetStakerIterator(parentIterator StakerIterator) StakerIterator { - return NewMaskedIterator( - NewMergedIterator( +func (s *diffStakers) GetStakerIterator(parentIterator iterator.Iterator[*Staker]) iterator.Iterator[*Staker] { + return iterator.Filter( + iterator.Merge( + (*Staker).Less, parentIterator, - NewTreeIterator(s.addedStakers), + iterator.FromTree(s.addedStakers), ), - s.deletedStakers, + func(staker *Staker) bool { + _, ok := s.deletedStakers[staker.TxID] + return ok + }, ) } diff --git a/vms/platformvm/state/stakers_test.go b/vms/platformvm/state/stakers_test.go index d01593c0548e..6b1343891540 100644 --- a/vms/platformvm/state/stakers_test.go +++ b/vms/platformvm/state/stakers_test.go @@ -11,6 +11,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/iterator" "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/txs" ) @@ -85,7 +86,7 @@ func TestBaseStakersValidator(t *testing.T) { require.ErrorIs(err, database.ErrNotFound) stakerIterator := v.GetStakerIterator() - assertIteratorsEqual(t, NewSliceIterator(delegator), stakerIterator) + assertIteratorsEqual(t, iterator.FromSlice(delegator), stakerIterator) v.PutValidator(staker) @@ -96,7 +97,7 @@ func TestBaseStakersValidator(t *testing.T) { v.DeleteDelegator(delegator) stakerIterator = v.GetStakerIterator() - assertIteratorsEqual(t, NewSliceIterator(staker), stakerIterator) + assertIteratorsEqual(t, iterator.FromSlice(staker), stakerIterator) v.DeleteValidator(staker) @@ -104,7 +105,7 @@ func TestBaseStakersValidator(t *testing.T) { require.ErrorIs(err, database.ErrNotFound) stakerIterator = v.GetStakerIterator() - assertIteratorsEqual(t, EmptyIterator, stakerIterator) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, stakerIterator) } func TestBaseStakersDelegator(t *testing.T) { @@ -114,20 +115,20 @@ func TestBaseStakersDelegator(t *testing.T) { v := newBaseStakers() delegatorIterator := v.GetDelegatorIterator(delegator.SubnetID, delegator.NodeID) - assertIteratorsEqual(t, EmptyIterator, delegatorIterator) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) v.PutDelegator(delegator) delegatorIterator = v.GetDelegatorIterator(delegator.SubnetID, ids.GenerateTestNodeID()) - assertIteratorsEqual(t, EmptyIterator, delegatorIterator) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) delegatorIterator = v.GetDelegatorIterator(delegator.SubnetID, delegator.NodeID) - assertIteratorsEqual(t, NewSliceIterator(delegator), delegatorIterator) + assertIteratorsEqual(t, iterator.FromSlice(delegator), delegatorIterator) v.DeleteDelegator(delegator) delegatorIterator = v.GetDelegatorIterator(delegator.SubnetID, delegator.NodeID) - assertIteratorsEqual(t, EmptyIterator, delegatorIterator) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) v.PutValidator(staker) @@ -135,7 +136,7 @@ func TestBaseStakersDelegator(t *testing.T) { v.DeleteDelegator(delegator) delegatorIterator = v.GetDelegatorIterator(staker.SubnetID, staker.NodeID) - assertIteratorsEqual(t, EmptyIterator, delegatorIterator) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) } func TestDiffStakersValidator(t *testing.T) { @@ -158,8 +159,8 @@ func TestDiffStakersValidator(t *testing.T) { _, status = v.GetValidator(delegator.SubnetID, delegator.NodeID) require.Equal(unmodified, status) - stakerIterator := v.GetStakerIterator(EmptyIterator) - assertIteratorsEqual(t, NewSliceIterator(delegator), stakerIterator) + stakerIterator := v.GetStakerIterator(iterator.Empty[*Staker]{}) + assertIteratorsEqual(t, iterator.FromSlice(delegator), stakerIterator) v.PutValidator(staker) @@ -175,8 +176,8 @@ func TestDiffStakersValidator(t *testing.T) { _, status = v.GetValidator(staker.SubnetID, staker.NodeID) require.Equal(unmodified, status) - stakerIterator = v.GetStakerIterator(EmptyIterator) - assertIteratorsEqual(t, NewSliceIterator(delegator), stakerIterator) + stakerIterator = v.GetStakerIterator(iterator.Empty[*Staker]{}) + assertIteratorsEqual(t, iterator.FromSlice(delegator), stakerIterator) } func TestDiffStakersDeleteValidator(t *testing.T) { @@ -204,18 +205,18 @@ func TestDiffStakersDelegator(t *testing.T) { v.PutValidator(staker) - delegatorIterator := v.GetDelegatorIterator(EmptyIterator, ids.GenerateTestID(), delegator.NodeID) - assertIteratorsEqual(t, EmptyIterator, delegatorIterator) + delegatorIterator := v.GetDelegatorIterator(iterator.Empty[*Staker]{}, ids.GenerateTestID(), delegator.NodeID) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) v.PutDelegator(delegator) - delegatorIterator = v.GetDelegatorIterator(EmptyIterator, delegator.SubnetID, delegator.NodeID) - assertIteratorsEqual(t, NewSliceIterator(delegator), delegatorIterator) + delegatorIterator = v.GetDelegatorIterator(iterator.Empty[*Staker]{}, delegator.SubnetID, delegator.NodeID) + assertIteratorsEqual(t, iterator.FromSlice(delegator), delegatorIterator) v.DeleteDelegator(delegator) - delegatorIterator = v.GetDelegatorIterator(EmptyIterator, ids.GenerateTestID(), delegator.NodeID) - assertIteratorsEqual(t, EmptyIterator, delegatorIterator) + delegatorIterator = v.GetDelegatorIterator(iterator.Empty[*Staker]{}, ids.GenerateTestID(), delegator.NodeID) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) } func newTestStaker() *Staker { @@ -235,7 +236,7 @@ func newTestStaker() *Staker { } } -func assertIteratorsEqual(t *testing.T, expected, actual StakerIterator) { +func assertIteratorsEqual(t *testing.T, expected, actual iterator.Iterator[*Staker]) { require := require.New(t) t.Helper() diff --git a/vms/platformvm/state/state.go b/vms/platformvm/state/state.go index 952ffac01145..17a5e83bd28f 100644 --- a/vms/platformvm/state/state.go +++ b/vms/platformvm/state/state.go @@ -30,6 +30,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/hashing" + "github.com/ava-labs/avalanchego/utils/iterator" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer" "github.com/ava-labs/avalanchego/utils/wrappers" @@ -48,6 +49,7 @@ import ( ) const ( + defaultTreeDegree = 2 indexIterationLimit = 4096 indexIterationSleepMultiplier = 5 indexIterationSleepCap = 10 * time.Second @@ -688,7 +690,7 @@ func (s *state) DeleteCurrentValidator(staker *Staker) { s.currentStakers.DeleteValidator(staker) } -func (s *state) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) { +func (s *state) GetCurrentDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { return s.currentStakers.GetDelegatorIterator(subnetID, nodeID), nil } @@ -700,7 +702,7 @@ func (s *state) DeleteCurrentDelegator(staker *Staker) { s.currentStakers.DeleteDelegator(staker) } -func (s *state) GetCurrentStakerIterator() (StakerIterator, error) { +func (s *state) GetCurrentStakerIterator() (iterator.Iterator[*Staker], error) { return s.currentStakers.GetStakerIterator(), nil } @@ -716,7 +718,7 @@ func (s *state) DeletePendingValidator(staker *Staker) { s.pendingStakers.DeleteValidator(staker) } -func (s *state) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (StakerIterator, error) { +func (s *state) GetPendingDelegatorIterator(subnetID ids.ID, nodeID ids.NodeID) (iterator.Iterator[*Staker], error) { return s.pendingStakers.GetDelegatorIterator(subnetID, nodeID), nil } @@ -728,7 +730,7 @@ func (s *state) DeletePendingDelegator(staker *Staker) { s.pendingStakers.DeleteDelegator(staker) } -func (s *state) GetPendingStakerIterator() (StakerIterator, error) { +func (s *state) GetPendingStakerIterator() (iterator.Iterator[*Staker], error) { return s.pendingStakers.GetStakerIterator(), nil } @@ -1649,7 +1651,7 @@ func (s *state) initValidatorSets() error { return err } - delegatorIterator := NewTreeIterator(validator.delegators) + delegatorIterator := iterator.FromTree(validator.delegators) for delegatorIterator.Next() { delegatorStaker := delegatorIterator.Value() if err := s.validators.AddWeight(subnetID, nodeID, delegatorStaker.Weight); err != nil { @@ -2071,7 +2073,7 @@ func writeCurrentDelegatorDiff( validatorDiff *diffValidator, codecVersion uint16, ) error { - addedDelegatorIterator := NewTreeIterator(validatorDiff.addedDelegators) + addedDelegatorIterator := iterator.FromTree(validatorDiff.addedDelegators) defer addedDelegatorIterator.Release() for addedDelegatorIterator.Next() { staker := addedDelegatorIterator.Value() @@ -2145,7 +2147,7 @@ func writePendingDiff( } } - addedDelegatorIterator := NewTreeIterator(validatorDiff.addedDelegators) + addedDelegatorIterator := iterator.FromTree(validatorDiff.addedDelegators) defer addedDelegatorIterator.Release() for addedDelegatorIterator.Next() { staker := addedDelegatorIterator.Value() diff --git a/vms/platformvm/state/state_test.go b/vms/platformvm/state/state_test.go index 41a51b17d588..7e52453d5742 100644 --- a/vms/platformvm/state/state_test.go +++ b/vms/platformvm/state/state_test.go @@ -26,6 +26,7 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" + "github.com/ava-labs/avalanchego/utils/iterator" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/utils/wrappers" @@ -81,18 +82,18 @@ func TestStateSyncGenesis(t *testing.T) { delegatorIterator, err := state.GetCurrentDelegatorIterator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) require.NoError(err) - assertIteratorsEqual(t, EmptyIterator, delegatorIterator) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) stakerIterator, err := state.GetCurrentStakerIterator() require.NoError(err) - assertIteratorsEqual(t, NewSliceIterator(staker), stakerIterator) + assertIteratorsEqual(t, iterator.FromSlice(staker), stakerIterator) _, err = state.GetPendingValidator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) require.ErrorIs(err, database.ErrNotFound) delegatorIterator, err = state.GetPendingDelegatorIterator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) require.NoError(err) - assertIteratorsEqual(t, EmptyIterator, delegatorIterator) + assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) } // Whenever we store a staker, a whole bunch a data structures are updated diff --git a/vms/platformvm/state/statemock/chain.go b/vms/platformvm/state/statemock/chain.go deleted file mode 100644 index b0d239671610..000000000000 --- a/vms/platformvm/state/statemock/chain.go +++ /dev/null @@ -1,526 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/platformvm/state (interfaces: Chain) -// -// Generated by this command: -// -// mockgen -package=statemock -destination=vms/platformvm/state/statemock/chain.go -mock_names=Chain=Chain github.com/ava-labs/avalanchego/vms/platformvm/state Chain -// - -// Package statemock is a generated GoMock package. -package statemock - -import ( - reflect "reflect" - time "time" - - ids "github.com/ava-labs/avalanchego/ids" - avax "github.com/ava-labs/avalanchego/vms/components/avax" - gas "github.com/ava-labs/avalanchego/vms/components/gas" - fx "github.com/ava-labs/avalanchego/vms/platformvm/fx" - state "github.com/ava-labs/avalanchego/vms/platformvm/state" - status "github.com/ava-labs/avalanchego/vms/platformvm/status" - txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" - gomock "go.uber.org/mock/gomock" -) - -// Chain is a mock of Chain interface. -type Chain struct { - ctrl *gomock.Controller - recorder *ChainMockRecorder -} - -// ChainMockRecorder is the mock recorder for Chain. -type ChainMockRecorder struct { - mock *Chain -} - -// NewChain creates a new mock instance. -func NewChain(ctrl *gomock.Controller) *Chain { - mock := &Chain{ctrl: ctrl} - mock.recorder = &ChainMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *Chain) EXPECT() *ChainMockRecorder { - return m.recorder -} - -// AddChain mocks base method. -func (m *Chain) AddChain(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddChain", arg0) -} - -// AddChain indicates an expected call of AddChain. -func (mr *ChainMockRecorder) AddChain(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*Chain)(nil).AddChain), arg0) -} - -// AddRewardUTXO mocks base method. -func (m *Chain) AddRewardUTXO(arg0 ids.ID, arg1 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddRewardUTXO", arg0, arg1) -} - -// AddRewardUTXO indicates an expected call of AddRewardUTXO. -func (mr *ChainMockRecorder) AddRewardUTXO(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*Chain)(nil).AddRewardUTXO), arg0, arg1) -} - -// AddSubnet mocks base method. -func (m *Chain) AddSubnet(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnet", arg0) -} - -// AddSubnet indicates an expected call of AddSubnet. -func (mr *ChainMockRecorder) AddSubnet(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*Chain)(nil).AddSubnet), arg0) -} - -// AddSubnetTransformation mocks base method. -func (m *Chain) AddSubnetTransformation(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnetTransformation", arg0) -} - -// AddSubnetTransformation indicates an expected call of AddSubnetTransformation. -func (mr *ChainMockRecorder) AddSubnetTransformation(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*Chain)(nil).AddSubnetTransformation), arg0) -} - -// AddTx mocks base method. -func (m *Chain) AddTx(arg0 *txs.Tx, arg1 status.Status) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddTx", arg0, arg1) -} - -// AddTx indicates an expected call of AddTx. -func (mr *ChainMockRecorder) AddTx(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*Chain)(nil).AddTx), arg0, arg1) -} - -// AddUTXO mocks base method. -func (m *Chain) AddUTXO(arg0 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddUTXO", arg0) -} - -// AddUTXO indicates an expected call of AddUTXO. -func (mr *ChainMockRecorder) AddUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*Chain)(nil).AddUTXO), arg0) -} - -// DeleteCurrentDelegator mocks base method. -func (m *Chain) DeleteCurrentDelegator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentDelegator", arg0) -} - -// DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. -func (mr *ChainMockRecorder) DeleteCurrentDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*Chain)(nil).DeleteCurrentDelegator), arg0) -} - -// DeleteCurrentValidator mocks base method. -func (m *Chain) DeleteCurrentValidator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentValidator", arg0) -} - -// DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. -func (mr *ChainMockRecorder) DeleteCurrentValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*Chain)(nil).DeleteCurrentValidator), arg0) -} - -// DeletePendingDelegator mocks base method. -func (m *Chain) DeletePendingDelegator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingDelegator", arg0) -} - -// DeletePendingDelegator indicates an expected call of DeletePendingDelegator. -func (mr *ChainMockRecorder) DeletePendingDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*Chain)(nil).DeletePendingDelegator), arg0) -} - -// DeletePendingValidator mocks base method. -func (m *Chain) DeletePendingValidator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingValidator", arg0) -} - -// DeletePendingValidator indicates an expected call of DeletePendingValidator. -func (mr *ChainMockRecorder) DeletePendingValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*Chain)(nil).DeletePendingValidator), arg0) -} - -// DeleteUTXO mocks base method. -func (m *Chain) DeleteUTXO(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteUTXO", arg0) -} - -// DeleteUTXO indicates an expected call of DeleteUTXO. -func (mr *ChainMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*Chain)(nil).DeleteUTXO), arg0) -} - -// GetCurrentDelegatorIterator mocks base method. -func (m *Chain) GetCurrentDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (state.StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", arg0, arg1) - ret0, _ := ret[0].(state.StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. -func (mr *ChainMockRecorder) GetCurrentDelegatorIterator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*Chain)(nil).GetCurrentDelegatorIterator), arg0, arg1) -} - -// GetCurrentStakerIterator mocks base method. -func (m *Chain) GetCurrentStakerIterator() (state.StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentStakerIterator") - ret0, _ := ret[0].(state.StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentStakerIterator indicates an expected call of GetCurrentStakerIterator. -func (mr *ChainMockRecorder) GetCurrentStakerIterator() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentStakerIterator", reflect.TypeOf((*Chain)(nil).GetCurrentStakerIterator)) -} - -// GetCurrentSupply mocks base method. -func (m *Chain) GetCurrentSupply(arg0 ids.ID) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentSupply", arg0) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentSupply indicates an expected call of GetCurrentSupply. -func (mr *ChainMockRecorder) GetCurrentSupply(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*Chain)(nil).GetCurrentSupply), arg0) -} - -// GetCurrentValidator mocks base method. -func (m *Chain) GetCurrentValidator(arg0 ids.ID, arg1 ids.NodeID) (*state.Staker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentValidator", arg0, arg1) - ret0, _ := ret[0].(*state.Staker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentValidator indicates an expected call of GetCurrentValidator. -func (mr *ChainMockRecorder) GetCurrentValidator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*Chain)(nil).GetCurrentValidator), arg0, arg1) -} - -// GetDelegateeReward mocks base method. -func (m *Chain) GetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDelegateeReward", arg0, arg1) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetDelegateeReward indicates an expected call of GetDelegateeReward. -func (mr *ChainMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*Chain)(nil).GetDelegateeReward), arg0, arg1) -} - -// GetFeeState mocks base method. -func (m *Chain) GetFeeState() gas.State { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetFeeState") - ret0, _ := ret[0].(gas.State) - return ret0 -} - -// GetFeeState indicates an expected call of GetFeeState. -func (mr *ChainMockRecorder) GetFeeState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeeState", reflect.TypeOf((*Chain)(nil).GetFeeState)) -} - -// GetPendingDelegatorIterator mocks base method. -func (m *Chain) GetPendingDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (state.StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", arg0, arg1) - ret0, _ := ret[0].(state.StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. -func (mr *ChainMockRecorder) GetPendingDelegatorIterator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*Chain)(nil).GetPendingDelegatorIterator), arg0, arg1) -} - -// GetPendingStakerIterator mocks base method. -func (m *Chain) GetPendingStakerIterator() (state.StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingStakerIterator") - ret0, _ := ret[0].(state.StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingStakerIterator indicates an expected call of GetPendingStakerIterator. -func (mr *ChainMockRecorder) GetPendingStakerIterator() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingStakerIterator", reflect.TypeOf((*Chain)(nil).GetPendingStakerIterator)) -} - -// GetPendingValidator mocks base method. -func (m *Chain) GetPendingValidator(arg0 ids.ID, arg1 ids.NodeID) (*state.Staker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingValidator", arg0, arg1) - ret0, _ := ret[0].(*state.Staker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingValidator indicates an expected call of GetPendingValidator. -func (mr *ChainMockRecorder) GetPendingValidator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*Chain)(nil).GetPendingValidator), arg0, arg1) -} - -// GetSubnetManager mocks base method. -func (m *Chain) GetSubnetManager(arg0 ids.ID) (ids.ID, []byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetManager", arg0) - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].([]byte) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetSubnetManager indicates an expected call of GetSubnetManager. -func (mr *ChainMockRecorder) GetSubnetManager(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*Chain)(nil).GetSubnetManager), arg0) -} - -// GetSubnetOwner mocks base method. -func (m *Chain) GetSubnetOwner(arg0 ids.ID) (fx.Owner, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetOwner", arg0) - ret0, _ := ret[0].(fx.Owner) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubnetOwner indicates an expected call of GetSubnetOwner. -func (mr *ChainMockRecorder) GetSubnetOwner(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*Chain)(nil).GetSubnetOwner), arg0) -} - -// GetSubnetTransformation mocks base method. -func (m *Chain) GetSubnetTransformation(arg0 ids.ID) (*txs.Tx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetTransformation", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubnetTransformation indicates an expected call of GetSubnetTransformation. -func (mr *ChainMockRecorder) GetSubnetTransformation(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*Chain)(nil).GetSubnetTransformation), arg0) -} - -// GetTimestamp mocks base method. -func (m *Chain) GetTimestamp() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTimestamp") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// GetTimestamp indicates an expected call of GetTimestamp. -func (mr *ChainMockRecorder) GetTimestamp() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*Chain)(nil).GetTimestamp)) -} - -// GetTx mocks base method. -func (m *Chain) GetTx(arg0 ids.ID) (*txs.Tx, status.Status, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTx", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(status.Status) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetTx indicates an expected call of GetTx. -func (mr *ChainMockRecorder) GetTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*Chain)(nil).GetTx), arg0) -} - -// GetUTXO mocks base method. -func (m *Chain) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUTXO", arg0) - ret0, _ := ret[0].(*avax.UTXO) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUTXO indicates an expected call of GetUTXO. -func (mr *ChainMockRecorder) GetUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*Chain)(nil).GetUTXO), arg0) -} - -// PutCurrentDelegator mocks base method. -func (m *Chain) PutCurrentDelegator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentDelegator", arg0) -} - -// PutCurrentDelegator indicates an expected call of PutCurrentDelegator. -func (mr *ChainMockRecorder) PutCurrentDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*Chain)(nil).PutCurrentDelegator), arg0) -} - -// PutCurrentValidator mocks base method. -func (m *Chain) PutCurrentValidator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentValidator", arg0) -} - -// PutCurrentValidator indicates an expected call of PutCurrentValidator. -func (mr *ChainMockRecorder) PutCurrentValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*Chain)(nil).PutCurrentValidator), arg0) -} - -// PutPendingDelegator mocks base method. -func (m *Chain) PutPendingDelegator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingDelegator", arg0) -} - -// PutPendingDelegator indicates an expected call of PutPendingDelegator. -func (mr *ChainMockRecorder) PutPendingDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*Chain)(nil).PutPendingDelegator), arg0) -} - -// PutPendingValidator mocks base method. -func (m *Chain) PutPendingValidator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingValidator", arg0) -} - -// PutPendingValidator indicates an expected call of PutPendingValidator. -func (mr *ChainMockRecorder) PutPendingValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*Chain)(nil).PutPendingValidator), arg0) -} - -// SetCurrentSupply mocks base method. -func (m *Chain) SetCurrentSupply(arg0 ids.ID, arg1 uint64) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetCurrentSupply", arg0, arg1) -} - -// SetCurrentSupply indicates an expected call of SetCurrentSupply. -func (mr *ChainMockRecorder) SetCurrentSupply(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*Chain)(nil).SetCurrentSupply), arg0, arg1) -} - -// SetDelegateeReward mocks base method. -func (m *Chain) SetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID, arg2 uint64) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetDelegateeReward", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetDelegateeReward indicates an expected call of SetDelegateeReward. -func (mr *ChainMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*Chain)(nil).SetDelegateeReward), arg0, arg1, arg2) -} - -// SetFeeState mocks base method. -func (m *Chain) SetFeeState(arg0 gas.State) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetFeeState", arg0) -} - -// SetFeeState indicates an expected call of SetFeeState. -func (mr *ChainMockRecorder) SetFeeState(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*Chain)(nil).SetFeeState), arg0) -} - -// SetSubnetManager mocks base method. -func (m *Chain) SetSubnetManager(arg0, arg1 ids.ID, arg2 []byte) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetManager", arg0, arg1, arg2) -} - -// SetSubnetManager indicates an expected call of SetSubnetManager. -func (mr *ChainMockRecorder) SetSubnetManager(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*Chain)(nil).SetSubnetManager), arg0, arg1, arg2) -} - -// SetSubnetOwner mocks base method. -func (m *Chain) SetSubnetOwner(arg0 ids.ID, arg1 fx.Owner) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetOwner", arg0, arg1) -} - -// SetSubnetOwner indicates an expected call of SetSubnetOwner. -func (mr *ChainMockRecorder) SetSubnetOwner(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*Chain)(nil).SetSubnetOwner), arg0, arg1) -} - -// SetTimestamp mocks base method. -func (m *Chain) SetTimestamp(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimestamp", arg0) -} - -// SetTimestamp indicates an expected call of SetTimestamp. -func (mr *ChainMockRecorder) SetTimestamp(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*Chain)(nil).SetTimestamp), arg0) -} diff --git a/vms/platformvm/state/statemock/diff.go b/vms/platformvm/state/statemock/diff.go deleted file mode 100644 index 350326ffb47c..000000000000 --- a/vms/platformvm/state/statemock/diff.go +++ /dev/null @@ -1,540 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/vms/platformvm/state (interfaces: Diff) -// -// Generated by this command: -// -// mockgen -package=statemock -destination=vms/platformvm/state/statemock/diff.go -mock_names=Diff=Diff github.com/ava-labs/avalanchego/vms/platformvm/state Diff -// - -// Package statemock is a generated GoMock package. -package statemock - -import ( - reflect "reflect" - time "time" - - ids "github.com/ava-labs/avalanchego/ids" - avax "github.com/ava-labs/avalanchego/vms/components/avax" - gas "github.com/ava-labs/avalanchego/vms/components/gas" - fx "github.com/ava-labs/avalanchego/vms/platformvm/fx" - state "github.com/ava-labs/avalanchego/vms/platformvm/state" - status "github.com/ava-labs/avalanchego/vms/platformvm/status" - txs "github.com/ava-labs/avalanchego/vms/platformvm/txs" - gomock "go.uber.org/mock/gomock" -) - -// Diff is a mock of Diff interface. -type Diff struct { - ctrl *gomock.Controller - recorder *DiffMockRecorder -} - -// DiffMockRecorder is the mock recorder for Diff. -type DiffMockRecorder struct { - mock *Diff -} - -// NewDiff creates a new mock instance. -func NewDiff(ctrl *gomock.Controller) *Diff { - mock := &Diff{ctrl: ctrl} - mock.recorder = &DiffMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *Diff) EXPECT() *DiffMockRecorder { - return m.recorder -} - -// AddChain mocks base method. -func (m *Diff) AddChain(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddChain", arg0) -} - -// AddChain indicates an expected call of AddChain. -func (mr *DiffMockRecorder) AddChain(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddChain", reflect.TypeOf((*Diff)(nil).AddChain), arg0) -} - -// AddRewardUTXO mocks base method. -func (m *Diff) AddRewardUTXO(arg0 ids.ID, arg1 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddRewardUTXO", arg0, arg1) -} - -// AddRewardUTXO indicates an expected call of AddRewardUTXO. -func (mr *DiffMockRecorder) AddRewardUTXO(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddRewardUTXO", reflect.TypeOf((*Diff)(nil).AddRewardUTXO), arg0, arg1) -} - -// AddSubnet mocks base method. -func (m *Diff) AddSubnet(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnet", arg0) -} - -// AddSubnet indicates an expected call of AddSubnet. -func (mr *DiffMockRecorder) AddSubnet(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnet", reflect.TypeOf((*Diff)(nil).AddSubnet), arg0) -} - -// AddSubnetTransformation mocks base method. -func (m *Diff) AddSubnetTransformation(arg0 *txs.Tx) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddSubnetTransformation", arg0) -} - -// AddSubnetTransformation indicates an expected call of AddSubnetTransformation. -func (mr *DiffMockRecorder) AddSubnetTransformation(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddSubnetTransformation", reflect.TypeOf((*Diff)(nil).AddSubnetTransformation), arg0) -} - -// AddTx mocks base method. -func (m *Diff) AddTx(arg0 *txs.Tx, arg1 status.Status) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddTx", arg0, arg1) -} - -// AddTx indicates an expected call of AddTx. -func (mr *DiffMockRecorder) AddTx(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTx", reflect.TypeOf((*Diff)(nil).AddTx), arg0, arg1) -} - -// AddUTXO mocks base method. -func (m *Diff) AddUTXO(arg0 *avax.UTXO) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "AddUTXO", arg0) -} - -// AddUTXO indicates an expected call of AddUTXO. -func (mr *DiffMockRecorder) AddUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddUTXO", reflect.TypeOf((*Diff)(nil).AddUTXO), arg0) -} - -// Apply mocks base method. -func (m *Diff) Apply(arg0 state.Chain) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "Apply", arg0) - ret0, _ := ret[0].(error) - return ret0 -} - -// Apply indicates an expected call of Apply. -func (mr *DiffMockRecorder) Apply(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Apply", reflect.TypeOf((*Diff)(nil).Apply), arg0) -} - -// DeleteCurrentDelegator mocks base method. -func (m *Diff) DeleteCurrentDelegator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentDelegator", arg0) -} - -// DeleteCurrentDelegator indicates an expected call of DeleteCurrentDelegator. -func (mr *DiffMockRecorder) DeleteCurrentDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentDelegator", reflect.TypeOf((*Diff)(nil).DeleteCurrentDelegator), arg0) -} - -// DeleteCurrentValidator mocks base method. -func (m *Diff) DeleteCurrentValidator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteCurrentValidator", arg0) -} - -// DeleteCurrentValidator indicates an expected call of DeleteCurrentValidator. -func (mr *DiffMockRecorder) DeleteCurrentValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteCurrentValidator", reflect.TypeOf((*Diff)(nil).DeleteCurrentValidator), arg0) -} - -// DeletePendingDelegator mocks base method. -func (m *Diff) DeletePendingDelegator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingDelegator", arg0) -} - -// DeletePendingDelegator indicates an expected call of DeletePendingDelegator. -func (mr *DiffMockRecorder) DeletePendingDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingDelegator", reflect.TypeOf((*Diff)(nil).DeletePendingDelegator), arg0) -} - -// DeletePendingValidator mocks base method. -func (m *Diff) DeletePendingValidator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeletePendingValidator", arg0) -} - -// DeletePendingValidator indicates an expected call of DeletePendingValidator. -func (mr *DiffMockRecorder) DeletePendingValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePendingValidator", reflect.TypeOf((*Diff)(nil).DeletePendingValidator), arg0) -} - -// DeleteUTXO mocks base method. -func (m *Diff) DeleteUTXO(arg0 ids.ID) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "DeleteUTXO", arg0) -} - -// DeleteUTXO indicates an expected call of DeleteUTXO. -func (mr *DiffMockRecorder) DeleteUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteUTXO", reflect.TypeOf((*Diff)(nil).DeleteUTXO), arg0) -} - -// GetCurrentDelegatorIterator mocks base method. -func (m *Diff) GetCurrentDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (state.StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentDelegatorIterator", arg0, arg1) - ret0, _ := ret[0].(state.StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentDelegatorIterator indicates an expected call of GetCurrentDelegatorIterator. -func (mr *DiffMockRecorder) GetCurrentDelegatorIterator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentDelegatorIterator", reflect.TypeOf((*Diff)(nil).GetCurrentDelegatorIterator), arg0, arg1) -} - -// GetCurrentStakerIterator mocks base method. -func (m *Diff) GetCurrentStakerIterator() (state.StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentStakerIterator") - ret0, _ := ret[0].(state.StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentStakerIterator indicates an expected call of GetCurrentStakerIterator. -func (mr *DiffMockRecorder) GetCurrentStakerIterator() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentStakerIterator", reflect.TypeOf((*Diff)(nil).GetCurrentStakerIterator)) -} - -// GetCurrentSupply mocks base method. -func (m *Diff) GetCurrentSupply(arg0 ids.ID) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentSupply", arg0) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentSupply indicates an expected call of GetCurrentSupply. -func (mr *DiffMockRecorder) GetCurrentSupply(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentSupply", reflect.TypeOf((*Diff)(nil).GetCurrentSupply), arg0) -} - -// GetCurrentValidator mocks base method. -func (m *Diff) GetCurrentValidator(arg0 ids.ID, arg1 ids.NodeID) (*state.Staker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetCurrentValidator", arg0, arg1) - ret0, _ := ret[0].(*state.Staker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetCurrentValidator indicates an expected call of GetCurrentValidator. -func (mr *DiffMockRecorder) GetCurrentValidator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCurrentValidator", reflect.TypeOf((*Diff)(nil).GetCurrentValidator), arg0, arg1) -} - -// GetDelegateeReward mocks base method. -func (m *Diff) GetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID) (uint64, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetDelegateeReward", arg0, arg1) - ret0, _ := ret[0].(uint64) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetDelegateeReward indicates an expected call of GetDelegateeReward. -func (mr *DiffMockRecorder) GetDelegateeReward(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetDelegateeReward", reflect.TypeOf((*Diff)(nil).GetDelegateeReward), arg0, arg1) -} - -// GetFeeState mocks base method. -func (m *Diff) GetFeeState() gas.State { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetFeeState") - ret0, _ := ret[0].(gas.State) - return ret0 -} - -// GetFeeState indicates an expected call of GetFeeState. -func (mr *DiffMockRecorder) GetFeeState() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFeeState", reflect.TypeOf((*Diff)(nil).GetFeeState)) -} - -// GetPendingDelegatorIterator mocks base method. -func (m *Diff) GetPendingDelegatorIterator(arg0 ids.ID, arg1 ids.NodeID) (state.StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingDelegatorIterator", arg0, arg1) - ret0, _ := ret[0].(state.StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingDelegatorIterator indicates an expected call of GetPendingDelegatorIterator. -func (mr *DiffMockRecorder) GetPendingDelegatorIterator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingDelegatorIterator", reflect.TypeOf((*Diff)(nil).GetPendingDelegatorIterator), arg0, arg1) -} - -// GetPendingStakerIterator mocks base method. -func (m *Diff) GetPendingStakerIterator() (state.StakerIterator, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingStakerIterator") - ret0, _ := ret[0].(state.StakerIterator) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingStakerIterator indicates an expected call of GetPendingStakerIterator. -func (mr *DiffMockRecorder) GetPendingStakerIterator() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingStakerIterator", reflect.TypeOf((*Diff)(nil).GetPendingStakerIterator)) -} - -// GetPendingValidator mocks base method. -func (m *Diff) GetPendingValidator(arg0 ids.ID, arg1 ids.NodeID) (*state.Staker, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetPendingValidator", arg0, arg1) - ret0, _ := ret[0].(*state.Staker) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetPendingValidator indicates an expected call of GetPendingValidator. -func (mr *DiffMockRecorder) GetPendingValidator(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPendingValidator", reflect.TypeOf((*Diff)(nil).GetPendingValidator), arg0, arg1) -} - -// GetSubnetManager mocks base method. -func (m *Diff) GetSubnetManager(arg0 ids.ID) (ids.ID, []byte, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetManager", arg0) - ret0, _ := ret[0].(ids.ID) - ret1, _ := ret[1].([]byte) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetSubnetManager indicates an expected call of GetSubnetManager. -func (mr *DiffMockRecorder) GetSubnetManager(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetManager", reflect.TypeOf((*Diff)(nil).GetSubnetManager), arg0) -} - -// GetSubnetOwner mocks base method. -func (m *Diff) GetSubnetOwner(arg0 ids.ID) (fx.Owner, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetOwner", arg0) - ret0, _ := ret[0].(fx.Owner) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubnetOwner indicates an expected call of GetSubnetOwner. -func (mr *DiffMockRecorder) GetSubnetOwner(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetOwner", reflect.TypeOf((*Diff)(nil).GetSubnetOwner), arg0) -} - -// GetSubnetTransformation mocks base method. -func (m *Diff) GetSubnetTransformation(arg0 ids.ID) (*txs.Tx, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetSubnetTransformation", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetSubnetTransformation indicates an expected call of GetSubnetTransformation. -func (mr *DiffMockRecorder) GetSubnetTransformation(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSubnetTransformation", reflect.TypeOf((*Diff)(nil).GetSubnetTransformation), arg0) -} - -// GetTimestamp mocks base method. -func (m *Diff) GetTimestamp() time.Time { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTimestamp") - ret0, _ := ret[0].(time.Time) - return ret0 -} - -// GetTimestamp indicates an expected call of GetTimestamp. -func (mr *DiffMockRecorder) GetTimestamp() *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTimestamp", reflect.TypeOf((*Diff)(nil).GetTimestamp)) -} - -// GetTx mocks base method. -func (m *Diff) GetTx(arg0 ids.ID) (*txs.Tx, status.Status, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetTx", arg0) - ret0, _ := ret[0].(*txs.Tx) - ret1, _ := ret[1].(status.Status) - ret2, _ := ret[2].(error) - return ret0, ret1, ret2 -} - -// GetTx indicates an expected call of GetTx. -func (mr *DiffMockRecorder) GetTx(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetTx", reflect.TypeOf((*Diff)(nil).GetTx), arg0) -} - -// GetUTXO mocks base method. -func (m *Diff) GetUTXO(arg0 ids.ID) (*avax.UTXO, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetUTXO", arg0) - ret0, _ := ret[0].(*avax.UTXO) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetUTXO indicates an expected call of GetUTXO. -func (mr *DiffMockRecorder) GetUTXO(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUTXO", reflect.TypeOf((*Diff)(nil).GetUTXO), arg0) -} - -// PutCurrentDelegator mocks base method. -func (m *Diff) PutCurrentDelegator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentDelegator", arg0) -} - -// PutCurrentDelegator indicates an expected call of PutCurrentDelegator. -func (mr *DiffMockRecorder) PutCurrentDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentDelegator", reflect.TypeOf((*Diff)(nil).PutCurrentDelegator), arg0) -} - -// PutCurrentValidator mocks base method. -func (m *Diff) PutCurrentValidator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentValidator", arg0) -} - -// PutCurrentValidator indicates an expected call of PutCurrentValidator. -func (mr *DiffMockRecorder) PutCurrentValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutCurrentValidator", reflect.TypeOf((*Diff)(nil).PutCurrentValidator), arg0) -} - -// PutPendingDelegator mocks base method. -func (m *Diff) PutPendingDelegator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingDelegator", arg0) -} - -// PutPendingDelegator indicates an expected call of PutPendingDelegator. -func (mr *DiffMockRecorder) PutPendingDelegator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingDelegator", reflect.TypeOf((*Diff)(nil).PutPendingDelegator), arg0) -} - -// PutPendingValidator mocks base method. -func (m *Diff) PutPendingValidator(arg0 *state.Staker) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingValidator", arg0) -} - -// PutPendingValidator indicates an expected call of PutPendingValidator. -func (mr *DiffMockRecorder) PutPendingValidator(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PutPendingValidator", reflect.TypeOf((*Diff)(nil).PutPendingValidator), arg0) -} - -// SetCurrentSupply mocks base method. -func (m *Diff) SetCurrentSupply(arg0 ids.ID, arg1 uint64) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetCurrentSupply", arg0, arg1) -} - -// SetCurrentSupply indicates an expected call of SetCurrentSupply. -func (mr *DiffMockRecorder) SetCurrentSupply(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCurrentSupply", reflect.TypeOf((*Diff)(nil).SetCurrentSupply), arg0, arg1) -} - -// SetDelegateeReward mocks base method. -func (m *Diff) SetDelegateeReward(arg0 ids.ID, arg1 ids.NodeID, arg2 uint64) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "SetDelegateeReward", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// SetDelegateeReward indicates an expected call of SetDelegateeReward. -func (mr *DiffMockRecorder) SetDelegateeReward(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetDelegateeReward", reflect.TypeOf((*Diff)(nil).SetDelegateeReward), arg0, arg1, arg2) -} - -// SetFeeState mocks base method. -func (m *Diff) SetFeeState(arg0 gas.State) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetFeeState", arg0) -} - -// SetFeeState indicates an expected call of SetFeeState. -func (mr *DiffMockRecorder) SetFeeState(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFeeState", reflect.TypeOf((*Diff)(nil).SetFeeState), arg0) -} - -// SetSubnetManager mocks base method. -func (m *Diff) SetSubnetManager(arg0, arg1 ids.ID, arg2 []byte) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetManager", arg0, arg1, arg2) -} - -// SetSubnetManager indicates an expected call of SetSubnetManager. -func (mr *DiffMockRecorder) SetSubnetManager(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetManager", reflect.TypeOf((*Diff)(nil).SetSubnetManager), arg0, arg1, arg2) -} - -// SetSubnetOwner mocks base method. -func (m *Diff) SetSubnetOwner(arg0 ids.ID, arg1 fx.Owner) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetSubnetOwner", arg0, arg1) -} - -// SetSubnetOwner indicates an expected call of SetSubnetOwner. -func (mr *DiffMockRecorder) SetSubnetOwner(arg0, arg1 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetSubnetOwner", reflect.TypeOf((*Diff)(nil).SetSubnetOwner), arg0, arg1) -} - -// SetTimestamp mocks base method. -func (m *Diff) SetTimestamp(arg0 time.Time) { - m.ctrl.T.Helper() - m.ctrl.Call(m, "SetTimestamp", arg0) -} - -// SetTimestamp indicates an expected call of SetTimestamp. -func (mr *DiffMockRecorder) SetTimestamp(arg0 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetTimestamp", reflect.TypeOf((*Diff)(nil).SetTimestamp), arg0) -} diff --git a/vms/platformvm/state/tree_iterator.go b/vms/platformvm/state/tree_iterator.go deleted file mode 100644 index 920bc1377902..000000000000 --- a/vms/platformvm/state/tree_iterator.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package state - -import ( - "sync" - - "github.com/google/btree" -) - -const defaultTreeDegree = 2 - -var _ StakerIterator = (*treeIterator)(nil) - -type treeIterator struct { - current *Staker - next chan *Staker - releaseOnce sync.Once - release chan struct{} - wg sync.WaitGroup -} - -// NewTreeIterator returns a new iterator of the stakers in [tree] in ascending -// order. Note that it isn't safe to modify [tree] while iterating over it. -func NewTreeIterator(tree *btree.BTreeG[*Staker]) StakerIterator { - if tree == nil { - return EmptyIterator - } - it := &treeIterator{ - next: make(chan *Staker), - release: make(chan struct{}), - } - it.wg.Add(1) - go func() { - defer it.wg.Done() - tree.Ascend(func(i *Staker) bool { - select { - case it.next <- i: - return true - case <-it.release: - return false - } - }) - close(it.next) - }() - return it -} - -func (i *treeIterator) Next() bool { - next, ok := <-i.next - i.current = next - return ok -} - -func (i *treeIterator) Value() *Staker { - return i.current -} - -func (i *treeIterator) Release() { - i.releaseOnce.Do(func() { - close(i.release) - }) - i.wg.Wait() -} diff --git a/vms/platformvm/txs/executor/staker_tx_verification_test.go b/vms/platformvm/txs/executor/staker_tx_verification_test.go index d2f85b8d87e7..037d789a8eb2 100644 --- a/vms/platformvm/txs/executor/staker_tx_verification_test.go +++ b/vms/platformvm/txs/executor/staker_tx_verification_test.go @@ -22,7 +22,6 @@ import ( "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/platformvm/utxo/utxomock" @@ -120,7 +119,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := statemock.NewChain(ctrl) + mockState := state.NewMockChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now) return mockState }, @@ -144,7 +143,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := statemock.NewChain(ctrl) + mockState := state.NewMockChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after Durango fork activation since now.After(activeForkTime) return mockState }, @@ -170,7 +169,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) state.EXPECT().GetTimestamp().Return(verifiedTx.StartTime()).Times(2) return state }, @@ -196,7 +195,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) state.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -225,7 +224,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) state.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -254,7 +253,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) state.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -284,7 +283,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) state.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -317,7 +316,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) state.EXPECT().GetTimestamp().Return(time.Unix(1, 0)).Times(2) // chain time is after fork activation since time.Unix(1, 0).After(activeForkTime) state.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return state @@ -350,7 +349,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := statemock.NewChain(ctrl) + mockState := state.NewMockChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) return mockState @@ -385,7 +384,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := statemock.NewChain(ctrl) + mockState := state.NewMockChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(2) // chain time is after latest fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) // State says validator exists @@ -414,7 +413,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := statemock.NewChain(ctrl) + mockState := state.NewMockChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(3) // chain time is after latest fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) mockState.EXPECT().GetCurrentValidator(subnetID, verifiedTx.NodeID()).Return(nil, database.ErrNotFound) @@ -463,7 +462,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := statemock.NewChain(ctrl) + mockState := state.NewMockChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(3) // chain time is after latest fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) mockState.EXPECT().GetCurrentValidator(subnetID, verifiedTx.NodeID()).Return(nil, database.ErrNotFound) @@ -511,7 +510,7 @@ func TestVerifyAddPermissionlessValidatorTx(t *testing.T) { } }, stateF: func(ctrl *gomock.Controller) state.Chain { - mockState := statemock.NewChain(ctrl) + mockState := state.NewMockChain(ctrl) mockState.EXPECT().GetTimestamp().Return(now).Times(3) // chain time is after Durango fork activation since now.After(activeForkTime) mockState.EXPECT().GetSubnetTransformation(subnetID).Return(&transformTx, nil) mockState.EXPECT().GetCurrentValidator(subnetID, verifiedTx.NodeID()).Return(nil, database.ErrNotFound) @@ -600,7 +599,7 @@ func TestGetValidatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) state.EXPECT().GetSubnetTransformation(subnetID).Return(nil, errTest) return state }, @@ -612,7 +611,7 @@ func TestGetValidatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) tx := &txs.Tx{ Unsigned: &txs.AddDelegatorTx{}, } @@ -627,7 +626,7 @@ func TestGetValidatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) tx := &txs.Tx{ Unsigned: &txs.TransformSubnetTx{ AssetID: customAssetID, @@ -717,7 +716,7 @@ func TestGetDelegatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) state.EXPECT().GetSubnetTransformation(subnetID).Return(nil, errTest) return state }, @@ -729,7 +728,7 @@ func TestGetDelegatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) tx := &txs.Tx{ Unsigned: &txs.AddDelegatorTx{}, } @@ -744,7 +743,7 @@ func TestGetDelegatorRules(t *testing.T) { subnetID: subnetID, backend: nil, chainStateF: func(ctrl *gomock.Controller) state.Chain { - state := statemock.NewChain(ctrl) + state := state.NewMockChain(ctrl) tx := &txs.Tx{ Unsigned: &txs.TransformSubnetTx{ AssetID: customAssetID, diff --git a/vms/platformvm/txs/executor/standard_tx_executor_test.go b/vms/platformvm/txs/executor/standard_tx_executor_test.go index e0400698fb30..d6f16a981c7d 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor_test.go +++ b/vms/platformvm/txs/executor/standard_tx_executor_test.go @@ -31,7 +31,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/state/statemock" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/utxo/utxomock" @@ -1726,7 +1725,7 @@ type removeSubnetValidatorTxVerifyEnv struct { flowChecker *utxomock.Verifier unsignedTx *txs.RemoveSubnetValidatorTx tx *txs.Tx - state *statemock.Diff + state *state.MockDiff staker *state.Staker } @@ -1739,7 +1738,7 @@ func newValidRemoveSubnetValidatorTxVerifyEnv(t *testing.T, ctrl *gomock.Control mockFx := fxmock.NewFx(ctrl) mockFlowChecker := utxomock.NewVerifier(ctrl) unsignedTx, tx := newRemoveSubnetValidatorTx(t) - mockState := statemock.NewDiff(ctrl) + mockState := state.NewMockDiff(ctrl) return removeSubnetValidatorTxVerifyEnv{ latestForkTime: now, fx: mockFx, @@ -1808,7 +1807,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) // Setting the subnet ID to the Primary Network ID makes the tx fail syntactic verification env.tx.Unsigned.(*txs.RemoveSubnetValidatorTx).Subnet = constants.PrimaryNetworkID - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() cfg := &config.Config{ @@ -1836,7 +1835,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { name: "node isn't a validator of the subnet", newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(nil, database.ErrNotFound) env.state.EXPECT().GetPendingValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(nil, database.ErrNotFound) @@ -1901,7 +1900,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) // Remove credentials env.tx.Creds = nil - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) @@ -1930,7 +1929,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { name: "can't find subnet", newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(nil, database.ErrNotFound) @@ -1960,7 +1959,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { name: "no permission to remove validator", newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) subnetOwner := fxmock.NewOwner(ctrl) @@ -1992,7 +1991,7 @@ func TestStandardExecutorRemoveSubnetValidatorTx(t *testing.T) { name: "flow checker failed", newExecutor: func(ctrl *gomock.Controller) (*txs.RemoveSubnetValidatorTx, *StandardTxExecutor) { env := newValidRemoveSubnetValidatorTxVerifyEnv(t, ctrl) - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetCurrentValidator(env.unsignedTx.Subnet, env.unsignedTx.NodeID).Return(env.staker, nil) subnetOwner := fxmock.NewOwner(ctrl) @@ -2143,7 +2142,7 @@ type transformSubnetTxVerifyEnv struct { flowChecker *utxomock.Verifier unsignedTx *txs.TransformSubnetTx tx *txs.Tx - state *statemock.Diff + state *state.MockDiff staker *state.Staker } @@ -2156,7 +2155,7 @@ func newValidTransformSubnetTxVerifyEnv(t *testing.T, ctrl *gomock.Controller) t mockFx := fxmock.NewFx(ctrl) mockFlowChecker := utxomock.NewVerifier(ctrl) unsignedTx, tx := newTransformSubnetTx(t) - mockState := statemock.NewDiff(ctrl) + mockState := state.NewMockDiff(ctrl) return transformSubnetTxVerifyEnv{ latestForkTime: now, fx: mockFx, @@ -2185,7 +2184,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) // Setting the tx to nil makes the tx fail syntactic verification env.tx.Unsigned = (*txs.TransformSubnetTx)(nil) - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() cfg := &config.Config{ @@ -2214,7 +2213,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { newExecutor: func(ctrl *gomock.Controller) (*txs.TransformSubnetTx, *StandardTxExecutor) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) env.unsignedTx.MaxStakeDuration = math.MaxUint32 - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() cfg := &config.Config{ @@ -2244,7 +2243,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) // Remove credentials env.tx.Creds = nil - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() cfg := &config.Config{ @@ -2274,7 +2273,7 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { name: "flow checker failed", newExecutor: func(ctrl *gomock.Controller) (*txs.TransformSubnetTx, *StandardTxExecutor) { env := newValidTransformSubnetTxVerifyEnv(t, ctrl) - env.state = statemock.NewDiff(ctrl) + env.state = state.NewMockDiff(ctrl) subnetOwner := fxmock.NewOwner(ctrl) env.state.EXPECT().GetTimestamp().Return(env.latestForkTime).AnyTimes() env.state.EXPECT().GetSubnetOwner(env.unsignedTx.Subnet).Return(subnetOwner, nil) From 85ab9693d28fa243d1121df59e555693be4cc0ad Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Thu, 22 Aug 2024 22:28:45 -0400 Subject: [PATCH 42/69] Remove duplicate genesis creations in P-chain unit tests (#3318) --- vms/platformvm/block/builder/builder_test.go | 25 +- vms/platformvm/block/builder/helpers_test.go | 107 +----- .../block/builder/standard_block_test.go | 9 +- vms/platformvm/block/executor/helpers_test.go | 112 +------ .../block/executor/proposal_block_test.go | 98 +++--- .../block/executor/standard_block_test.go | 43 +-- .../block/executor/verifier_test.go | 9 +- vms/platformvm/block/parse_test.go | 4 +- vms/platformvm/genesis/genesistest/genesis.go | 204 ++++++++---- vms/platformvm/service_test.go | 138 +++++--- vms/platformvm/state/stakers_test.go | 2 +- vms/platformvm/state/state_test.go | 20 +- vms/platformvm/state/statetest/state.go | 9 +- vms/platformvm/txs/add_delegator_test.go | 12 +- .../txs/add_subnet_validator_test.go | 4 +- vms/platformvm/txs/add_validator_test.go | 12 +- vms/platformvm/txs/create_chain_test.go | 2 +- .../txs/executor/advance_time_test.go | 58 ++-- .../txs/executor/create_chain_test.go | 13 +- .../txs/executor/create_subnet_test.go | 11 +- vms/platformvm/txs/executor/export_test.go | 7 +- vms/platformvm/txs/executor/helpers_test.go | 121 ++----- vms/platformvm/txs/executor/import_test.go | 4 +- .../txs/executor/proposal_tx_executor_test.go | 159 ++++----- .../txs/executor/reward_validator_test.go | 27 +- .../txs/executor/standard_tx_executor_test.go | 213 ++++++------ vms/platformvm/validator_set_property_test.go | 108 +----- .../validators/manager_benchmark_test.go | 55 +--- vms/platformvm/vm_regression_test.go | 123 ++++--- vms/platformvm/vm_test.go | 308 ++++++------------ 30 files changed, 823 insertions(+), 1194 deletions(-) diff --git a/vms/platformvm/block/builder/builder_test.go b/vms/platformvm/block/builder/builder_test.go index 7c8213124d50..2d83b37615d0 100644 --- a/vms/platformvm/block/builder/builder_test.go +++ b/vms/platformvm/block/builder/builder_test.go @@ -21,6 +21,7 @@ import ( "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/platformvm/block" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -113,7 +114,7 @@ func TestBuildBlockShouldReward(t *testing.T) { require.NoError(err) // Create a valid [AddPermissionlessValidatorTx] - builder, txSigner := env.factory.NewWallet(preFundedKeys[0]) + builder, txSigner := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -128,16 +129,16 @@ func TestBuildBlockShouldReward(t *testing.T) { env.ctx.AVAXAssetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, reward.PercentDenominator, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -322,7 +323,7 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) - builder1, signer1 := env.factory.NewWallet(preFundedKeys[0]) + builder1, signer1 := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx1, err := builder1.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -337,16 +338,16 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { env.ctx.AVAXAssetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, reward.PercentDenominator, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -363,7 +364,7 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { sk, err = bls.NewSecretKey() require.NoError(err) - builder2, signer2 := env.factory.NewWallet(preFundedKeys[2]) + builder2, signer2 := env.factory.NewWallet(genesistest.DefaultFundedKeys[2]) utx2, err := builder2.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -378,16 +379,16 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { env.ctx.AVAXAssetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[2].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[2].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, }, reward.PercentDenominator, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[2].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, }), ) require.NoError(err) diff --git a/vms/platformvm/block/builder/helpers_test.go b/vms/platformvm/block/builder/helpers_test.go index 1d7436485e17..79b4453f6aa0 100644 --- a/vms/platformvm/block/builder/helpers_test.go +++ b/vms/platformvm/block/builder/helpers_test.go @@ -28,16 +28,12 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/utils/formatting" - "github.com/ava-labs/avalanchego/utils/formatting/address" - "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" - "github.com/ava-labs/avalanchego/vms/platformvm/api" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/fx" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/network" "github.com/ava-labs/avalanchego/vms/platformvm/reward" @@ -59,34 +55,16 @@ import ( ) const ( - defaultWeight = 10000 - trackChecksum = false -) - -var ( defaultMinStakingDuration = 24 * time.Hour defaultMaxStakingDuration = 365 * 24 * time.Hour - defaultGenesisTime = time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC) - defaultValidateStartTime = defaultGenesisTime - defaultValidateEndTime = defaultValidateStartTime.Add(10 * defaultMinStakingDuration) - defaultMinValidatorStake = 5 * units.MilliAvax - defaultBalance = 100 * defaultMinValidatorStake - preFundedKeys = secp256k1.TestKeys() - defaultTxFee = uint64(100) - testSubnet1 *txs.Tx - testSubnet1ControlKeys = preFundedKeys[0:3] - - // Node IDs of genesis validators. Initialized in init function - genesisNodeIDs []ids.NodeID + defaultTxFee = 100 * units.NanoAvax ) -func init() { - genesisNodeIDs = make([]ids.NodeID, len(preFundedKeys)) - for i := range preFundedKeys { - genesisNodeIDs[i] = ids.GenerateTestNodeID() - } -} +var ( + testSubnet1 *txs.Tx + testSubnet1ControlKeys = genesistest.DefaultFundedKeys[0:3] +) type mutableSharedMemory struct { atomic.SharedMemory @@ -141,7 +119,7 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { //nolint:un rewardsCalc := reward.NewCalculator(res.config.RewardConfig) res.state = statetest.New(t, statetest.Config{ DB: res.baseDB, - Genesis: buildGenesisTest(t, res.ctx), + Genesis: genesistest.NewBytes(t, genesistest.Config{}), Validators: res.config.Validators, Context: res.ctx, Rewards: rewardsCalc, @@ -232,19 +210,19 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { //nolint:un func addSubnet(t *testing.T, env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 2, Addrs: []ids.ShortID{ - preFundedKeys[0].PublicKey().Address(), - preFundedKeys[1].PublicKey().Address(), - preFundedKeys[2].PublicKey().Address(), + genesistest.DefaultFundedKeys[0].Address(), + genesistest.DefaultFundedKeys[1].Address(), + genesistest.DefaultFundedKeys[2].Address(), }, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -275,7 +253,7 @@ func defaultConfig(f upgradetest.Fork) *config.Config { upgradetest.SetTimesTo( &upgrades, min(f, upgradetest.ApricotPhase5), - defaultValidateEndTime, + genesistest.DefaultValidatorEndTime, ) return &config.Config{ @@ -305,7 +283,7 @@ func defaultConfig(f upgradetest.Fork) *config.Config { func defaultClock() *mockable.Clock { // set time after Banff fork (and before default nextStakerTime) clk := &mockable.Clock{} - clk.Set(defaultGenesisTime) + clk.Set(genesistest.DefaultValidatorStartTime) return clk } @@ -342,60 +320,3 @@ func defaultFx(t *testing.T, clk *mockable.Clock, log logging.Logger, isBootstra } return res } - -func buildGenesisTest(t *testing.T, ctx *snow.Context) []byte { - require := require.New(t) - - genesisUTXOs := make([]api.UTXO, len(preFundedKeys)) - for i, key := range preFundedKeys { - id := key.PublicKey().Address() - addr, err := address.FormatBech32(constants.UnitTestHRP, id.Bytes()) - require.NoError(err) - genesisUTXOs[i] = api.UTXO{ - Amount: json.Uint64(defaultBalance), - Address: addr, - } - } - - genesisValidators := make([]api.GenesisPermissionlessValidator, len(genesisNodeIDs)) - for i, nodeID := range genesisNodeIDs { - addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes()) - require.NoError(err) - genesisValidators[i] = api.GenesisPermissionlessValidator{ - GenesisValidator: api.GenesisValidator{ - StartTime: json.Uint64(defaultValidateStartTime.Unix()), - EndTime: json.Uint64(defaultValidateEndTime.Unix()), - NodeID: nodeID, - }, - RewardOwner: &api.Owner{ - Threshold: 1, - Addresses: []string{addr}, - }, - Staked: []api.UTXO{{ - Amount: json.Uint64(defaultWeight), - Address: addr, - }}, - DelegationFee: reward.PercentDenominator, - } - } - - buildGenesisArgs := api.BuildGenesisArgs{ - NetworkID: json.Uint32(constants.UnitTestID), - AvaxAssetID: ctx.AVAXAssetID, - UTXOs: genesisUTXOs, - Validators: genesisValidators, - Chains: nil, - Time: json.Uint64(defaultGenesisTime.Unix()), - InitialSupply: json.Uint64(360 * units.MegaAvax), - Encoding: formatting.Hex, - } - - buildGenesisResponse := api.BuildGenesisReply{} - platformvmSS := api.StaticService{} - require.NoError(platformvmSS.BuildGenesis(nil, &buildGenesisArgs, &buildGenesisResponse)) - - genesisBytes, err := formatting.Decode(buildGenesisResponse.Encoding, buildGenesisResponse.Bytes) - require.NoError(err) - - return genesisBytes -} diff --git a/vms/platformvm/block/builder/standard_block_test.go b/vms/platformvm/block/builder/standard_block_test.go index 6909c0efd794..e97cbee313fd 100644 --- a/vms/platformvm/block/builder/standard_block_test.go +++ b/vms/platformvm/block/builder/standard_block_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -33,7 +34,7 @@ func TestAtomicTxImports(t *testing.T) { OutputIndex: 1, } amount := uint64(70000) - recipientKey := preFundedKeys[1] + recipientKey := genesistest.DefaultFundedKeys[1] m := atomic.NewMemory(prefixdb.New([]byte{5}, env.baseDB)) @@ -46,7 +47,7 @@ func TestAtomicTxImports(t *testing.T) { Amt: amount, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{recipientKey.PublicKey().Address()}, + Addrs: []ids.ShortID{recipientKey.Address()}, }, }, } @@ -59,7 +60,7 @@ func TestAtomicTxImports(t *testing.T) { Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - recipientKey.PublicKey().Address().Bytes(), + recipientKey.Address().Bytes(), }, }}}, })) @@ -69,7 +70,7 @@ func TestAtomicTxImports(t *testing.T) { env.ctx.XChainID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{recipientKey.PublicKey().Address()}, + Addrs: []ids.ShortID{recipientKey.Address()}, }, ) require.NoError(err) diff --git a/vms/platformvm/block/executor/helpers_test.go b/vms/platformvm/block/executor/helpers_test.go index 08b1d334d4df..947fd15a8691 100644 --- a/vms/platformvm/block/executor/helpers_test.go +++ b/vms/platformvm/block/executor/helpers_test.go @@ -30,15 +30,12 @@ import ( "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/utils/formatting" - "github.com/ava-labs/avalanchego/utils/formatting/address" - "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" - "github.com/ava-labs/avalanchego/vms/platformvm/api" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/fx" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/metrics" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -61,34 +58,13 @@ const ( pending stakerStatus = iota current - defaultWeight = 10000 - trackChecksum = false -) - -var ( defaultMinStakingDuration = 24 * time.Hour defaultMaxStakingDuration = 365 * 24 * time.Hour - defaultGenesisTime = time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC) - defaultValidateStartTime = defaultGenesisTime - defaultValidateEndTime = defaultValidateStartTime.Add(10 * defaultMinStakingDuration) - defaultMinValidatorStake = 5 * units.MilliAvax - defaultBalance = 100 * defaultMinValidatorStake - preFundedKeys = secp256k1.TestKeys() - avaxAssetID = ids.ID{'y', 'e', 'e', 't'} - defaultTxFee = uint64(100) - - testSubnet1 *txs.Tx - - // Node IDs of genesis validators. Initialized in init function - genesisNodeIDs []ids.NodeID + + defaultTxFee = 100 * units.NanoAvax ) -func init() { - genesisNodeIDs = make([]ids.NodeID, len(preFundedKeys)) - for i := range preFundedKeys { - genesisNodeIDs[i] = ids.GenerateTestNodeID() - } -} +var testSubnet1 *txs.Tx type stakerStatus uint @@ -139,7 +115,6 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * m := atomic.NewMemory(atomicDB) res.ctx = snowtest.Context(t, snowtest.PChainID) - res.ctx.AVAXAssetID = avaxAssetID res.ctx.SharedMemory = m.NewSharedMemory(res.ctx.ChainID) res.fx = defaultFx(res.clk, res.ctx.Log, res.isBootstrapped.Get()) @@ -149,7 +124,7 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * if ctrl == nil { res.state = statetest.New(t, statetest.Config{ DB: res.baseDB, - Genesis: buildGenesisTest(res.ctx), + Genesis: genesistest.NewBytes(t, genesistest.Config{}), Validators: res.config.Validators, Context: res.ctx, Rewards: rewardsCalc, @@ -248,19 +223,19 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * } func addSubnet(env *environment) { - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 2, Addrs: []ids.ShortID{ - preFundedKeys[0].PublicKey().Address(), - preFundedKeys[1].PublicKey().Address(), - preFundedKeys[2].PublicKey().Address(), + genesistest.DefaultFundedKeys[0].Address(), + genesistest.DefaultFundedKeys[1].Address(), + genesistest.DefaultFundedKeys[2].Address(), }, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) if err != nil { @@ -303,7 +278,7 @@ func defaultConfig(f upgradetest.Fork) *config.Config { upgradetest.SetTimesTo( &upgrades, min(f, upgradetest.ApricotPhase5), - defaultValidateEndTime, + genesistest.DefaultValidatorEndTime, ) return &config.Config{ @@ -332,7 +307,7 @@ func defaultConfig(f upgradetest.Fork) *config.Config { func defaultClock() *mockable.Clock { clk := &mockable.Clock{} - clk.Set(defaultGenesisTime) + clk.Set(genesistest.DefaultValidatorStartTime) return clk } @@ -372,69 +347,6 @@ func defaultFx(clk *mockable.Clock, log logging.Logger, isBootstrapped bool) fx. return res } -func buildGenesisTest(ctx *snow.Context) []byte { - genesisUTXOs := make([]api.UTXO, len(preFundedKeys)) - for i, key := range preFundedKeys { - id := key.PublicKey().Address() - addr, err := address.FormatBech32(constants.UnitTestHRP, id.Bytes()) - if err != nil { - panic(err) - } - genesisUTXOs[i] = api.UTXO{ - Amount: json.Uint64(defaultBalance), - Address: addr, - } - } - - genesisValidators := make([]api.GenesisPermissionlessValidator, len(genesisNodeIDs)) - for i, nodeID := range genesisNodeIDs { - addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes()) - if err != nil { - panic(err) - } - genesisValidators[i] = api.GenesisPermissionlessValidator{ - GenesisValidator: api.GenesisValidator{ - StartTime: json.Uint64(defaultValidateStartTime.Unix()), - EndTime: json.Uint64(defaultValidateEndTime.Unix()), - NodeID: nodeID, - }, - RewardOwner: &api.Owner{ - Threshold: 1, - Addresses: []string{addr}, - }, - Staked: []api.UTXO{{ - Amount: json.Uint64(defaultWeight), - Address: addr, - }}, - DelegationFee: reward.PercentDenominator, - } - } - - buildGenesisArgs := api.BuildGenesisArgs{ - NetworkID: json.Uint32(constants.UnitTestID), - AvaxAssetID: ctx.AVAXAssetID, - UTXOs: genesisUTXOs, - Validators: genesisValidators, - Chains: nil, - Time: json.Uint64(defaultGenesisTime.Unix()), - InitialSupply: json.Uint64(360 * units.MegaAvax), - Encoding: formatting.Hex, - } - - buildGenesisResponse := api.BuildGenesisReply{} - platformvmSS := api.StaticService{} - if err := platformvmSS.BuildGenesis(nil, &buildGenesisArgs, &buildGenesisResponse); err != nil { - panic(fmt.Errorf("problem while building platform chain's genesis state: %w", err)) - } - - genesisBytes, err := formatting.Decode(buildGenesisResponse.Encoding, buildGenesisResponse.Bytes) - if err != nil { - panic(err) - } - - return genesisBytes -} - func addPendingValidator( env *environment, startTime time.Time, diff --git a/vms/platformvm/block/executor/proposal_block_test.go b/vms/platformvm/block/executor/proposal_block_test.go index db7d5b44c532..1060c1c59be0 100644 --- a/vms/platformvm/block/executor/proposal_block_test.go +++ b/vms/platformvm/block/executor/proposal_block_test.go @@ -24,6 +24,7 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -145,7 +146,7 @@ func TestBanffProposalBlockTimeVerification(t *testing.T) { env := newEnvironment(t, ctrl, upgradetest.Banff) // create parentBlock. It's a standard one for simplicity - parentTime := defaultGenesisTime + parentTime := genesistest.DefaultValidatorStartTime parentHeight := uint64(2022) banffParentBlk, err := block.NewApricotStandardBlock( @@ -375,15 +376,15 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { staker0 := staker{ nodeID: ids.BuildTestNodeID([]byte{0xf0}), rewardAddress: ids.ShortID{0xf0}, - startTime: defaultGenesisTime, + startTime: genesistest.DefaultValidatorStartTime, endTime: time.Time{}, // actual endTime depends on specific test } staker1 := staker{ nodeID: ids.BuildTestNodeID([]byte{0xf1}), rewardAddress: ids.ShortID{0xf1}, - startTime: defaultGenesisTime.Add(1 * time.Minute), - endTime: defaultGenesisTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute), + startTime: genesistest.DefaultValidatorStartTime.Add(1 * time.Minute), + endTime: genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute), } staker2 := staker{ nodeID: ids.BuildTestNodeID([]byte{0xf2}), @@ -509,25 +510,6 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { staker5.nodeID: pending, }, }, - { - description: "advance time to staker5 start", - stakers: []staker{staker1, staker2, staker3, staker4, staker5}, - advanceTimeTo: []time.Time{staker1.startTime, staker2.startTime, staker3.startTime, staker5.startTime}, - expectedStakers: map[ids.NodeID]stakerStatus{ - staker1.nodeID: current, - - // Staker2's end time matches staker5's start time, so typically - // the block builder would produce a ProposalBlock to remove - // staker2 when advancing the time. However, this test injects - // staker0 into the staker set artificially to advance the time. - // This means that staker2 is not removed by the ProposalBlock - // when advancing the time. - staker2.nodeID: current, - staker3.nodeID: current, - staker4.nodeID: current, - staker5.nodeID: current, - }, - }, } for _, test := range tests { @@ -539,7 +521,7 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) for _, staker := range test.stakers { - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: staker.nodeID, @@ -573,7 +555,7 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { } for _, subStaker := range test.subnetStakers { - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -610,7 +592,7 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance staker0.endTime = newTime - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: staker0.nodeID, @@ -717,15 +699,14 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) // Add a subnet validator to the staker set - subnetValidatorNodeID := genesisNodeIDs[0] - subnetVdr1StartTime := defaultValidateStartTime - subnetVdr1EndTime := defaultValidateStartTime.Add(defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] + subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, - Start: uint64(subnetVdr1StartTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix, End: uint64(subnetVdr1EndTime.Unix()), Wght: 1, }, @@ -752,7 +733,7 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { // The above validator is now part of the staking set // Queue a staker that joins the staker set after the above validator leaves - subnetVdr2NodeID := genesisNodeIDs[1] + subnetVdr2NodeID := genesistest.DefaultNodeIDs[1] utx, err = builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -785,12 +766,11 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance - staker0StartTime := defaultValidateStartTime staker0EndTime := subnetVdr1EndTime uVdrTx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), - Start: uint64(staker0StartTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix, End: uint64(staker0EndTime.Unix()), Wght: 10, }, @@ -876,11 +856,11 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { } // Add a subnet validator to the staker set - subnetValidatorNodeID := genesisNodeIDs[0] - subnetVdr1StartTime := defaultGenesisTime.Add(1 * time.Minute) - subnetVdr1EndTime := defaultGenesisTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) + subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] + subnetVdr1StartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Minute) + subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -911,7 +891,7 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance - staker0StartTime := defaultGenesisTime + staker0StartTime := genesistest.DefaultValidatorStartTime staker0EndTime := subnetVdr1StartTime uVdrTx, err := builder.NewAddValidatorTx( @@ -986,7 +966,7 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { // Case: Timestamp is after next validator start time // Add a pending validator - pendingValidatorStartTime := defaultGenesisTime.Add(1 * time.Second) + pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMaxStakingDuration) nodeID := ids.GenerateTestNodeID() rewardAddress := ids.GenerateTestShortID() @@ -996,15 +976,15 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { pendingValidatorEndTime, nodeID, rewardAddress, - []*secp256k1.PrivateKey{preFundedKeys[0]}, + []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) require.NoError(err) // add Staker0 (with the right end time) to state // just to allow proposalBlk issuance (with a reward Tx) - staker0StartTime := defaultGenesisTime + staker0StartTime := genesistest.DefaultValidatorStartTime staker0EndTime := pendingValidatorStartTime - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), @@ -1075,7 +1055,7 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(1 * time.Second) - builder, signer = env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1], preFundedKeys[4]) + builder, signer = env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) uDelTx, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: nodeID, @@ -1085,7 +1065,7 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, ) require.NoError(err) @@ -1106,7 +1086,7 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance staker0EndTime = pendingDelegatorStartTime - builder, signer = env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer = env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err = builder.NewAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), @@ -1181,10 +1161,10 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { // Case: Timestamp is after next validator start time // Add a pending validator - pendingValidatorStartTime := defaultGenesisTime.Add(1 * time.Second) + pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeIDKey, _ := secp256k1.NewPrivateKey() - rewardAddress := nodeIDKey.PublicKey().Address() + rewardAddress := nodeIDKey.Address() nodeID := ids.BuildTestNodeID(rewardAddress[:]) _, err := addPendingValidator( @@ -1193,15 +1173,15 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { pendingValidatorEndTime, nodeID, rewardAddress, - []*secp256k1.PrivateKey{preFundedKeys[0]}, + []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) require.NoError(err) // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance - staker0StartTime := defaultGenesisTime + staker0StartTime := genesistest.DefaultValidatorStartTime staker0EndTime := pendingValidatorStartTime - builder, txSigner := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, txSigner := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), @@ -1271,7 +1251,7 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { // Add delegator pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(defaultMinStakingDuration) - builder, txSigner = env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1], preFundedKeys[4]) + builder, txSigner = env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) uDelTx, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: nodeID, @@ -1281,7 +1261,7 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, ) require.NoError(err) @@ -1302,7 +1282,7 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance staker0EndTime = pendingDelegatorStartTime - builder, txSigner = env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, txSigner = env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err = builder.NewAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), @@ -1386,7 +1366,7 @@ func TestAddValidatorProposalBlock(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1], preFundedKeys[4]) + builder, txSigner := env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) utx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -1401,11 +1381,11 @@ func TestAddValidatorProposalBlock(t *testing.T) { env.ctx.AVAXAssetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, 10000, ) @@ -1485,11 +1465,11 @@ func TestAddValidatorProposalBlock(t *testing.T) { env.ctx.AVAXAssetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, 10000, ) diff --git a/vms/platformvm/block/executor/standard_block_test.go b/vms/platformvm/block/executor/standard_block_test.go index e0154b8c9ef0..3b9b55408ef1 100644 --- a/vms/platformvm/block/executor/standard_block_test.go +++ b/vms/platformvm/block/executor/standard_block_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" @@ -21,6 +22,7 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" @@ -143,7 +145,7 @@ func TestBanffStandardBlockTimeVerification(t *testing.T) { TxID: txID, }, Asset: avax.Asset{ - ID: avaxAssetID, + ID: snowtest.AVAXAssetID, }, Out: &secp256k1fx.TransferOutput{ Amt: env.config.StaticFeeConfig.CreateSubnetTxFee, @@ -296,7 +298,7 @@ func TestBanffStandardBlockUpdatePrimaryNetworkStakers(t *testing.T) { // Case: Timestamp is after next validator start time // Add a pending validator - pendingValidatorStartTime := defaultGenesisTime.Add(1 * time.Second) + pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeID := ids.GenerateTestNodeID() rewardAddress := ids.GenerateTestShortID() @@ -306,7 +308,7 @@ func TestBanffStandardBlockUpdatePrimaryNetworkStakers(t *testing.T) { pendingValidatorEndTime, nodeID, rewardAddress, - []*secp256k1.PrivateKey{preFundedKeys[0]}, + []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) require.NoError(err) @@ -363,8 +365,8 @@ func TestBanffStandardBlockUpdateStakers(t *testing.T) { staker1 := staker{ nodeID: ids.BuildTestNodeID([]byte{0xf1}), rewardAddress: ids.ShortID{0xf1}, - startTime: defaultGenesisTime.Add(1 * time.Minute), - endTime: defaultGenesisTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute), + startTime: genesistest.DefaultValidatorStartTime.Add(1 * time.Minute), + endTime: genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute), } staker2 := staker{ nodeID: ids.BuildTestNodeID([]byte{0xf2}), @@ -505,13 +507,13 @@ func TestBanffStandardBlockUpdateStakers(t *testing.T) { staker.endTime, staker.nodeID, staker.rewardAddress, - []*secp256k1.PrivateKey{preFundedKeys[0]}, + []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) require.NoError(err) } for _, staker := range test.subnetStakers { - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -602,15 +604,14 @@ func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) // Add a subnet validator to the staker set - subnetValidatorNodeID := genesisNodeIDs[0] - subnetVdr1StartTime := defaultValidateStartTime - subnetVdr1EndTime := defaultValidateStartTime.Add(defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] + subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, - Start: uint64(subnetVdr1StartTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix, End: uint64(subnetVdr1EndTime.Unix()), Wght: 1, }, @@ -637,7 +638,7 @@ func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { // The above validator is now part of the staking set // Queue a staker that joins the staker set after the above validator leaves - subnetVdr2NodeID := genesisNodeIDs[1] + subnetVdr2NodeID := genesistest.DefaultNodeIDs[1] utx, err = builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -708,10 +709,10 @@ func TestBanffStandardBlockTrackedSubnet(t *testing.T) { } // Add a subnet validator to the staker set - subnetValidatorNodeID := genesisNodeIDs[0] - subnetVdr1StartTime := defaultGenesisTime.Add(1 * time.Minute) - subnetVdr1EndTime := defaultGenesisTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] + subnetVdr1StartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Minute) + subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -768,7 +769,7 @@ func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { // Case: Timestamp is after next validator start time // Add a pending validator - pendingValidatorStartTime := defaultGenesisTime.Add(1 * time.Second) + pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMaxStakingDuration) nodeID := ids.GenerateTestNodeID() rewardAddress := ids.GenerateTestShortID() @@ -778,7 +779,7 @@ func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { pendingValidatorEndTime, nodeID, rewardAddress, - []*secp256k1.PrivateKey{preFundedKeys[0]}, + []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) require.NoError(err) @@ -806,7 +807,7 @@ func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1], preFundedKeys[4]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) utx, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: nodeID, @@ -816,7 +817,7 @@ func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, ) require.NoError(err) diff --git a/vms/platformvm/block/executor/verifier_test.go b/vms/platformvm/block/executor/verifier_test.go index 73bef61aa9f7..d2b131a3f2a3 100644 --- a/vms/platformvm/block/executor/verifier_test.go +++ b/vms/platformvm/block/executor/verifier_test.go @@ -23,6 +23,7 @@ import ( "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" @@ -469,7 +470,7 @@ func TestVerifyUnverifiedParent(t *testing.T) { func TestBanffAbortBlockTimestampChecks(t *testing.T) { ctrl := gomock.NewController(t) - now := defaultGenesisTime.Add(time.Hour) + now := genesistest.DefaultValidatorStartTime.Add(time.Hour) tests := []struct { description string @@ -532,7 +533,7 @@ func TestBanffAbortBlockTimestampChecks(t *testing.T) { require.NoError(err) // setup parent state - parentTime := defaultGenesisTime + parentTime := genesistest.DefaultValidatorStartTime s.EXPECT().GetLastAccepted().Return(parentID).Times(3) s.EXPECT().GetTimestamp().Return(parentTime).Times(3) s.EXPECT().GetFeeState().Return(gas.State{}).Times(3) @@ -566,7 +567,7 @@ func TestBanffAbortBlockTimestampChecks(t *testing.T) { func TestBanffCommitBlockTimestampChecks(t *testing.T) { ctrl := gomock.NewController(t) - now := defaultGenesisTime.Add(time.Hour) + now := genesistest.DefaultValidatorStartTime.Add(time.Hour) tests := []struct { description string @@ -629,7 +630,7 @@ func TestBanffCommitBlockTimestampChecks(t *testing.T) { require.NoError(err) // setup parent state - parentTime := defaultGenesisTime + parentTime := genesistest.DefaultValidatorStartTime s.EXPECT().GetLastAccepted().Return(parentID).Times(3) s.EXPECT().GetTimestamp().Return(parentTime).Times(3) s.EXPECT().GetFeeState().Return(gas.State{}).Times(3) diff --git a/vms/platformvm/block/parse_test.go b/vms/platformvm/block/parse_test.go index 8bebb50753c4..b63d4bbc513f 100644 --- a/vms/platformvm/block/parse_test.go +++ b/vms/platformvm/block/parse_test.go @@ -296,7 +296,7 @@ func testAtomicTx() (*txs.Tx, error) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }}, @@ -345,7 +345,7 @@ func testDecisionTxs() ([]*txs.Tx, error) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }}, diff --git a/vms/platformvm/genesis/genesistest/genesis.go b/vms/platformvm/genesis/genesistest/genesis.go index 24e16ecf0934..9a9f9a2a48c4 100644 --- a/vms/platformvm/genesis/genesistest/genesis.go +++ b/vms/platformvm/genesis/genesistest/genesis.go @@ -10,98 +10,166 @@ import ( "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow/snowtest" + "github.com/ava-labs/avalanchego/upgrade" "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/platformvm/genesis" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + + platformvmgenesis "github.com/ava-labs/avalanchego/vms/platformvm/genesis" +) + +const ( + DefaultValidatorDuration = 28 * 24 * time.Hour + DefaultValidatorWeight = 5 * units.MilliAvax + DefaultInitialBalance = 1 * units.Avax + + ValidatorDelegationShares = reward.PercentDenominator + XChainName = "x" + InitialSupply = 360 * units.MegaAvax ) var ( - AVAXAssetID = ids.GenerateTestID() - AVAXAsset = avax.Asset{ID: AVAXAssetID} - - ValidatorNodeID = ids.GenerateTestNodeID() - Time = time.Now().Round(time.Second) - TimeUnix = uint64(Time.Unix()) - ValidatorDuration = 28 * 24 * time.Hour - ValidatorEndTime = Time.Add(ValidatorDuration) - ValidatorEndTimeUnix = uint64(ValidatorEndTime.Unix()) - ValidatorWeight = units.Avax - ValidatorRewardsOwner = &secp256k1fx.OutputOwners{} - ValidatorDelegationShares uint32 = reward.PercentDenominator - - XChainName = "x" - - InitialBalance = units.Schmeckle - InitialSupply = ValidatorWeight + InitialBalance + AVAXAsset = avax.Asset{ID: snowtest.AVAXAssetID} + + DefaultValidatorStartTime = upgrade.InitiallyActiveTime + DefaultValidatorStartTimeUnix = uint64(DefaultValidatorStartTime.Unix()) + DefaultValidatorEndTime = DefaultValidatorStartTime.Add(DefaultValidatorDuration) + DefaultValidatorEndTimeUnix = uint64(DefaultValidatorEndTime.Unix()) ) -func New(t testing.TB) *genesis.Genesis { - require := require.New(t) +var ( + // Keys that are funded in the genesis + DefaultFundedKeys = secp256k1.TestKeys() - genesisValidator := &txs.AddValidatorTx{ - Validator: txs.Validator{ - NodeID: ValidatorNodeID, - Start: TimeUnix, - End: ValidatorEndTimeUnix, - Wght: ValidatorWeight, - }, - StakeOuts: []*avax.TransferableOutput{ - { - Asset: AVAXAsset, - Out: &secp256k1fx.TransferOutput{ - Amt: ValidatorWeight, - }, - }, - }, - RewardsOwner: ValidatorRewardsOwner, - DelegationShares: ValidatorDelegationShares, + // Node IDs of genesis validators + DefaultNodeIDs []ids.NodeID +) + +func init() { + DefaultNodeIDs = make([]ids.NodeID, len(DefaultFundedKeys)) + for i := range DefaultFundedKeys { + DefaultNodeIDs[i] = ids.GenerateTestNodeID() } - genesisValidatorTx := &txs.Tx{Unsigned: genesisValidator} - require.NoError(genesisValidatorTx.Initialize(txs.Codec)) +} - genesisChain := &txs.CreateChainTx{ - SubnetID: constants.PrimaryNetworkID, - ChainName: XChainName, - VMID: constants.AVMID, - SubnetAuth: &secp256k1fx.Input{}, +type Config struct { + NodeIDs []ids.NodeID + ValidatorWeight uint64 + ValidatorStartTime time.Time + ValidatorEndTime time.Time + + FundedKeys []*secp256k1.PrivateKey + InitialBalance uint64 +} + +func New(t testing.TB, c Config) *platformvmgenesis.Genesis { + if len(c.NodeIDs) == 0 { + c.NodeIDs = DefaultNodeIDs + } + if c.ValidatorWeight == 0 { + c.ValidatorWeight = DefaultValidatorWeight + } + if c.ValidatorStartTime.IsZero() { + c.ValidatorStartTime = DefaultValidatorStartTime + } + if c.ValidatorEndTime.IsZero() { + c.ValidatorEndTime = DefaultValidatorEndTime } - genesisChainTx := &txs.Tx{Unsigned: genesisChain} - require.NoError(genesisChainTx.Initialize(txs.Codec)) - - return &genesis.Genesis{ - UTXOs: []*genesis.UTXO{ - { - UTXO: avax.UTXO{ - UTXOID: avax.UTXOID{ - TxID: AVAXAssetID, - OutputIndex: 0, + if len(c.FundedKeys) == 0 { + c.FundedKeys = DefaultFundedKeys + } + if c.InitialBalance == 0 { + c.InitialBalance = DefaultInitialBalance + } + + require := require.New(t) + + genesis := &platformvmgenesis.Genesis{ + UTXOs: make([]*platformvmgenesis.UTXO, len(c.FundedKeys)), + Validators: make([]*txs.Tx, len(c.NodeIDs)), + Timestamp: uint64(c.ValidatorStartTime.Unix()), + InitialSupply: InitialSupply, + } + for i, key := range c.FundedKeys { + genesis.UTXOs[i] = &platformvmgenesis.UTXO{UTXO: avax.UTXO{ + UTXOID: avax.UTXOID{ + TxID: snowtest.AVAXAssetID, + OutputIndex: uint32(i), + }, + Asset: AVAXAsset, + Out: &secp256k1fx.TransferOutput{ + Amt: c.InitialBalance, + OutputOwners: secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + key.Address(), }, + }, + }, + }} + } + for i, nodeID := range c.NodeIDs { + key := c.FundedKeys[i%len(c.FundedKeys)] + owner := secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + key.Address(), + }, + } + validator := &txs.AddValidatorTx{ + BaseTx: txs.BaseTx{BaseTx: avax.BaseTx{ + NetworkID: constants.UnitTestID, + BlockchainID: constants.PlatformChainID, + }}, + Validator: txs.Validator{ + NodeID: nodeID, + Start: uint64(c.ValidatorStartTime.Unix()), + End: uint64(c.ValidatorEndTime.Unix()), + Wght: c.ValidatorWeight, + }, + StakeOuts: []*avax.TransferableOutput{ + { Asset: AVAXAsset, Out: &secp256k1fx.TransferOutput{ - Amt: InitialBalance, + Amt: c.ValidatorWeight, + OutputOwners: owner, }, }, - Message: nil, }, - }, - Validators: []*txs.Tx{ - genesisValidatorTx, - }, - Chains: []*txs.Tx{ - genesisChainTx, - }, - Timestamp: TimeUnix, - InitialSupply: InitialSupply, + RewardsOwner: &owner, + DelegationShares: ValidatorDelegationShares, + } + validatorTx := &txs.Tx{Unsigned: validator} + require.NoError(validatorTx.Initialize(txs.GenesisCodec)) + + genesis.Validators[i] = validatorTx } + + chain := &txs.CreateChainTx{ + BaseTx: txs.BaseTx{BaseTx: avax.BaseTx{ + NetworkID: constants.UnitTestID, + BlockchainID: constants.PlatformChainID, + }}, + SubnetID: constants.PrimaryNetworkID, + ChainName: XChainName, + VMID: constants.AVMID, + SubnetAuth: &secp256k1fx.Input{}, + } + chainTx := &txs.Tx{Unsigned: chain} + require.NoError(chainTx.Initialize(txs.GenesisCodec)) + + genesis.Chains = []*txs.Tx{chainTx} + return genesis } -func NewBytes(t testing.TB) []byte { - g := New(t) - genesisBytes, err := genesis.Codec.Marshal(genesis.CodecVersion, g) +func NewBytes(t testing.TB, c Config) []byte { + g := New(t, c) + genesisBytes, err := platformvmgenesis.Codec.Marshal(platformvmgenesis.CodecVersion, g) require.NoError(t, err) return genesisBytes } diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index f1c1cd2f44dc..47e8a48ef578 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -32,11 +32,13 @@ import ( "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/formatting" + "github.com/ava-labs/avalanchego/utils/formatting/address" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/block/executor/executormock" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -106,7 +108,7 @@ func TestExportKey(t *testing.T) { pk, err := secp256k1.ToPrivateKey(testPrivateKey) require.NoError(err) - require.NoError(user.PutKeys(pk, keys[0])) + require.NoError(user.PutKeys(pk, genesistest.DefaultFundedKeys[0])) service.vm.ctx.Lock.Unlock() @@ -146,7 +148,7 @@ func TestGetTxStatus(t *testing.T) { Amt: 1234567, OutputOwners: secp256k1fx.OutputOwners{ Locktime: 0, - Addrs: []ids.ShortID{recipientKey.PublicKey().Address()}, + Addrs: []ids.ShortID{recipientKey.Address()}, Threshold: 1, }, }, @@ -162,7 +164,7 @@ func TestGetTxStatus(t *testing.T) { Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - recipientKey.PublicKey().Address().Bytes(), + recipientKey.Address().Bytes(), }, }, }, @@ -233,7 +235,7 @@ func TestGetTx(t *testing.T) { "chain name", common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(t, err) @@ -251,7 +253,7 @@ func TestGetTx(t *testing.T) { Addrs: []ids.ShortID{ids.GenerateTestShortID()}, } - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -269,7 +271,7 @@ func TestGetTx(t *testing.T) { 0, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(t, err) @@ -279,7 +281,7 @@ func TestGetTx(t *testing.T) { { "atomic block", func(service *Service, factory *txstest.WalletFactory) (*txs.Tx, error) { - builder, signer := factory.NewWallet(keys[0]) + builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewExportTx( service.vm.ctx.XChainID, []*avax.TransferableOutput{{ @@ -295,7 +297,7 @@ func TestGetTx(t *testing.T) { }}, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(t, err) @@ -383,21 +385,28 @@ func TestGetBalance(t *testing.T) { require.NoError(err) // Ensure GetStake is correct for each of the genesis validators - genesis, _ := defaultGenesis(t, service.vm.ctx.AVAXAssetID) + genesis := genesistest.New(t, genesistest.Config{}) for idx, utxo := range genesis.UTXOs { + out := utxo.Out.(*secp256k1fx.TransferOutput) + require.Len(out.Addrs, 1) + + addr := out.Addrs[0] + addrStr, err := address.Format("P", constants.UnitTestHRP, addr.Bytes()) + require.NoError(err) + request := GetBalanceRequest{ Addresses: []string{ - "P-" + utxo.Address, + addrStr, }, } reply := GetBalanceResponse{} require.NoError(service.GetBalance(nil, &request, &reply)) - balance := defaultBalance + balance := genesistest.DefaultInitialBalance if idx == 0 { // we use the first key to fund a subnet creation in [defaultGenesis]. // As such we need to account for the subnet creation fee - balance = defaultBalance - createSubnetFee + balance = genesistest.DefaultInitialBalance - createSubnetFee } require.Equal(avajson.Uint64(balance), reply.Balance) require.Equal(avajson.Uint64(balance), reply.Unlocked) @@ -411,21 +420,29 @@ func TestGetStake(t *testing.T) { service, _, factory := defaultService(t) // Ensure GetStake is correct for each of the genesis validators - genesis, _ := defaultGenesis(t, service.vm.ctx.AVAXAssetID) + genesis := genesistest.New(t, genesistest.Config{}) addrsStrs := []string{} - for i, validator := range genesis.Validators { - addr := "P-" + validator.RewardOwner.Addresses[0] - addrsStrs = append(addrsStrs, addr) + for _, validatorTx := range genesis.Validators { + validator := validatorTx.Unsigned.(*txs.AddValidatorTx) + require.Len(validator.StakeOuts, 1) + stakeOut := validator.StakeOuts[0].Out.(*secp256k1fx.TransferOutput) + require.Len(stakeOut.Addrs, 1) + addr := stakeOut.Addrs[0] + + addrStr, err := address.Format("P", constants.UnitTestHRP, addr.Bytes()) + require.NoError(err) + + addrsStrs = append(addrsStrs, addrStr) args := GetStakeArgs{ JSONAddresses: api.JSONAddresses{ - Addresses: []string{addr}, + Addresses: []string{addrStr}, }, Encoding: formatting.Hex, } response := GetStakeReply{} require.NoError(service.GetStake(nil, &args, &response)) - require.Equal(defaultWeight, uint64(response.Staked)) + require.Equal(genesistest.DefaultValidatorWeight, uint64(response.Staked)) require.Len(response.Outputs, 1) // Unmarshal into an output @@ -436,12 +453,23 @@ func TestGetStake(t *testing.T) { _, err = txs.Codec.Unmarshal(outputBytes, &output) require.NoError(err) - out := output.Out.(*secp256k1fx.TransferOutput) - require.Equal(defaultWeight, out.Amount()) - require.Equal(uint32(1), out.Threshold) - require.Len(out.Addrs, 1) - require.Equal(keys[i].PublicKey().Address(), out.Addrs[0]) - require.Zero(out.Locktime) + require.Equal( + avax.TransferableOutput{ + Asset: avax.Asset{ + ID: service.vm.ctx.AVAXAssetID, + }, + Out: &secp256k1fx.TransferOutput{ + Amt: genesistest.DefaultValidatorWeight, + OutputOwners: secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + addr, + }, + }, + }, + }, + output, + ) } // Make sure this works for multiple addresses @@ -453,7 +481,7 @@ func TestGetStake(t *testing.T) { } response := GetStakeReply{} require.NoError(service.GetStake(nil, &args, &response)) - require.Equal(len(genesis.Validators)*int(defaultWeight), int(response.Staked)) + require.Equal(len(genesis.Validators)*int(genesistest.DefaultValidatorWeight), int(response.Staked)) require.Len(response.Outputs, len(genesis.Validators)) for _, outputStr := range response.Outputs { @@ -465,26 +493,25 @@ func TestGetStake(t *testing.T) { require.NoError(err) out := output.Out.(*secp256k1fx.TransferOutput) - require.Equal(defaultWeight, out.Amount()) + require.Equal(genesistest.DefaultValidatorWeight, out.Amt) require.Equal(uint32(1), out.Threshold) require.Zero(out.Locktime) require.Len(out.Addrs, 1) } - oldStake := defaultWeight + oldStake := genesistest.DefaultValidatorWeight service.vm.ctx.Lock.Lock() // Add a delegator stakeAmount := service.vm.MinDelegatorStake + 12345 - delegatorNodeID := genesisNodeIDs[0] - delegatorStartTime := defaultValidateStartTime - delegatorEndTime := defaultGenesisTime.Add(defaultMinStakingDuration) - builder, signer := factory.NewWallet(keys[0]) + delegatorNodeID := genesistest.DefaultNodeIDs[0] + delegatorEndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) + builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: delegatorNodeID, - Start: uint64(delegatorStartTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix, End: uint64(delegatorEndTime.Unix()), Wght: stakeAmount, }, @@ -494,7 +521,7 @@ func TestGetStake(t *testing.T) { }, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -505,7 +532,7 @@ func TestGetStake(t *testing.T) { staker, err := state.NewCurrentStaker( tx.ID(), addDelTx, - delegatorStartTime, + genesistest.DefaultValidatorStartTime, 0, ) require.NoError(err) @@ -517,7 +544,7 @@ func TestGetStake(t *testing.T) { service.vm.ctx.Lock.Unlock() // Make sure the delegator addr has the right stake (old stake + stakeAmount) - addr, _ := service.addrManager.FormatLocalAddress(keys[0].PublicKey().Address()) + addr, _ := service.addrManager.FormatLocalAddress(genesistest.DefaultFundedKeys[0].Address()) args.Addresses = []string{addr} require.NoError(service.GetStake(nil, &args, &response)) require.Equal(oldStake+stakeAmount, uint64(response.Staked)) @@ -543,11 +570,11 @@ func TestGetStake(t *testing.T) { // Add a pending staker stakeAmount = service.vm.MinValidatorStake + 54321 pendingStakerNodeID := ids.GenerateTestNodeID() - pendingStakerEndTime := uint64(defaultGenesisTime.Add(defaultMinStakingDuration).Unix()) + pendingStakerEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration).Unix()) utx2, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: pendingStakerNodeID, - Start: uint64(defaultGenesisTime.Unix()), + Start: uint64(genesistest.DefaultValidatorStartTime.Unix()), End: pendingStakerEndTime, Wght: stakeAmount, }, @@ -558,7 +585,7 @@ func TestGetStake(t *testing.T) { 0, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -599,7 +626,7 @@ func TestGetCurrentValidators(t *testing.T) { require := require.New(t) service, _, factory := defaultService(t) - genesis, _ := defaultGenesis(t, service.vm.ctx.AVAXAssetID) + genesis := genesistest.New(t, genesistest.Config{}) // Call getValidators args := GetCurrentValidatorsArgs{SubnetID: constants.PrimaryNetworkID} @@ -608,34 +635,37 @@ func TestGetCurrentValidators(t *testing.T) { require.NoError(service.GetCurrentValidators(nil, &args, &response)) require.Len(response.Validators, len(genesis.Validators)) - for _, vdr := range genesis.Validators { + for _, validatorTx := range genesis.Validators { + validator := validatorTx.Unsigned.(*txs.AddValidatorTx) + nodeID := validator.NodeID() + found := false - for i := 0; i < len(response.Validators) && !found; i++ { + for i := 0; i < len(response.Validators); i++ { gotVdr := response.Validators[i].(pchainapi.PermissionlessValidator) - if gotVdr.NodeID != vdr.NodeID { + if gotVdr.NodeID != nodeID { continue } - require.Equal(vdr.EndTime, gotVdr.EndTime) - require.Equal(vdr.StartTime, gotVdr.StartTime) + require.Equal(validator.EndTime().Unix(), int64(gotVdr.EndTime)) + require.Equal(validator.StartTime().Unix(), int64(gotVdr.StartTime)) found = true + break } - require.True(found, "expected validators to contain %s but didn't", vdr.NodeID) + require.True(found, "expected validators to contain %s but didn't", nodeID) } // Add a delegator stakeAmount := service.vm.MinDelegatorStake + 12345 - validatorNodeID := genesisNodeIDs[1] - delegatorStartTime := defaultValidateStartTime - delegatorEndTime := delegatorStartTime.Add(defaultMinStakingDuration) + validatorNodeID := genesistest.DefaultNodeIDs[1] + delegatorEndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) service.vm.ctx.Lock.Lock() - builder, signer := factory.NewWallet(keys[0]) + builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: validatorNodeID, - Start: uint64(delegatorStartTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix, End: uint64(delegatorEndTime.Unix()), Wght: stakeAmount, }, @@ -645,7 +675,7 @@ func TestGetCurrentValidators(t *testing.T) { }, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -656,7 +686,7 @@ func TestGetCurrentValidators(t *testing.T) { staker, err := state.NewCurrentStaker( delTx.ID(), addDelTx, - delegatorStartTime, + genesistest.DefaultValidatorStartTime, 0, ) require.NoError(err) @@ -698,7 +728,7 @@ func TestGetCurrentValidators(t *testing.T) { require.Len(*innerVdr.Delegators, 1) delegator := (*innerVdr.Delegators)[0] require.Equal(delegator.NodeID, innerVdr.NodeID) - require.Equal(int64(delegator.StartTime), delegatorStartTime.Unix()) + require.Equal(uint64(delegator.StartTime), genesistest.DefaultValidatorStartTimeUnix) require.Equal(int64(delegator.EndTime), delegatorEndTime.Unix()) require.Equal(uint64(delegator.Weight), stakeAmount) } @@ -782,7 +812,7 @@ func TestGetBlock(t *testing.T) { "chain name", common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) diff --git a/vms/platformvm/state/stakers_test.go b/vms/platformvm/state/stakers_test.go index 6b1343891540..e4ae2aa840c5 100644 --- a/vms/platformvm/state/stakers_test.go +++ b/vms/platformvm/state/stakers_test.go @@ -221,7 +221,7 @@ func TestDiffStakersDelegator(t *testing.T) { func newTestStaker() *Staker { startTime := time.Now().Round(time.Second) - endTime := startTime.Add(genesistest.ValidatorDuration) + endTime := startTime.Add(genesistest.DefaultValidatorDuration) return &Staker{ TxID: ids.GenerateTestID(), NodeID: ids.GenerateTestNodeID(), diff --git a/vms/platformvm/state/state_test.go b/vms/platformvm/state/state_test.go index 7e52453d5742..de2bab544c00 100644 --- a/vms/platformvm/state/state_test.go +++ b/vms/platformvm/state/state_test.go @@ -47,16 +47,22 @@ import ( safemath "github.com/ava-labs/avalanchego/utils/math" ) +var defaultValidatorNodeID = ids.GenerateTestNodeID() + func newTestState(t testing.TB, db database.Database) *state { s, err := New( db, - genesistest.NewBytes(t), + genesistest.NewBytes(t, genesistest.Config{ + NodeIDs: []ids.NodeID{defaultValidatorNodeID}, + }), prometheus.NewRegistry(), validators.NewManager(), upgradetest.GetConfig(upgradetest.Latest), &config.DefaultExecutionConfig, &snow.Context{ - Log: logging.NoLog{}, + NetworkID: constants.UnitTestID, + NodeID: ids.GenerateTestNodeID(), + Log: logging.NoLog{}, }, metrics.Noop, reward.NewCalculator(reward.Config{ @@ -75,12 +81,12 @@ func TestStateSyncGenesis(t *testing.T) { require := require.New(t) state := newTestState(t, memdb.New()) - staker, err := state.GetCurrentValidator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) + staker, err := state.GetCurrentValidator(constants.PrimaryNetworkID, defaultValidatorNodeID) require.NoError(err) require.NotNil(staker) - require.Equal(genesistest.ValidatorNodeID, staker.NodeID) + require.Equal(defaultValidatorNodeID, staker.NodeID) - delegatorIterator, err := state.GetCurrentDelegatorIterator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) + delegatorIterator, err := state.GetCurrentDelegatorIterator(constants.PrimaryNetworkID, defaultValidatorNodeID) require.NoError(err) assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) @@ -88,10 +94,10 @@ func TestStateSyncGenesis(t *testing.T) { require.NoError(err) assertIteratorsEqual(t, iterator.FromSlice(staker), stakerIterator) - _, err = state.GetPendingValidator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) + _, err = state.GetPendingValidator(constants.PrimaryNetworkID, defaultValidatorNodeID) require.ErrorIs(err, database.ErrNotFound) - delegatorIterator, err = state.GetPendingDelegatorIterator(constants.PrimaryNetworkID, genesistest.ValidatorNodeID) + delegatorIterator, err = state.GetPendingDelegatorIterator(constants.PrimaryNetworkID, defaultValidatorNodeID) require.NoError(err) assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) } diff --git a/vms/platformvm/state/statetest/state.go b/vms/platformvm/state/statetest/state.go index fbc71381ec51..66998ea3cf10 100644 --- a/vms/platformvm/state/statetest/state.go +++ b/vms/platformvm/state/statetest/state.go @@ -27,6 +27,8 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/state" ) +var DefaultNodeID = ids.GenerateTestNodeID() + type Config struct { DB database.Database Genesis []byte @@ -44,11 +46,14 @@ func New(t testing.TB, c Config) state.State { c.DB = memdb.New() } if len(c.Genesis) == 0 { - c.Genesis = genesistest.NewBytes(t) + c.Genesis = genesistest.NewBytes(t, genesistest.Config{}) } if c.Registerer == nil { c.Registerer = prometheus.NewRegistry() } + if c.Validators == nil { + c.Validators = validators.NewManager() + } if c.Upgrades == (upgrade.Config{}) { c.Upgrades = upgradetest.GetConfig(upgradetest.Latest) } @@ -58,7 +63,7 @@ func New(t testing.TB, c Config) state.State { if c.Context == nil { c.Context = &snow.Context{ NetworkID: constants.UnitTestID, - NodeID: ids.GenerateTestNodeID(), + NodeID: DefaultNodeID, Log: logging.NoLog{}, } } diff --git a/vms/platformvm/txs/add_delegator_test.go b/vms/platformvm/txs/add_delegator_test.go index ac3290fb2431..3d2ba834f9c6 100644 --- a/vms/platformvm/txs/add_delegator_test.go +++ b/vms/platformvm/txs/add_delegator_test.go @@ -58,7 +58,7 @@ func TestAddDelegatorTxSyntacticVerify(t *testing.T) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }} @@ -70,7 +70,7 @@ func TestAddDelegatorTxSyntacticVerify(t *testing.T) { Amt: validatorWeight, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }, @@ -93,7 +93,7 @@ func TestAddDelegatorTxSyntacticVerify(t *testing.T) { DelegationRewardsOwner: &secp256k1fx.OutputOwners{ Locktime: 0, Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, } @@ -157,7 +157,7 @@ func TestAddDelegatorTxSyntacticVerifyNotAVAX(t *testing.T) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }} @@ -169,7 +169,7 @@ func TestAddDelegatorTxSyntacticVerifyNotAVAX(t *testing.T) { Amt: validatorWeight, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }, @@ -192,7 +192,7 @@ func TestAddDelegatorTxSyntacticVerifyNotAVAX(t *testing.T) { DelegationRewardsOwner: &secp256k1fx.OutputOwners{ Locktime: 0, Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, } diff --git a/vms/platformvm/txs/add_subnet_validator_test.go b/vms/platformvm/txs/add_subnet_validator_test.go index 8dc8d76782ac..b3c3630ef2f0 100644 --- a/vms/platformvm/txs/add_subnet_validator_test.go +++ b/vms/platformvm/txs/add_subnet_validator_test.go @@ -58,7 +58,7 @@ func TestAddSubnetValidatorTxSyntacticVerify(t *testing.T) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }} @@ -169,7 +169,7 @@ func TestAddSubnetValidatorMarshal(t *testing.T) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }} diff --git a/vms/platformvm/txs/add_validator_test.go b/vms/platformvm/txs/add_validator_test.go index daf32f66746d..27ea18dc5a7e 100644 --- a/vms/platformvm/txs/add_validator_test.go +++ b/vms/platformvm/txs/add_validator_test.go @@ -40,7 +40,7 @@ func TestAddValidatorTxSyntacticVerify(t *testing.T) { require.ErrorIs(err, ErrNilTx) validatorWeight := uint64(2022) - rewardAddress := preFundedKeys[0].PublicKey().Address() + rewardAddress := preFundedKeys[0].Address() inputs := []*avax.TransferableInput{{ UTXOID: avax.UTXOID{ TxID: ids.ID{'t', 'x', 'I', 'D'}, @@ -58,7 +58,7 @@ func TestAddValidatorTxSyntacticVerify(t *testing.T) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }} @@ -70,7 +70,7 @@ func TestAddValidatorTxSyntacticVerify(t *testing.T) { Amt: validatorWeight, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }, @@ -156,7 +156,7 @@ func TestAddValidatorTxSyntacticVerifyNotAVAX(t *testing.T) { assetID := ids.GenerateTestID() validatorWeight := uint64(2022) - rewardAddress := preFundedKeys[0].PublicKey().Address() + rewardAddress := preFundedKeys[0].Address() inputs := []*avax.TransferableInput{{ UTXOID: avax.UTXOID{ TxID: ids.ID{'t', 'x', 'I', 'D'}, @@ -174,7 +174,7 @@ func TestAddValidatorTxSyntacticVerifyNotAVAX(t *testing.T) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }} @@ -186,7 +186,7 @@ func TestAddValidatorTxSyntacticVerifyNotAVAX(t *testing.T) { Amt: validatorWeight, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }, diff --git a/vms/platformvm/txs/create_chain_test.go b/vms/platformvm/txs/create_chain_test.go index ecf52567d357..a3565d4ae29d 100644 --- a/vms/platformvm/txs/create_chain_test.go +++ b/vms/platformvm/txs/create_chain_test.go @@ -143,7 +143,7 @@ func TestUnsignedCreateChainTxVerify(t *testing.T) { Amt: uint64(1234), OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{preFundedKeys[0].Address()}, }, }, }} diff --git a/vms/platformvm/txs/executor/advance_time_test.go b/vms/platformvm/txs/executor/advance_time_test.go index e9e54ad8a3e6..c10c76ec7bac 100644 --- a/vms/platformvm/txs/executor/advance_time_test.go +++ b/vms/platformvm/txs/executor/advance_time_test.go @@ -17,6 +17,7 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -46,7 +47,7 @@ func TestAdvanceTimeTxUpdatePrimaryNetworkStakers(t *testing.T) { // Case: Timestamp is after next validator start time // Add a pending validator - pendingValidatorStartTime := defaultValidateStartTime.Add(1 * time.Second) + pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeID := ids.GenerateTestNodeID() addPendingValidatorTx, err := addPendingValidator( @@ -54,7 +55,7 @@ func TestAdvanceTimeTxUpdatePrimaryNetworkStakers(t *testing.T) { pendingValidatorStartTime, pendingValidatorEndTime, nodeID, - []*secp256k1.PrivateKey{preFundedKeys[0]}, + []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) require.NoError(err) @@ -136,10 +137,10 @@ func TestAdvanceTimeTxTimestampTooLate(t *testing.T) { // Case: Timestamp is after next validator start time // Add a pending validator - pendingValidatorStartTime := defaultValidateStartTime.Add(1 * time.Second) + pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeID := ids.GenerateTestNodeID() - _, err := addPendingValidator(env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{preFundedKeys[0]}) + _, err := addPendingValidator(env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}) require.NoError(err) { @@ -170,11 +171,11 @@ func TestAdvanceTimeTxTimestampTooLate(t *testing.T) { defer env.ctx.Lock.Unlock() // fast forward clock to 10 seconds before genesis validators stop validating - env.clk.Set(defaultValidateEndTime.Add(-10 * time.Second)) + env.clk.Set(genesistest.DefaultValidatorEndTime.Add(-10 * time.Second)) { // Proposes advancing timestamp to 1 second after genesis validators stop validating - tx, err := newAdvanceTimeTx(t, defaultValidateEndTime.Add(1*time.Second)) + tx, err := newAdvanceTimeTx(t, genesistest.DefaultValidatorEndTime.Add(1*time.Second)) require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) @@ -228,8 +229,8 @@ func TestAdvanceTimeTxUpdateStakers(t *testing.T) { // Staker5: |--------------------| staker1 := staker{ nodeID: ids.GenerateTestNodeID(), - startTime: defaultValidateStartTime.Add(1 * time.Minute), - endTime: defaultValidateStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute), + startTime: genesistest.DefaultValidatorStartTime.Add(1 * time.Minute), + endTime: genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute), } staker2 := staker{ nodeID: ids.GenerateTestNodeID(), @@ -382,13 +383,13 @@ func TestAdvanceTimeTxUpdateStakers(t *testing.T) { staker.startTime, staker.endTime, staker.nodeID, - []*secp256k1.PrivateKey{preFundedKeys[0]}, + []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) require.NoError(err) } for _, staker := range test.subnetStakers { - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -486,16 +487,15 @@ func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { dummyHeight := uint64(1) // Add a subnet validator to the staker set - subnetValidatorNodeID := genesisNodeIDs[0] - subnetVdr1StartTime := defaultValidateStartTime - subnetVdr1EndTime := defaultValidateStartTime.Add(defaultMinStakingDuration) + subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] + subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, - Start: uint64(subnetVdr1StartTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix, End: uint64(subnetVdr1EndTime.Unix()), Wght: 1, }, @@ -523,7 +523,7 @@ func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { // The above validator is now part of the staking set // Queue a staker that joins the staker set after the above validator leaves - subnetVdr2NodeID := genesisNodeIDs[1] + subnetVdr2NodeID := genesistest.DefaultNodeIDs[1] utx, err = builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -602,11 +602,11 @@ func TestTrackedSubnet(t *testing.T) { } // Add a subnet validator to the staker set - subnetValidatorNodeID := genesisNodeIDs[0] + subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] - subnetVdr1StartTime := defaultValidateStartTime.Add(1 * time.Minute) - subnetVdr1EndTime := defaultValidateStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + subnetVdr1StartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Minute) + subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -673,7 +673,7 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { // Case: Timestamp is after next validator start time // Add a pending validator - pendingValidatorStartTime := defaultValidateStartTime.Add(1 * time.Second) + pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMaxStakingDuration) nodeID := ids.GenerateTestNodeID() _, err := addPendingValidator( @@ -681,7 +681,7 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { pendingValidatorStartTime, pendingValidatorEndTime, nodeID, - []*secp256k1.PrivateKey{preFundedKeys[0]}, + []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) require.NoError(err) @@ -717,7 +717,7 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1], preFundedKeys[4]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) utx, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: nodeID, @@ -727,7 +727,7 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, ) require.NoError(err) @@ -783,10 +783,10 @@ func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { // Case: Timestamp is after next validator start time // Add a pending validator - pendingValidatorStartTime := defaultValidateStartTime.Add(1 * time.Second) + pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeID := ids.GenerateTestNodeID() - _, err := addPendingValidator(env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{preFundedKeys[0]}) + _, err := addPendingValidator(env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}) require.NoError(err) tx, err := newAdvanceTimeTx(t, pendingValidatorStartTime) @@ -820,7 +820,7 @@ func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { // Add delegator pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1], preFundedKeys[4]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) utx, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: nodeID, @@ -830,7 +830,7 @@ func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, ) require.NoError(err) @@ -882,7 +882,7 @@ func TestAdvanceTimeTxAfterBanff(t *testing.T) { env := newEnvironment(t, upgradetest.Durango) env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - env.clk.Set(defaultGenesisTime) // VM's clock reads the genesis time + env.clk.Set(genesistest.DefaultValidatorStartTime) // VM's clock reads the genesis time upgradeTime := env.clk.Time().Add(SyncBound) env.config.UpgradeConfig.BanffTime = upgradeTime env.config.UpgradeConfig.CortinaTime = upgradeTime diff --git a/vms/platformvm/txs/executor/create_chain_test.go b/vms/platformvm/txs/executor/create_chain_test.go index a1ad4c81e186..d454cda30a78 100644 --- a/vms/platformvm/txs/executor/create_chain_test.go +++ b/vms/platformvm/txs/executor/create_chain_test.go @@ -18,6 +18,7 @@ import ( "github.com/ava-labs/avalanchego/utils/hashing" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" @@ -34,7 +35,7 @@ func TestCreateChainTxInsufficientControlSigs(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - builder, signer := env.factory.NewWallet(preFundedKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewCreateChainTx( testSubnet1.ID(), nil, @@ -180,7 +181,7 @@ func TestCreateChainTxValid(t *testing.T) { } func TestCreateChainTxAP3FeeChange(t *testing.T) { - ap3Time := defaultGenesisTime.Add(time.Hour) + ap3Time := genesistest.DefaultValidatorStartTime.Add(time.Hour) tests := []struct { name string time time.Time @@ -189,7 +190,7 @@ func TestCreateChainTxAP3FeeChange(t *testing.T) { }{ { name: "pre-fork - correctly priced", - time: defaultGenesisTime, + time: genesistest.DefaultValidatorStartTime, fee: 0, expectedError: nil, }, @@ -213,8 +214,8 @@ func TestCreateChainTxAP3FeeChange(t *testing.T) { env := newEnvironment(t, upgradetest.Banff) env.config.UpgradeConfig.ApricotPhase3Time = ap3Time - addrs := set.NewSet[ids.ShortID](len(preFundedKeys)) - for _, key := range preFundedKeys { + addrs := set.NewSet[ids.ShortID](len(genesistest.DefaultFundedKeys)) + for _, key := range genesistest.DefaultFundedKeys { addrs.Add(key.Address()) } @@ -224,7 +225,7 @@ func TestCreateChainTxAP3FeeChange(t *testing.T) { cfg.StaticFeeConfig.CreateBlockchainTxFee = test.fee factory := txstest.NewWalletFactory(env.ctx, &cfg, env.state) - builder, signer := factory.NewWallet(preFundedKeys...) + builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewCreateChainTx( testSubnet1.ID(), nil, diff --git a/vms/platformvm/txs/executor/create_subnet_test.go b/vms/platformvm/txs/executor/create_subnet_test.go index a991bda7de0e..ad51fdc0b2b0 100644 --- a/vms/platformvm/txs/executor/create_subnet_test.go +++ b/vms/platformvm/txs/executor/create_subnet_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/platformvm/utxo" @@ -23,7 +24,7 @@ import ( ) func TestCreateSubnetTxAP3FeeChange(t *testing.T) { - ap3Time := defaultGenesisTime.Add(time.Hour) + ap3Time := genesistest.DefaultValidatorStartTime.Add(time.Hour) tests := []struct { name string time time.Time @@ -32,7 +33,7 @@ func TestCreateSubnetTxAP3FeeChange(t *testing.T) { }{ { name: "pre-fork - correctly priced", - time: defaultGenesisTime, + time: genesistest.DefaultValidatorStartTime, fee: 0, expectedErr: nil, }, @@ -60,15 +61,15 @@ func TestCreateSubnetTxAP3FeeChange(t *testing.T) { env.state.SetTimestamp(test.time) // to duly set fee - addrs := set.NewSet[ids.ShortID](len(preFundedKeys)) - for _, key := range preFundedKeys { + addrs := set.NewSet[ids.ShortID](len(genesistest.DefaultFundedKeys)) + for _, key := range genesistest.DefaultFundedKeys { addrs.Add(key.Address()) } cfg := *env.config cfg.StaticFeeConfig.CreateSubnetTxFee = test.fee factory := txstest.NewWalletFactory(env.ctx, &cfg, env.state) - builder, signer := factory.NewWallet(preFundedKeys...) + builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{}, ) diff --git a/vms/platformvm/txs/executor/export_test.go b/vms/platformvm/txs/executor/export_test.go index d392f0bc9618..a6f292c92c33 100644 --- a/vms/platformvm/txs/executor/export_test.go +++ b/vms/platformvm/txs/executor/export_test.go @@ -14,6 +14,7 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/secp256k1fx" @@ -32,14 +33,14 @@ func TestNewExportTx(t *testing.T) { timestamp time.Time } - sourceKey := preFundedKeys[0] + sourceKey := genesistest.DefaultFundedKeys[0] tests := []test{ { description: "P->X export", destinationChainID: env.ctx.XChainID, sourceKeys: []*secp256k1.PrivateKey{sourceKey}, - timestamp: defaultValidateStartTime, + timestamp: genesistest.DefaultValidatorStartTime, }, { description: "P->C export", @@ -60,7 +61,7 @@ func TestNewExportTx(t *testing.T) { []*avax.TransferableOutput{{ Asset: avax.Asset{ID: env.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: defaultBalance - defaultTxFee, + Amt: genesistest.DefaultInitialBalance - defaultTxFee, OutputOwners: secp256k1fx.OutputOwners{ Locktime: 0, Threshold: 1, diff --git a/vms/platformvm/txs/executor/helpers_test.go b/vms/platformvm/txs/executor/helpers_test.go index 4005c32fddaa..e740178fbe48 100644 --- a/vms/platformvm/txs/executor/helpers_test.go +++ b/vms/platformvm/txs/executor/helpers_test.go @@ -5,7 +5,6 @@ package executor import ( "context" - "fmt" "math" "testing" "time" @@ -26,16 +25,12 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/utils/formatting" - "github.com/ava-labs/avalanchego/utils/formatting/address" - "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" - "github.com/ava-labs/avalanchego/vms/platformvm/api" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/fx" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" @@ -51,35 +46,20 @@ import ( ) const ( - defaultWeight = 5 * units.MilliAvax - trackChecksum = false -) + defaultMinValidatorStake = 5 * units.MilliAvax -var ( defaultMinStakingDuration = 24 * time.Hour defaultMaxStakingDuration = 365 * 24 * time.Hour - defaultGenesisTime = time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC) - defaultValidateStartTime = defaultGenesisTime - defaultValidateEndTime = defaultValidateStartTime.Add(20 * defaultMinStakingDuration) - defaultMinValidatorStake = 5 * units.MilliAvax - defaultBalance = 100 * defaultMinValidatorStake - preFundedKeys = secp256k1.TestKeys() - defaultTxFee = uint64(100) - lastAcceptedID = ids.GenerateTestID() - - testSubnet1 *txs.Tx - testSubnet1ControlKeys = preFundedKeys[0:3] - // Node IDs of genesis validators. Initialized in init function - genesisNodeIDs []ids.NodeID + defaultTxFee = 100 * units.NanoAvax ) -func init() { - genesisNodeIDs = make([]ids.NodeID, len(preFundedKeys)) - for i := range preFundedKeys { - genesisNodeIDs[i] = ids.GenerateTestNodeID() - } -} +var ( + lastAcceptedID = ids.GenerateTestID() + + testSubnet1 *txs.Tx + testSubnet1ControlKeys = genesistest.DefaultFundedKeys[0:3] +) type mutableSharedMemory struct { atomic.SharedMemory @@ -133,7 +113,7 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { rewards := reward.NewCalculator(config.RewardConfig) baseState := statetest.New(t, statetest.Config{ DB: baseDB, - Genesis: buildGenesisTest(ctx), + Genesis: genesistest.NewBytes(t, genesistest.Config{}), Validators: config.Validators, Upgrades: config.UpgradeConfig, Context: ctx, @@ -205,19 +185,19 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { func addSubnet(t *testing.T, env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 2, Addrs: []ids.ShortID{ - preFundedKeys[0].PublicKey().Address(), - preFundedKeys[1].PublicKey().Address(), - preFundedKeys[2].PublicKey().Address(), + genesistest.DefaultFundedKeys[0].Address(), + genesistest.DefaultFundedKeys[1].Address(), + genesistest.DefaultFundedKeys[2].Address(), }, }, common.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{preFundedKeys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -244,12 +224,12 @@ func addSubnet(t *testing.T, env *environment) { func defaultConfig(f upgradetest.Fork) *config.Config { upgrades := upgradetest.GetConfigWithUpgradeTime( f, - defaultValidateStartTime.Add(-2*time.Second), + genesistest.DefaultValidatorStartTime.Add(-2*time.Second), ) upgradetest.SetTimesTo( &upgrades, min(f, upgradetest.ApricotPhase5), - defaultValidateEndTime, + genesistest.DefaultValidatorEndTime, ) return &config.Config{ @@ -277,10 +257,10 @@ func defaultConfig(f upgradetest.Fork) *config.Config { } func defaultClock(f upgradetest.Fork) *mockable.Clock { - now := defaultGenesisTime + now := genesistest.DefaultValidatorStartTime if f >= upgradetest.Banff { // 1 second after active fork - now = defaultValidateEndTime.Add(-2 * time.Second) + now = genesistest.DefaultValidatorEndTime.Add(-2 * time.Second) } clk := &mockable.Clock{} clk.Set(now) @@ -322,66 +302,3 @@ func defaultFx(clk *mockable.Clock, log logging.Logger, isBootstrapped bool) fx. } return res } - -func buildGenesisTest(ctx *snow.Context) []byte { - genesisUTXOs := make([]api.UTXO, len(preFundedKeys)) - for i, key := range preFundedKeys { - id := key.PublicKey().Address() - addr, err := address.FormatBech32(constants.UnitTestHRP, id.Bytes()) - if err != nil { - panic(err) - } - genesisUTXOs[i] = api.UTXO{ - Amount: json.Uint64(defaultBalance), - Address: addr, - } - } - - genesisValidators := make([]api.GenesisPermissionlessValidator, len(genesisNodeIDs)) - for i, nodeID := range genesisNodeIDs { - addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes()) - if err != nil { - panic(err) - } - genesisValidators[i] = api.GenesisPermissionlessValidator{ - GenesisValidator: api.GenesisValidator{ - StartTime: json.Uint64(defaultValidateStartTime.Unix()), - EndTime: json.Uint64(defaultValidateEndTime.Unix()), - NodeID: nodeID, - }, - RewardOwner: &api.Owner{ - Threshold: 1, - Addresses: []string{addr}, - }, - Staked: []api.UTXO{{ - Amount: json.Uint64(defaultWeight), - Address: addr, - }}, - DelegationFee: reward.PercentDenominator, - } - } - - buildGenesisArgs := api.BuildGenesisArgs{ - NetworkID: json.Uint32(constants.UnitTestID), - AvaxAssetID: ctx.AVAXAssetID, - UTXOs: genesisUTXOs, - Validators: genesisValidators, - Chains: nil, - Time: json.Uint64(defaultGenesisTime.Unix()), - InitialSupply: json.Uint64(360 * units.MegaAvax), - Encoding: formatting.Hex, - } - - buildGenesisResponse := api.BuildGenesisReply{} - platformvmSS := api.StaticService{} - if err := platformvmSS.BuildGenesis(nil, &buildGenesisArgs, &buildGenesisResponse); err != nil { - panic(fmt.Errorf("problem while building platform chain's genesis state: %w", err)) - } - - genesisBytes, err := formatting.Decode(buildGenesisResponse.Encoding, buildGenesisResponse.Bytes) - if err != nil { - panic(err) - } - - return genesisBytes -} diff --git a/vms/platformvm/txs/executor/import_test.go b/vms/platformvm/txs/executor/import_test.go index ed9ff97375af..6cc5c8a0cb38 100644 --- a/vms/platformvm/txs/executor/import_test.go +++ b/vms/platformvm/txs/executor/import_test.go @@ -200,7 +200,7 @@ func fundedSharedMemory( Amt: amt, OutputOwners: secp256k1fx.OutputOwners{ Locktime: 0, - Addrs: []ids.ShortID{sourceKey.PublicKey().Address()}, + Addrs: []ids.ShortID{sourceKey.Address()}, Threshold: 1, }, }, @@ -216,7 +216,7 @@ func fundedSharedMemory( Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - sourceKey.PublicKey().Address().Bytes(), + sourceKey.Address().Bytes(), }, }, }, diff --git a/vms/platformvm/txs/executor/proposal_tx_executor_test.go b/vms/platformvm/txs/executor/proposal_tx_executor_test.go index 0efbae5e65ba..e7d79ca58eba 100644 --- a/vms/platformvm/txs/executor/proposal_tx_executor_test.go +++ b/vms/platformvm/txs/executor/proposal_tx_executor_test.go @@ -16,6 +16,7 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/hashing" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -27,19 +28,19 @@ import ( func TestProposalTxExecuteAddDelegator(t *testing.T) { dummyHeight := uint64(1) - rewardAddress := preFundedKeys[0].PublicKey().Address() - nodeID := genesisNodeIDs[0] + rewardAddress := genesistest.DefaultFundedKeys[0].Address() + nodeID := genesistest.DefaultNodeIDs[0] newValidatorID := ids.GenerateTestNodeID() - newValidatorStartTime := uint64(defaultValidateStartTime.Add(5 * time.Second).Unix()) - newValidatorEndTime := uint64(defaultValidateEndTime.Add(-5 * time.Second).Unix()) + newValidatorStartTime := uint64(genesistest.DefaultValidatorStartTime.Add(5 * time.Second).Unix()) + newValidatorEndTime := uint64(genesistest.DefaultValidatorEndTime.Add(-5 * time.Second).Unix()) // [addMinStakeValidator] adds a new validator to the primary network's // pending validator set with the minimum staking amount addMinStakeValidator := func(env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: newValidatorID, @@ -77,7 +78,7 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { addMaxStakeValidator := func(env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: newValidatorID, @@ -129,23 +130,23 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { { description: "validator stops validating earlier than delegator", stakeAmount: env.config.MinDelegatorStake, - startTime: uint64(defaultValidateStartTime.Unix()) + 1, - endTime: uint64(defaultValidateEndTime.Unix()) + 1, + startTime: genesistest.DefaultValidatorStartTimeUnix + 1, + endTime: genesistest.DefaultValidatorEndTimeUnix + 1, nodeID: nodeID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: nil, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedErr: ErrPeriodMismatch, }, { description: "validator not in the current or pending validator sets", stakeAmount: env.config.MinDelegatorStake, - startTime: uint64(defaultValidateStartTime.Add(5 * time.Second).Unix()), - endTime: uint64(defaultValidateEndTime.Add(-5 * time.Second).Unix()), + startTime: uint64(genesistest.DefaultValidatorStartTime.Add(5 * time.Second).Unix()), + endTime: uint64(genesistest.DefaultValidatorEndTime.Add(-5 * time.Second).Unix()), nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: nil, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedErr: database.ErrNotFound, }, { @@ -154,9 +155,9 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { startTime: newValidatorStartTime - 1, // start validating subnet before primary network endTime: newValidatorEndTime, nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMinStakeValidator, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedErr: ErrPeriodMismatch, }, { @@ -165,9 +166,9 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { startTime: newValidatorStartTime, endTime: newValidatorEndTime + 1, // stop validating subnet after stopping validating primary network nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMinStakeValidator, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedErr: ErrPeriodMismatch, }, { @@ -176,32 +177,32 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { startTime: newValidatorStartTime, // same start time as for primary network endTime: newValidatorEndTime, // same end time as for primary network nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMinStakeValidator, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedErr: nil, }, { description: "starts delegating at current timestamp", stakeAmount: env.config.MinDelegatorStake, startTime: uint64(currentTimestamp.Unix()), - endTime: uint64(defaultValidateEndTime.Unix()), + endTime: genesistest.DefaultValidatorEndTimeUnix, nodeID: nodeID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: nil, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedErr: ErrTimestampNotBeforeStartTime, }, { description: "tx fee paying key has no funds", stakeAmount: env.config.MinDelegatorStake, - startTime: uint64(defaultValidateStartTime.Unix()) + 1, - endTime: uint64(defaultValidateEndTime.Unix()), + startTime: genesistest.DefaultValidatorStartTimeUnix + 1, + endTime: genesistest.DefaultValidatorEndTimeUnix, nodeID: nodeID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[1]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[1]}, setup: func(env *environment) { // Remove all UTXOs owned by keys[1] utxoIDs, err := env.state.UTXOIDs( - preFundedKeys[1].PublicKey().Address().Bytes(), + genesistest.DefaultFundedKeys[1].Address().Bytes(), ids.Empty, math.MaxInt32) require.NoError(t, err) @@ -212,7 +213,7 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { env.state.SetHeight(dummyHeight) require.NoError(t, env.state.Commit()) }, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedErr: ErrFlowCheckFailed, }, { @@ -221,9 +222,9 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { startTime: newValidatorStartTime, // same start time as for primary network endTime: newValidatorEndTime, // same end time as for primary network nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMaxStakeValidator, - AP3Time: defaultValidateEndTime, + AP3Time: genesistest.DefaultValidatorEndTime, expectedErr: nil, }, { @@ -232,9 +233,9 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { startTime: newValidatorStartTime, // same start time as for primary network endTime: newValidatorEndTime, // same end time as for primary network nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMaxStakeValidator, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedErr: ErrOverDelegated, }, } @@ -292,7 +293,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - nodeID := genesisNodeIDs[0] + nodeID := genesistest.DefaultNodeIDs[0] { // Case: Proposed validator currently validating primary network // but stops validating subnet after stops validating primary network @@ -302,9 +303,9 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()) + 1, - End: uint64(defaultValidateEndTime.Unix()) + 1, - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: genesistest.DefaultValidatorEndTimeUnix + 1, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -341,9 +342,9 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()) + 1, - End: uint64(defaultValidateEndTime.Unix()), - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: genesistest.DefaultValidatorEndTimeUnix, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -372,10 +373,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { // Add a validator to pending validator set of primary network // Starts validating primary network 10 seconds after genesis pendingDSValidatorID := ids.GenerateTestNodeID() - dsStartTime := defaultValidateStartTime.Add(10 * time.Second) + dsStartTime := genesistest.DefaultValidatorStartTime.Add(10 * time.Second) dsEndTime := dsStartTime.Add(5 * defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: pendingDSValidatorID, @@ -402,7 +403,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()), // start validating subnet before primary network End: uint64(dsEndTime.Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -444,7 +445,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) - // Node with ID key.PublicKey().Address() now a pending validator for primary network + // Node with ID key.Address() now a pending validator for primary network { // Case: Proposed validator is pending validator of primary network @@ -456,7 +457,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()) - 1, // start validating subnet before primary network End: uint64(dsEndTime.Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -493,7 +494,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()), End: uint64(dsEndTime.Unix()) + 1, // stop validating subnet after stopping validating primary network - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -530,7 +531,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()), // same start time as for primary network End: uint64(dsEndTime.Unix()), // same end time as for primary network - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -558,7 +559,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { // Case: Proposed validator start validating at/before current timestamp // First, advance the timestamp - newTimestamp := defaultValidateStartTime.Add(2 * time.Second) + newTimestamp := genesistest.DefaultValidatorStartTime.Add(2 * time.Second) env.state.SetTimestamp(newTimestamp) { @@ -569,7 +570,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { NodeID: nodeID, Start: uint64(newTimestamp.Unix()), End: uint64(newTimestamp.Add(defaultMinStakingDuration).Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -597,7 +598,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { } // reset the timestamp - env.state.SetTimestamp(defaultValidateStartTime) + env.state.SetTimestamp(genesistest.DefaultValidatorStartTime) // Case: Proposed validator already validating the subnet // First, add validator as validator of subnet @@ -606,9 +607,9 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()), - End: uint64(defaultValidateEndTime.Unix()), - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix, + End: genesistest.DefaultValidatorEndTimeUnix, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -632,15 +633,15 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { require.NoError(env.state.Commit()) { - // Node with ID nodeIDKey.PublicKey().Address() now validating subnet with ID testSubnet1.ID + // Node with ID nodeIDKey.Address() now validating subnet with ID testSubnet1.ID builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()) + 1, - End: uint64(defaultValidateEndTime.Unix()), - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: genesistest.DefaultValidatorEndTimeUnix, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -678,9 +679,9 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()) + 1, - End: uint64(defaultValidateStartTime.Add(defaultMinStakingDuration).Unix()) + 1, - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: uint64(genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration).Unix()) + 1, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -716,14 +717,14 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { { // Case: Control Signature from invalid key (keys[3] is not a control key) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], preFundedKeys[1]) + builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], genesistest.DefaultFundedKeys[1]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()) + 1, - End: uint64(defaultValidateStartTime.Add(defaultMinStakingDuration).Unix()) + 1, - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: uint64(genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration).Unix()) + 1, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -733,7 +734,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { require.NoError(err) // Replace a valid signature with one from keys[3] - sig, err := preFundedKeys[3].SignHash(hashing.ComputeHash256(tx.Unsigned.Bytes())) + sig, err := genesistest.DefaultFundedKeys[3].SignHash(hashing.ComputeHash256(tx.Unsigned.Bytes())) require.NoError(err) copy(tx.Creds[0].(*secp256k1fx.Credential).Sigs[0][:], sig) @@ -763,9 +764,9 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()) + 1, - End: uint64(defaultValidateStartTime.Add(defaultMinStakingDuration).Unix()) + 1, - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: uint64(genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration).Unix()) + 1, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -818,12 +819,12 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { { // Case: Validator's start time too early - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(chainTime.Unix()), - End: uint64(defaultValidateEndTime.Unix()), + End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, &secp256k1fx.OutputOwners{ @@ -855,15 +856,15 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { } { - nodeID := genesisNodeIDs[0] + nodeID := genesistest.DefaultNodeIDs[0] // Case: Validator already validating primary network - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()) + 1, - End: uint64(defaultValidateEndTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, &secp256k1fx.OutputOwners{ @@ -896,8 +897,8 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { { // Case: Validator in pending validator set of primary network - startTime := defaultValidateStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -950,12 +951,12 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { { // Case: Validator doesn't have enough tokens to cover stake amount - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), - Start: uint64(defaultValidateStartTime.Unix()) + 1, - End: uint64(defaultValidateEndTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, &secp256k1fx.OutputOwners{ @@ -969,7 +970,7 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { require.NoError(err) // Remove all UTXOs owned by preFundedKeys[0] - utxoIDs, err := env.state.UTXOIDs(preFundedKeys[0].PublicKey().Address().Bytes(), ids.Empty, math.MaxInt32) + utxoIDs, err := env.state.UTXOIDs(genesistest.DefaultFundedKeys[0].Address().Bytes(), ids.Empty, math.MaxInt32) require.NoError(err) for _, utxoID := range utxoIDs { diff --git a/vms/platformvm/txs/executor/reward_validator_test.go b/vms/platformvm/txs/executor/reward_validator_test.go index 04dc3c27af9a..27dd9d304937 100644 --- a/vms/platformvm/txs/executor/reward_validator_test.go +++ b/vms/platformvm/txs/executor/reward_validator_test.go @@ -18,6 +18,7 @@ import ( "github.com/ava-labs/avalanchego/utils/math" "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -137,7 +138,7 @@ func TestRewardValidatorTxExecuteOnCommit(t *testing.T) { onCommitBalance, err := avax.GetBalance(env.state, stakeOwners) require.NoError(err) - require.Equal(oldBalance+stakerToRemove.Weight+27697, onCommitBalance) + require.Equal(oldBalance+stakerToRemove.Weight+38944, onCommitBalance) } func TestRewardValidatorTxExecuteOnAbort(t *testing.T) { @@ -246,11 +247,11 @@ func TestRewardDelegatorTxExecuteOnCommitPreDelegateeDeferral(t *testing.T) { vdrRewardAddress := ids.GenerateTestShortID() delRewardAddress := ids.GenerateTestShortID() - vdrStartTime := uint64(defaultValidateStartTime.Unix()) + 1 - vdrEndTime := uint64(defaultValidateStartTime.Add(2 * defaultMinStakingDuration).Unix()) + vdrStartTime := genesistest.DefaultValidatorStartTimeUnix + 1 + vdrEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(2 * defaultMinStakingDuration).Unix()) vdrNodeID := ids.GenerateTestNodeID() - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) uVdrTx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: vdrNodeID, @@ -380,11 +381,11 @@ func TestRewardDelegatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { vdrRewardAddress := ids.GenerateTestShortID() delRewardAddress := ids.GenerateTestShortID() - vdrStartTime := uint64(defaultValidateStartTime.Unix()) + 1 - vdrEndTime := uint64(defaultValidateStartTime.Add(2 * defaultMinStakingDuration).Unix()) + vdrStartTime := genesistest.DefaultValidatorStartTimeUnix + 1 + vdrEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(2 * defaultMinStakingDuration).Unix()) vdrNodeID := ids.GenerateTestNodeID() - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) uVdrTx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: vdrNodeID, @@ -610,11 +611,11 @@ func TestRewardDelegatorTxAndValidatorTxExecuteOnCommitPostDelegateeDeferral(t * vdrRewardAddress := ids.GenerateTestShortID() delRewardAddress := ids.GenerateTestShortID() - vdrStartTime := uint64(defaultValidateStartTime.Unix()) + 1 - vdrEndTime := uint64(defaultValidateStartTime.Add(2 * defaultMinStakingDuration).Unix()) + vdrStartTime := genesistest.DefaultValidatorStartTimeUnix + 1 + vdrEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(2 * defaultMinStakingDuration).Unix()) vdrNodeID := ids.GenerateTestNodeID() - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) uVdrTx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: vdrNodeID, @@ -786,11 +787,11 @@ func TestRewardDelegatorTxExecuteOnAbort(t *testing.T) { vdrRewardAddress := ids.GenerateTestShortID() delRewardAddress := ids.GenerateTestShortID() - vdrStartTime := uint64(defaultValidateStartTime.Unix()) + 1 - vdrEndTime := uint64(defaultValidateStartTime.Add(2 * defaultMinStakingDuration).Unix()) + vdrStartTime := genesistest.DefaultValidatorStartTimeUnix + 1 + vdrEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(2 * defaultMinStakingDuration).Unix()) vdrNodeID := ids.GenerateTestNodeID() - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) uVdrTx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: vdrNodeID, diff --git a/vms/platformvm/txs/executor/standard_tx_executor_test.go b/vms/platformvm/txs/executor/standard_tx_executor_test.go index d6f16a981c7d..d0652e6bd419 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor_test.go +++ b/vms/platformvm/txs/executor/standard_tx_executor_test.go @@ -28,6 +28,7 @@ import ( "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/fx/fxmock" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -53,7 +54,7 @@ func TestStandardTxExecutorAddValidatorTxEmptyID(t *testing.T) { defer env.ctx.Lock.Unlock() chainTime := env.state.GetTimestamp() - startTime := defaultValidateStartTime.Add(1 * time.Second) + startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) tests := []struct { banffTime time.Time @@ -76,12 +77,12 @@ func TestStandardTxExecutorAddValidatorTxEmptyID(t *testing.T) { // Case: Empty validator node ID after banff env.config.UpgradeConfig.BanffTime = test.banffTime - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: ids.EmptyNodeID, Start: uint64(startTime.Unix()), - End: uint64(defaultValidateEndTime.Unix()), + End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, &secp256k1fx.OutputOwners{ @@ -111,19 +112,19 @@ func TestStandardTxExecutorAddValidatorTxEmptyID(t *testing.T) { func TestStandardTxExecutorAddDelegator(t *testing.T) { dummyHeight := uint64(1) - rewardAddress := preFundedKeys[0].PublicKey().Address() - nodeID := genesisNodeIDs[0] + rewardAddress := genesistest.DefaultFundedKeys[0].Address() + nodeID := genesistest.DefaultNodeIDs[0] newValidatorID := ids.GenerateTestNodeID() - newValidatorStartTime := defaultValidateStartTime.Add(5 * time.Second) - newValidatorEndTime := defaultValidateEndTime.Add(-5 * time.Second) + newValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(5 * time.Second) + newValidatorEndTime := genesistest.DefaultValidatorEndTime.Add(-5 * time.Second) // [addMinStakeValidator] adds a new validator to the primary network's // pending validator set with the minimum staking amount addMinStakeValidator := func(env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: newValidatorID, @@ -161,7 +162,7 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { addMaxStakeValidator := func(env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: newValidatorID, @@ -213,23 +214,23 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { { description: "validator stops validating earlier than delegator", stakeAmount: env.config.MinDelegatorStake, - startTime: defaultValidateStartTime.Add(time.Second), - endTime: defaultValidateEndTime.Add(time.Second), + startTime: genesistest.DefaultValidatorStartTime.Add(time.Second), + endTime: genesistest.DefaultValidatorEndTime.Add(time.Second), nodeID: nodeID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: nil, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedExecutionErr: ErrPeriodMismatch, }, { description: "validator not in the current or pending validator sets", stakeAmount: env.config.MinDelegatorStake, - startTime: defaultValidateStartTime.Add(5 * time.Second), - endTime: defaultValidateEndTime.Add(-5 * time.Second), + startTime: genesistest.DefaultValidatorStartTime.Add(5 * time.Second), + endTime: genesistest.DefaultValidatorEndTime.Add(-5 * time.Second), nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: nil, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedExecutionErr: database.ErrNotFound, }, { @@ -238,9 +239,9 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { startTime: newValidatorStartTime.Add(-1 * time.Second), // start validating subnet before primary network endTime: newValidatorEndTime, nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMinStakeValidator, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedExecutionErr: ErrPeriodMismatch, }, { @@ -249,9 +250,9 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { startTime: newValidatorStartTime, endTime: newValidatorEndTime.Add(time.Second), // stop validating subnet after stopping validating primary network nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMinStakeValidator, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedExecutionErr: ErrPeriodMismatch, }, { @@ -260,32 +261,32 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { startTime: newValidatorStartTime, // same start time as for primary network endTime: newValidatorEndTime, // same end time as for primary network nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMinStakeValidator, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedExecutionErr: nil, }, { description: "starts delegating at current timestamp", - stakeAmount: env.config.MinDelegatorStake, // weight - startTime: currentTimestamp, // start time - endTime: defaultValidateEndTime, // end time - nodeID: nodeID, // node ID - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, // tx fee payer + stakeAmount: env.config.MinDelegatorStake, // weight + startTime: currentTimestamp, // start time + endTime: genesistest.DefaultValidatorEndTime, // end time + nodeID: nodeID, // node ID + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, // tx fee payer setup: nil, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedExecutionErr: ErrTimestampNotBeforeStartTime, }, { description: "tx fee paying key has no funds", - stakeAmount: env.config.MinDelegatorStake, // weight - startTime: defaultValidateStartTime.Add(time.Second), // start time - endTime: defaultValidateEndTime, // end time - nodeID: nodeID, // node ID - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[1]}, // tx fee payer + stakeAmount: env.config.MinDelegatorStake, // weight + startTime: genesistest.DefaultValidatorStartTime.Add(time.Second), // start time + endTime: genesistest.DefaultValidatorEndTime, // end time + nodeID: nodeID, // node ID + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[1]}, // tx fee payer setup: func(env *environment) { // Remove all UTXOs owned by keys[1] utxoIDs, err := env.state.UTXOIDs( - preFundedKeys[1].PublicKey().Address().Bytes(), + genesistest.DefaultFundedKeys[1].Address().Bytes(), ids.Empty, math.MaxInt32) require.NoError(t, err) @@ -296,7 +297,7 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { env.state.SetHeight(dummyHeight) require.NoError(t, env.state.Commit()) }, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedExecutionErr: ErrFlowCheckFailed, }, { @@ -305,9 +306,9 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { startTime: newValidatorStartTime, // same start time as for primary network endTime: newValidatorEndTime, // same end time as for primary network nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMaxStakeValidator, - AP3Time: defaultValidateEndTime, + AP3Time: genesistest.DefaultValidatorEndTime, expectedExecutionErr: nil, }, { @@ -316,9 +317,9 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { startTime: newValidatorStartTime, // same start time as for primary network endTime: newValidatorEndTime, // same end time as for primary network nodeID: newValidatorID, - feeKeys: []*secp256k1.PrivateKey{preFundedKeys[0]}, + feeKeys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, setup: addMaxStakeValidator, - AP3Time: defaultGenesisTime, + AP3Time: genesistest.DefaultValidatorStartTime, expectedExecutionErr: ErrOverDelegated, }, } @@ -374,21 +375,21 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - nodeID := genesisNodeIDs[0] + nodeID := genesistest.DefaultNodeIDs[0] { // Case: Proposed validator currently validating primary network // but stops validating subnet after stops validating primary network // (note that keys[0] is a genesis validator) - startTime := defaultValidateStartTime.Add(time.Second) + startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), - End: uint64(defaultValidateEndTime.Unix()) + 1, - Wght: defaultWeight, + End: genesistest.DefaultValidatorEndTimeUnix + 1, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -421,9 +422,9 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix() + 1), - End: uint64(defaultValidateEndTime.Unix()), - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: genesistest.DefaultValidatorEndTimeUnix, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -448,10 +449,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { // Add a validator to pending validator set of primary network // Starts validating primary network 10 seconds after genesis pendingDSValidatorID := ids.GenerateTestNodeID() - dsStartTime := defaultGenesisTime.Add(10 * time.Second) + dsStartTime := genesistest.DefaultValidatorStartTime.Add(10 * time.Second) dsEndTime := dsStartTime.Add(5 * defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: pendingDSValidatorID, @@ -478,7 +479,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()), // start validating subnet before primary network End: uint64(dsEndTime.Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -516,7 +517,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) - // Node with ID key.PublicKey().Address() now a pending validator for primary network + // Node with ID key.Address() now a pending validator for primary network { // Case: Proposed validator is pending validator of primary network @@ -528,7 +529,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()) - 1, // start validating subnet before primary network End: uint64(dsEndTime.Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -561,7 +562,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()), End: uint64(dsEndTime.Unix()) + 1, // stop validating subnet after stopping validating primary network - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -594,7 +595,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()), // same start time as for primary network End: uint64(dsEndTime.Unix()), // same end time as for primary network - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -618,7 +619,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { // Case: Proposed validator start validating at/before current timestamp // First, advance the timestamp - newTimestamp := defaultGenesisTime.Add(2 * time.Second) + newTimestamp := genesistest.DefaultValidatorStartTime.Add(2 * time.Second) env.state.SetTimestamp(newTimestamp) { @@ -629,7 +630,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { NodeID: nodeID, Start: uint64(newTimestamp.Unix()), End: uint64(newTimestamp.Add(defaultMinStakingDuration).Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -653,7 +654,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { } // reset the timestamp - env.state.SetTimestamp(defaultGenesisTime) + env.state.SetTimestamp(genesistest.DefaultValidatorStartTime) // Case: Proposed validator already validating the subnet // First, add validator as validator of subnet @@ -662,9 +663,9 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()), - End: uint64(defaultValidateEndTime.Unix()), - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix, + End: genesistest.DefaultValidatorEndTimeUnix, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -677,7 +678,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { staker, err = state.NewCurrentStaker( subnetTx.ID(), addSubnetValTx, - defaultValidateStartTime, + genesistest.DefaultValidatorStartTime, 0, ) require.NoError(err) @@ -688,16 +689,16 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { require.NoError(env.state.Commit()) { - // Node with ID nodeIDKey.PublicKey().Address() now validating subnet with ID testSubnet1.ID - startTime := defaultValidateStartTime.Add(time.Second) + // Node with ID nodeIDKey.Address() now validating subnet with ID testSubnet1.ID + startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), - End: uint64(defaultValidateEndTime.Unix()), - Wght: defaultWeight, + End: genesistest.DefaultValidatorEndTimeUnix, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -726,7 +727,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Duplicate signatures - startTime := defaultValidateStartTime.Add(time.Second) + startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1], testSubnet1ControlKeys[2]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ @@ -734,7 +735,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(startTime.Add(defaultMinStakingDuration).Unix()) + 1, - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -766,7 +767,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Too few signatures - startTime := defaultValidateStartTime.Add(time.Second) + startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[2]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ @@ -774,7 +775,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(startTime.Add(defaultMinStakingDuration).Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -806,15 +807,15 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Control Signature from invalid key (keys[3] is not a control key) - startTime := defaultValidateStartTime.Add(time.Second) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], preFundedKeys[1]) + startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) + builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], genesistest.DefaultFundedKeys[1]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(startTime.Add(defaultMinStakingDuration).Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -824,7 +825,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { require.NoError(err) // Replace a valid signature with one from keys[3] - sig, err := preFundedKeys[3].SignHash(hashing.ComputeHash256(tx.Unsigned.Bytes())) + sig, err := genesistest.DefaultFundedKeys[3].SignHash(hashing.ComputeHash256(tx.Unsigned.Bytes())) require.NoError(err) copy(tx.Creds[0].(*secp256k1fx.Credential).Sigs[0][:], sig) @@ -845,7 +846,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Proposed validator in pending validator set for subnet // First, add validator to pending validator set of subnet - startTime := defaultValidateStartTime.Add(time.Second) + startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ @@ -853,7 +854,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { NodeID: nodeID, Start: uint64(startTime.Unix()) + 1, End: uint64(startTime.Add(defaultMinStakingDuration).Unix()) + 1, - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -866,7 +867,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { staker, err = state.NewCurrentStaker( subnetTx.ID(), addSubnetValTx, - defaultValidateStartTime, + genesistest.DefaultValidatorStartTime, 0, ) require.NoError(err) @@ -897,16 +898,16 @@ func TestEtnaStandardTxExecutorAddSubnetValidator(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - nodeID := genesisNodeIDs[0] + nodeID := genesistest.DefaultNodeIDs[0] builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix() + 1), - End: uint64(defaultValidateEndTime.Unix()), - Wght: defaultWeight, + Start: genesistest.DefaultValidatorStartTimeUnix + 1, + End: genesistest.DefaultValidatorEndTimeUnix, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -939,12 +940,12 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { { // Case: Validator's start time too early - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, - Start: uint64(defaultValidateStartTime.Unix()) - 1, - End: uint64(defaultValidateEndTime.Unix()), + Start: genesistest.DefaultValidatorStartTimeUnix - 1, + End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, &secp256k1fx.OutputOwners{ @@ -973,8 +974,8 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { { // Case: Validator in current validator set of primary network - startTime := defaultValidateStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -1020,8 +1021,8 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { { // Case: Validator in pending validator set of primary network - startTime := defaultValidateStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -1064,8 +1065,8 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { { // Case: Validator doesn't have enough tokens to cover stake amount - startTime := defaultValidateStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(preFundedKeys[0]) + startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -1084,7 +1085,7 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { require.NoError(err) // Remove all UTXOs owned by preFundedKeys[0] - utxoIDs, err := env.state.UTXOIDs(preFundedKeys[0].PublicKey().Address().Bytes(), ids.Empty, math.MaxInt32) + utxoIDs, err := env.state.UTXOIDs(genesistest.DefaultFundedKeys[0].Address().Bytes(), ids.Empty, math.MaxInt32) require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) @@ -1124,7 +1125,7 @@ func TestDurangoDisabledTransactions(t *testing.T) { endTime = chainTime.Add(defaultMaxStakingDuration) ) - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -1162,7 +1163,7 @@ func TestDurangoDisabledTransactions(t *testing.T) { } it.Release() - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: primaryValidator.NodeID, @@ -1234,7 +1235,7 @@ func TestDurangoMemoField(t *testing.T) { } it.Release() - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -1259,7 +1260,7 @@ func TestDurangoMemoField(t *testing.T) { { name: "CreateChainTx", setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewCreateChainTx( testSubnet1.TxID, []byte{}, @@ -1281,7 +1282,7 @@ func TestDurangoMemoField(t *testing.T) { { name: "CreateSubnetTx", setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 1, @@ -1307,7 +1308,7 @@ func TestDurangoMemoField(t *testing.T) { var ( sourceChain = env.ctx.XChainID - sourceKey = preFundedKeys[1] + sourceKey = genesistest.DefaultFundedKeys[1] sourceAmount = 10 * units.Avax ) @@ -1323,13 +1324,13 @@ func TestDurangoMemoField(t *testing.T) { ) env.msm.SharedMemory = sharedMemory - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewImportTx( sourceChain, &secp256k1fx.OutputOwners{ Locktime: 0, Threshold: 1, - Addrs: []ids.ShortID{sourceKey.PublicKey().Address()}, + Addrs: []ids.ShortID{sourceKey.Address()}, }, common.WithMemo(memoField), ) @@ -1346,7 +1347,7 @@ func TestDurangoMemoField(t *testing.T) { { name: "ExportTx", setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewExportTx( env.ctx.XChainID, []*avax.TransferableOutput{{ @@ -1396,7 +1397,7 @@ func TestDurangoMemoField(t *testing.T) { NodeID: primaryValidator.NodeID, Start: 0, End: uint64(endTime.Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -1416,7 +1417,7 @@ func TestDurangoMemoField(t *testing.T) { Tx: subnetValTx, })) - builder, signer = env.factory.NewWallet(preFundedKeys...) + builder, signer = env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx2, err := builder.NewRemoveSubnetValidatorTx( primaryValidator.NodeID, testSubnet1.ID(), @@ -1432,7 +1433,7 @@ func TestDurangoMemoField(t *testing.T) { { name: "TransformSubnetTx", setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewTransformSubnetTx( testSubnet1.TxID, // subnetID ids.GenerateTestID(), // assetID @@ -1471,7 +1472,7 @@ func TestDurangoMemoField(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(t, err) - builder, txSigner := env.factory.NewWallet(preFundedKeys...) + builder, txSigner := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -1521,7 +1522,7 @@ func TestDurangoMemoField(t *testing.T) { } it.Release() - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewAddPermissionlessDelegatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -1552,7 +1553,7 @@ func TestDurangoMemoField(t *testing.T) { { name: "TransferSubnetOwnershipTx", setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewTransferSubnetOwnershipTx( testSubnet1.TxID, &secp256k1fx.OutputOwners{ @@ -1574,7 +1575,7 @@ func TestDurangoMemoField(t *testing.T) { { name: "BaseTx", setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(preFundedKeys...) + builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) utx, err := builder.NewBaseTx( []*avax.TransferableOutput{ { diff --git a/vms/platformvm/validator_set_property_test.go b/vms/platformvm/validator_set_property_test.go index 3935b75416a9..44ba02e0e1a7 100644 --- a/vms/platformvm/validator_set_property_test.go +++ b/vms/platformvm/validator_set_property_test.go @@ -32,14 +32,10 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" - "github.com/ava-labs/avalanchego/utils/formatting" - "github.com/ava-labs/avalanchego/utils/formatting/address" - "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/timer/mockable" - "github.com/ava-labs/avalanchego/utils/units" - "github.com/ava-labs/avalanchego/vms/platformvm/api" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" @@ -89,7 +85,7 @@ func TestGetValidatorsSetProperty(t *testing.T) { }() nodeID := ids.GenerateTestNodeID() - currentTime := defaultGenesisTime + currentTime := genesistest.DefaultValidatorStartTime vm.clock.Set(currentTime) vm.state.SetTimestamp(currentTime) @@ -260,7 +256,7 @@ func takeValidatorsSnapshotAtCurrentHeight(vm *VM, validatorsSetByHeightAndSubne func addSubnetValidator(vm *VM, data *validatorInputData, subnetID ids.ID) (*state.Staker, error) { factory := txstest.NewWalletFactory(vm.ctx, &vm.Config, vm.state) - builder, signer := factory.NewWallet(keys[0], keys[1]) + builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -273,7 +269,7 @@ func addSubnetValidator(vm *VM, data *validatorInputData, subnetID ids.ID) (*sta }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) if err != nil { @@ -287,7 +283,7 @@ func addSubnetValidator(vm *VM, data *validatorInputData, subnetID ids.ID) (*sta } func addPrimaryValidatorWithBLSKey(vm *VM, data *validatorInputData) (*state.Staker, error) { - addr := keys[0].PublicKey().Address() + addr := genesistest.DefaultFundedKeys[0].Address() sk, err := bls.NewSecretKey() if err != nil { @@ -295,7 +291,7 @@ func addPrimaryValidatorWithBLSKey(vm *VM, data *validatorInputData) (*state.Sta } factory := txstest.NewWalletFactory(vm.ctx, &vm.Config, vm.state) - builder, txSigner := factory.NewWallet(keys[0], keys[1]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -662,9 +658,9 @@ func buildVM(t *testing.T) (*VM, ids.ID, error) { MinStakeDuration: defaultMinStakingDuration, MaxStakeDuration: defaultMaxStakingDuration, RewardConfig: defaultRewardConfig, - UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, defaultGenesisTime), + UpgradeConfig: upgradetest.GetConfigWithUpgradeTime(upgradetest.Durango, genesistest.DefaultValidatorStartTime), }} - vm.clock.Set(defaultGenesisTime.Add(time.Second)) + vm.clock.Set(genesistest.DefaultValidatorStartTime.Add(time.Second)) baseDB := memdb.New() chainDB := prefixdb.New([]byte{0}, baseDB) @@ -684,16 +680,16 @@ func buildVM(t *testing.T) (*VM, ids.ID, error) { return nil } - genesisBytes, err := buildCustomGenesis(ctx.AVAXAssetID) - if err != nil { - return nil, ids.Empty, err - } - - err = vm.Initialize( + err := vm.Initialize( context.Background(), ctx, chainDB, - genesisBytes, + genesistest.NewBytes(t, genesistest.Config{ + NodeIDs: []ids.NodeID{ + genesistest.DefaultNodeIDs[len(genesistest.DefaultNodeIDs)-1], + }, + ValidatorEndTime: mockable.MaxTime, + }), nil, nil, msgChan, @@ -713,15 +709,15 @@ func buildVM(t *testing.T) (*VM, ids.ID, error) { // Note: following Banff activation, block acceptance will move // chain time ahead factory := txstest.NewWalletFactory(vm.ctx, &vm.Config, vm.state) - builder, signer := factory.NewWallet(keys[len(keys)-1]) + builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[len(genesistest.DefaultFundedKeys)-1]) utx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) if err != nil { @@ -754,71 +750,3 @@ func buildVM(t *testing.T) (*VM, ids.ID, error) { return vm, testSubnet1.ID(), nil } - -func buildCustomGenesis(avaxAssetID ids.ID) ([]byte, error) { - genesisUTXOs := make([]api.UTXO, len(keys)) - for i, key := range keys { - id := key.PublicKey().Address() - addr, err := address.FormatBech32(constants.UnitTestHRP, id.Bytes()) - if err != nil { - return nil, err - } - genesisUTXOs[i] = api.UTXO{ - Amount: json.Uint64(defaultBalance), - Address: addr, - } - } - - // we need at least a validator, otherwise BuildBlock would fail, since it - // won't find next staker to promote/evict from stakers set. Contrary to - // what happens with production code we push such validator at the end of - // times, so to avoid interference with our tests - nodeID := genesisNodeIDs[len(genesisNodeIDs)-1] - addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes()) - if err != nil { - return nil, err - } - - starTime := mockable.MaxTime.Add(-1 * defaultMinStakingDuration) - endTime := mockable.MaxTime - genesisValidator := api.GenesisPermissionlessValidator{ - GenesisValidator: api.GenesisValidator{ - StartTime: json.Uint64(starTime.Unix()), - EndTime: json.Uint64(endTime.Unix()), - NodeID: nodeID, - }, - RewardOwner: &api.Owner{ - Threshold: 1, - Addresses: []string{addr}, - }, - Staked: []api.UTXO{{ - Amount: json.Uint64(defaultWeight), - Address: addr, - }}, - DelegationFee: reward.PercentDenominator, - } - - buildGenesisArgs := api.BuildGenesisArgs{ - Encoding: formatting.Hex, - NetworkID: json.Uint32(constants.UnitTestID), - AvaxAssetID: avaxAssetID, - UTXOs: genesisUTXOs, - Validators: []api.GenesisPermissionlessValidator{genesisValidator}, - Chains: nil, - Time: json.Uint64(defaultGenesisTime.Unix()), - InitialSupply: json.Uint64(360 * units.MegaAvax), - } - - buildGenesisResponse := api.BuildGenesisReply{} - platformvmSS := api.StaticService{} - if err := platformvmSS.BuildGenesis(nil, &buildGenesisArgs, &buildGenesisResponse); err != nil { - return nil, err - } - - genesisBytes, err := formatting.Decode(buildGenesisResponse.Encoding, buildGenesisResponse.Bytes) - if err != nil { - return nil, err - } - - return genesisBytes, nil -} diff --git a/vms/platformvm/validators/manager_benchmark_test.go b/vms/platformvm/validators/manager_benchmark_test.go index 905bb8fc2a1d..98227e09913d 100644 --- a/vms/platformvm/validators/manager_benchmark_test.go +++ b/vms/platformvm/validators/manager_benchmark_test.go @@ -17,17 +17,13 @@ import ( "github.com/ava-labs/avalanchego/snow/validators" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" - "github.com/ava-labs/avalanchego/utils/formatting" - "github.com/ava-labs/avalanchego/utils/formatting/address" - "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" - "github.com/ava-labs/avalanchego/vms/platformvm/api" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/metrics" - "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/txs" @@ -56,52 +52,9 @@ func BenchmarkGetValidatorSet(b *testing.B) { require.NoError(db.Close()) }() - avaxAssetID := ids.GenerateTestID() - genesisTime := time.Now().Truncate(time.Second) - genesisEndTime := genesisTime.Add(28 * 24 * time.Hour) - - addr, err := address.FormatBech32(constants.UnitTestHRP, ids.GenerateTestShortID().Bytes()) - require.NoError(err) - - genesisValidators := []api.GenesisPermissionlessValidator{{ - GenesisValidator: api.GenesisValidator{ - StartTime: json.Uint64(genesisTime.Unix()), - EndTime: json.Uint64(genesisEndTime.Unix()), - NodeID: ids.GenerateTestNodeID(), - }, - RewardOwner: &api.Owner{ - Threshold: 1, - Addresses: []string{addr}, - }, - Staked: []api.UTXO{{ - Amount: json.Uint64(2 * units.KiloAvax), - Address: addr, - }}, - DelegationFee: reward.PercentDenominator, - }} - - buildGenesisArgs := api.BuildGenesisArgs{ - NetworkID: json.Uint32(constants.UnitTestID), - AvaxAssetID: avaxAssetID, - UTXOs: nil, - Validators: genesisValidators, - Chains: nil, - Time: json.Uint64(genesisTime.Unix()), - InitialSupply: json.Uint64(360 * units.MegaAvax), - Encoding: formatting.Hex, - } - - buildGenesisResponse := api.BuildGenesisReply{} - platformvmSS := api.StaticService{} - require.NoError(platformvmSS.BuildGenesis(nil, &buildGenesisArgs, &buildGenesisResponse)) - - genesisBytes, err := formatting.Decode(buildGenesisResponse.Encoding, buildGenesisResponse.Bytes) - require.NoError(err) - vdrs := validators.NewManager() s := statetest.New(b, statetest.Config{ DB: db, - Genesis: genesisBytes, Validators: vdrs, }) @@ -121,18 +74,18 @@ func BenchmarkGetValidatorSet(b *testing.B) { ) for i := 0; i < 50; i++ { currentHeight++ - nodeID, err := addPrimaryValidator(s, genesisTime, genesisEndTime, currentHeight) + nodeID, err := addPrimaryValidator(s, genesistest.DefaultValidatorStartTime, genesistest.DefaultValidatorEndTime, currentHeight) require.NoError(err) nodeIDs = append(nodeIDs, nodeID) } subnetID := ids.GenerateTestID() for _, nodeID := range nodeIDs { currentHeight++ - require.NoError(addSubnetValidator(s, subnetID, genesisTime, genesisEndTime, nodeID, currentHeight)) + require.NoError(addSubnetValidator(s, subnetID, genesistest.DefaultValidatorStartTime, genesistest.DefaultValidatorEndTime, nodeID, currentHeight)) } for i := 0; i < 9900; i++ { currentHeight++ - require.NoError(addSubnetDelegator(s, subnetID, genesisTime, genesisEndTime, nodeIDs, currentHeight)) + require.NoError(addSubnetDelegator(s, subnetID, genesistest.DefaultValidatorStartTime, genesistest.DefaultValidatorEndTime, nodeIDs, currentHeight)) } ctx := context.Background() diff --git a/vms/platformvm/vm_regression_test.go b/vms/platformvm/vm_regression_test.go index 851117920bcf..9b4d8b19a5a6 100644 --- a/vms/platformvm/vm_regression_test.go +++ b/vms/platformvm/vm_regression_test.go @@ -35,6 +35,7 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" @@ -58,10 +59,10 @@ func TestAddDelegatorTxOverDelegatedRegression(t *testing.T) { validatorEndTime := validatorStartTime.Add(360 * 24 * time.Hour) nodeID := ids.GenerateTestNodeID() - changeAddr := keys[0].PublicKey().Address() + changeAddr := genesistest.DefaultFundedKeys[0].Address() // create valid tx - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -106,7 +107,7 @@ func TestAddDelegatorTxOverDelegatedRegression(t *testing.T) { firstDelegatorEndTime := firstDelegatorStartTime.Add(vm.MinStakeDuration) // create valid tx - builder, txSigner = factory.NewWallet(keys[0], keys[1]) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) uDelTx1, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: nodeID, @@ -152,7 +153,7 @@ func TestAddDelegatorTxOverDelegatedRegression(t *testing.T) { vm.clock.Set(secondDelegatorStartTime.Add(-10 * executor.SyncBound)) // create valid tx - builder, txSigner = factory.NewWallet(keys[0], keys[1], keys[3]) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[3]) uDelTx2, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: nodeID, @@ -188,7 +189,7 @@ func TestAddDelegatorTxOverDelegatedRegression(t *testing.T) { thirdDelegatorEndTime := thirdDelegatorStartTime.Add(vm.MinStakeDuration) // create valid tx - builder, txSigner = factory.NewWallet(keys[0], keys[1], keys[4]) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) uDelTx3, err := builder.NewAddDelegatorTx( &txs.Validator{ NodeID: nodeID, @@ -247,7 +248,7 @@ func TestAddDelegatorTxHeapCorruption(t *testing.T) { }, { name: "post-upgrade calculate max stake correctly", - ap3Time: defaultGenesisTime, + ap3Time: genesistest.DefaultValidatorStartTime, }, } @@ -264,12 +265,12 @@ func TestAddDelegatorTxHeapCorruption(t *testing.T) { key, err := secp256k1.NewPrivateKey() require.NoError(err) - id := key.PublicKey().Address() + id := key.Address() nodeID := ids.GenerateTestNodeID() - changeAddr := keys[0].PublicKey().Address() + changeAddr := genesistest.DefaultFundedKeys[0].Address() // create valid tx - builder, txSigner := factory.NewWallet(keys[0], keys[1]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -313,7 +314,7 @@ func TestAddDelegatorTxHeapCorruption(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, @@ -346,7 +347,7 @@ func TestAddDelegatorTxHeapCorruption(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, @@ -379,7 +380,7 @@ func TestAddDelegatorTxHeapCorruption(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, @@ -412,7 +413,7 @@ func TestAddDelegatorTxHeapCorruption(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, @@ -463,14 +464,12 @@ func TestUnverifiedParentPanicRegression(t *testing.T) { ctx.Lock.Unlock() }() - _, genesisBytes := defaultGenesis(t, ctx.AVAXAssetID) - msgChan := make(chan common.Message, 1) require.NoError(vm.Initialize( context.Background(), ctx, baseDB, - genesisBytes, + genesistest.NewBytes(t, genesistest.Config{}), nil, nil, msgChan, @@ -485,10 +484,10 @@ func TestUnverifiedParentPanicRegression(t *testing.T) { vm.clock.Set(latestForkTime.Add(time.Second)) vm.state.SetTimestamp(latestForkTime.Add(time.Second)) - key0 := keys[0] - key1 := keys[1] - addr0 := key0.PublicKey().Address() - addr1 := key1.PublicKey().Address() + key0 := genesistest.DefaultFundedKeys[0] + key1 := genesistest.DefaultFundedKeys[1] + addr0 := key0.Address() + addr1 := key1.Address() factory := txstest.NewWalletFactory( vm.ctx, @@ -601,7 +600,7 @@ func TestRejectedStateRegressionInvalidValidatorTimestamp(t *testing.T) { newValidatorEndTime := newValidatorStartTime.Add(defaultMinStakingDuration) // Create the tx to add a new validator - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -798,7 +797,7 @@ func TestRejectedStateRegressionInvalidValidatorReward(t *testing.T) { nodeID0 := ids.GenerateTestNodeID() // Create the tx to add the first new validator - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID0, @@ -967,7 +966,7 @@ func TestRejectedStateRegressionInvalidValidatorReward(t *testing.T) { nodeID1 := ids.GenerateTestNodeID() // Create the tx to add the second new validator - builder, txSigner = factory.NewWallet(keys[1]) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[1]) utx1, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID1, @@ -1102,11 +1101,11 @@ func TestValidatorSetAtCacheOverwriteRegression(t *testing.T) { require.Equal(uint64(1), currentHeight) expectedValidators1 := map[ids.NodeID]uint64{ - genesisNodeIDs[0]: defaultWeight, - genesisNodeIDs[1]: defaultWeight, - genesisNodeIDs[2]: defaultWeight, - genesisNodeIDs[3]: defaultWeight, - genesisNodeIDs[4]: defaultWeight, + genesistest.DefaultNodeIDs[0]: genesistest.DefaultValidatorWeight, + genesistest.DefaultNodeIDs[1]: genesistest.DefaultValidatorWeight, + genesistest.DefaultNodeIDs[2]: genesistest.DefaultValidatorWeight, + genesistest.DefaultNodeIDs[3]: genesistest.DefaultValidatorWeight, + genesistest.DefaultNodeIDs[4]: genesistest.DefaultValidatorWeight, } validators, err := vm.GetValidatorSet(context.Background(), 1, constants.PrimaryNetworkID) require.NoError(err) @@ -1120,7 +1119,7 @@ func TestValidatorSetAtCacheOverwriteRegression(t *testing.T) { extraNodeID := ids.GenerateTestNodeID() // Create the tx to add the first new validator - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: extraNodeID, @@ -1206,12 +1205,12 @@ func TestValidatorSetAtCacheOverwriteRegression(t *testing.T) { } expectedValidators2 := map[ids.NodeID]uint64{ - genesisNodeIDs[0]: defaultWeight, - genesisNodeIDs[1]: defaultWeight, - genesisNodeIDs[2]: defaultWeight, - genesisNodeIDs[3]: defaultWeight, - genesisNodeIDs[4]: defaultWeight, - extraNodeID: vm.MaxValidatorStake, + genesistest.DefaultNodeIDs[0]: genesistest.DefaultValidatorWeight, + genesistest.DefaultNodeIDs[1]: genesistest.DefaultValidatorWeight, + genesistest.DefaultNodeIDs[2]: genesistest.DefaultValidatorWeight, + genesistest.DefaultNodeIDs[3]: genesistest.DefaultValidatorWeight, + genesistest.DefaultNodeIDs[4]: genesistest.DefaultValidatorWeight, + extraNodeID: vm.MaxValidatorStake, } validators, err = vm.GetValidatorSet(context.Background(), 3, constants.PrimaryNetworkID) require.NoError(err) @@ -1244,10 +1243,10 @@ func TestAddDelegatorTxAddBeforeRemove(t *testing.T) { id := key.Address() nodeID := ids.GenerateTestNodeID() - changeAddr := keys[0].PublicKey().Address() + changeAddr := genesistest.DefaultFundedKeys[0].Address() // create valid tx - builder, txSigner := factory.NewWallet(keys[0], keys[1]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -1291,7 +1290,7 @@ func TestAddDelegatorTxAddBeforeRemove(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, @@ -1324,7 +1323,7 @@ func TestAddDelegatorTxAddBeforeRemove(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, @@ -1358,9 +1357,9 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionNotTracked(t id := key.Address() nodeID := ids.GenerateTestNodeID() - changeAddr := keys[0].PublicKey().Address() + changeAddr := genesistest.DefaultFundedKeys[0].Address() - builder, txSigner := factory.NewWallet(keys[0], keys[1]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -1505,11 +1504,11 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t key, err := secp256k1.NewPrivateKey() require.NoError(err) - id := key.PublicKey().Address() + id := key.Address() nodeID := ids.GenerateTestNodeID() - changeAddr := keys[0].PublicKey().Address() + changeAddr := genesistest.DefaultFundedKeys[0].Address() - builder, txSigner := factory.NewWallet(keys[0], keys[1]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -1637,7 +1636,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { subnetID := testSubnet1.TxID // setup time - currentTime := defaultGenesisTime + currentTime := genesistest.DefaultValidatorStartTime vm.clock.Set(currentTime) vm.state.SetTimestamp(currentTime) @@ -1654,13 +1653,13 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { // insert primary network validator var ( nodeID = ids.GenerateTestNodeID() - addr = keys[0].PublicKey().Address() + addr = genesistest.DefaultFundedKeys[0].Address() ) sk1, err := bls.NewSecretKey() require.NoError(err) // build primary network validator with BLS key - builder, txSigner := factory.NewWallet(keys...) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys...) uPrimaryTx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -1709,7 +1708,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { require.NoError(err) // insert the subnet validator - builder, txSigner = factory.NewWallet(keys[0], keys[1]) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -1790,7 +1789,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { require.NoError(err) require.NotEqual(sk1, sk2) - builder, txSigner = factory.NewWallet(keys...) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys...) uPrimaryRestartTx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -1900,7 +1899,7 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { defer vm.ctx.Lock.Unlock() // setup time - currentTime := defaultGenesisTime + currentTime := genesistest.DefaultValidatorStartTime vm.clock.Set(currentTime) vm.state.SetTimestamp(currentTime) @@ -1914,9 +1913,9 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { // Add a primary network validator with no BLS key nodeID := ids.GenerateTestNodeID() - addr := keys[0].PublicKey().Address() + addr := genesistest.DefaultFundedKeys[0].Address() - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) uAddValTx1, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -1986,7 +1985,7 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { sk2, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner = factory.NewWallet(keys...) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys...) uPrimaryRestartTx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -2058,7 +2057,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { subnetID := testSubnet1.TxID // setup time - currentTime := defaultGenesisTime + currentTime := genesistest.DefaultValidatorStartTime vm.clock.Set(currentTime) vm.state.SetTimestamp(currentTime) @@ -2074,9 +2073,9 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { // Add a primary network validator with no BLS key nodeID := ids.GenerateTestNodeID() - addr := keys[0].PublicKey().Address() + addr := genesistest.DefaultFundedKeys[0].Address() - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) uPrimaryTx1, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -2116,7 +2115,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(err) // insert the subnet validator - builder, txSigner = factory.NewWallet(keys[0], keys[1]) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -2196,7 +2195,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { sk2, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner = factory.NewWallet(keys...) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys...) uPrimaryRestartTx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -2277,7 +2276,7 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { subnetID := testSubnet1.TxID // setup time - currentTime := defaultGenesisTime + currentTime := genesistest.DefaultValidatorStartTime vm.clock.Set(currentTime) vm.state.SetTimestamp(currentTime) @@ -2291,9 +2290,9 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { // Add a primary network validator with no BLS key nodeID := ids.GenerateTestNodeID() - addr := keys[0].PublicKey().Address() + addr := genesistest.DefaultFundedKeys[0].Address() - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) uPrimaryTx1, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -2330,7 +2329,7 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { require.NoError(err) // insert the subnet validator - builder, txSigner = factory.NewWallet(keys[0], keys[1]) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ diff --git a/vms/platformvm/vm_test.go b/vms/platformvm/vm_test.go index 89aac04ce947..e6cfada5e7f7 100644 --- a/vms/platformvm/vm_test.go +++ b/vms/platformvm/vm_test.go @@ -40,9 +40,6 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/utils/formatting" - "github.com/ava-labs/avalanchego/utils/formatting/address" - "github.com/ava-labs/avalanchego/utils/json" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/math/meter" "github.com/ava-labs/avalanchego/utils/resource" @@ -52,9 +49,9 @@ import ( "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" - "github.com/ava-labs/avalanchego/vms/platformvm/api" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -76,12 +73,18 @@ import ( walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) -const defaultWeight uint64 = 10000 +const ( + defaultMinDelegatorStake = 1 * units.MilliAvax + defaultMinValidatorStake = 5 * defaultMinDelegatorStake + defaultMaxValidatorStake = 100 * defaultMinValidatorStake -var ( defaultMinStakingDuration = 24 * time.Hour defaultMaxStakingDuration = 365 * 24 * time.Hour + defaultTxFee = 100 * units.NanoAvax +) + +var ( defaultRewardConfig = reward.Config{ MaxConsumptionRate: .12 * reward.PercentDenominator, MinConsumptionRate: .10 * reward.PercentDenominator, @@ -89,28 +92,7 @@ var ( SupplyCap: 720 * units.MegaAvax, } - defaultTxFee = uint64(100) - - // chain timestamp at genesis - defaultGenesisTime = time.Date(1997, 1, 1, 0, 0, 0, 0, time.UTC) - - // time that genesis validators start validating - defaultValidateStartTime = defaultGenesisTime - - // time that genesis validators stop validating - defaultValidateEndTime = defaultValidateStartTime.Add(10 * defaultMinStakingDuration) - - latestForkTime = defaultGenesisTime.Add(time.Second) - - // each key controls an address that has [defaultBalance] AVAX at genesis - keys = secp256k1.TestKeys() - - // Node IDs of genesis validators. Initialized in init function - genesisNodeIDs []ids.NodeID - defaultMinDelegatorStake = 1 * units.MilliAvax - defaultMinValidatorStake = 5 * defaultMinDelegatorStake - defaultMaxValidatorStake = 100 * defaultMinValidatorStake - defaultBalance = 2 * defaultMaxValidatorStake // amount all genesis validators have in defaultVM + latestForkTime = genesistest.DefaultValidatorStartTime.Add(time.Second) defaultStaticFeeConfig = fee.StaticConfig{ TxFee: defaultTxFee, @@ -136,90 +118,19 @@ var ( // Its controlKeys are keys[0], keys[1], keys[2] // Its threshold is 2 testSubnet1 *txs.Tx - testSubnet1ControlKeys = keys[0:3] + testSubnet1ControlKeys = genesistest.DefaultFundedKeys[0:3] ) -func init() { - for _, key := range keys { - // TODO: use ids.GenerateTestNodeID() instead of ids.BuildTestNodeID - // Can be done when TestGetState is refactored - nodeBytes := key.PublicKey().Address() - nodeID := ids.BuildTestNodeID(nodeBytes[:]) - - genesisNodeIDs = append(genesisNodeIDs, nodeID) - } -} - type mutableSharedMemory struct { atomic.SharedMemory } -// Returns: -// 1) The genesis state -// 2) The byte representation of the default genesis for tests -func defaultGenesis(t *testing.T, avaxAssetID ids.ID) (*api.BuildGenesisArgs, []byte) { - require := require.New(t) - - genesisUTXOs := make([]api.UTXO, len(keys)) - for i, key := range keys { - id := key.PublicKey().Address() - addr, err := address.FormatBech32(constants.UnitTestHRP, id.Bytes()) - require.NoError(err) - genesisUTXOs[i] = api.UTXO{ - Amount: json.Uint64(defaultBalance), - Address: addr, - } - } - - genesisValidators := make([]api.GenesisPermissionlessValidator, len(genesisNodeIDs)) - for i, nodeID := range genesisNodeIDs { - addr, err := address.FormatBech32(constants.UnitTestHRP, nodeID.Bytes()) - require.NoError(err) - genesisValidators[i] = api.GenesisPermissionlessValidator{ - GenesisValidator: api.GenesisValidator{ - StartTime: json.Uint64(defaultValidateStartTime.Unix()), - EndTime: json.Uint64(defaultValidateEndTime.Unix()), - NodeID: nodeID, - }, - RewardOwner: &api.Owner{ - Threshold: 1, - Addresses: []string{addr}, - }, - Staked: []api.UTXO{{ - Amount: json.Uint64(defaultWeight), - Address: addr, - }}, - DelegationFee: reward.PercentDenominator, - } - } - - buildGenesisArgs := api.BuildGenesisArgs{ - Encoding: formatting.Hex, - NetworkID: json.Uint32(constants.UnitTestID), - AvaxAssetID: avaxAssetID, - UTXOs: genesisUTXOs, - Validators: genesisValidators, - Chains: nil, - Time: json.Uint64(defaultGenesisTime.Unix()), - InitialSupply: json.Uint64(360 * units.MegaAvax), - } - - buildGenesisResponse := api.BuildGenesisReply{} - platformvmSS := api.StaticService{} - require.NoError(platformvmSS.BuildGenesis(nil, &buildGenesisArgs, &buildGenesisResponse)) - - genesisBytes, err := formatting.Decode(buildGenesisResponse.Encoding, buildGenesisResponse.Bytes) - require.NoError(err) - - return &buildGenesisArgs, genesisBytes -} - func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, database.Database, *mutableSharedMemory) { require := require.New(t) // always reset latestForkTime (a package level variable) // to ensure test independence - latestForkTime = defaultGenesisTime.Add(time.Second) + latestForkTime = genesistest.DefaultValidatorStartTime.Add(time.Second) vm := &VM{Config: config.Config{ Chains: chains.TestManager, UptimeLockedCalculator: uptime.NewLockedCalculator(), @@ -252,7 +163,6 @@ func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, d ctx.Lock.Lock() defer ctx.Lock.Unlock() - _, genesisBytes := defaultGenesis(t, ctx.AVAXAssetID) appSender := &enginetest.Sender{} appSender.CantSendAppGossip = true appSender.SendAppGossipF = func(context.Context, common.SendConfig, []byte) error { @@ -267,7 +177,7 @@ func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, d context.Background(), ctx, chainDB, - genesisBytes, + genesistest.NewBytes(t, genesistest.Config{}), nil, dynamicConfigBytes, msgChan, @@ -289,19 +199,19 @@ func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, d // Create a subnet and store it in testSubnet1 // Note: following Banff activation, block acceptance will move // chain time ahead - builder, signer := factory.NewWallet(keys[0]) + builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 2, Addrs: []ids.ShortID{ - keys[0].PublicKey().Address(), - keys[1].PublicKey().Address(), - keys[2].PublicKey().Address(), + genesistest.DefaultFundedKeys[0].Address(), + genesistest.DefaultFundedKeys[1].Address(), + genesistest.DefaultFundedKeys[2].Address(), }, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -343,35 +253,31 @@ func TestGenesis(t *testing.T) { require.NoError(err) require.NotNil(genesisBlock) - genesisState, _ := defaultGenesis(t, vm.ctx.AVAXAssetID) + genesisState := genesistest.New(t, genesistest.Config{}) // Ensure all the genesis UTXOs are there for _, utxo := range genesisState.UTXOs { - _, addrBytes, err := address.ParseBech32(utxo.Address) - require.NoError(err) - - addr, err := ids.ToShortID(addrBytes) - require.NoError(err) - - addrs := set.Of(addr) - utxos, err := avax.GetAllUTXOs(vm.state, addrs) + genesisOut := utxo.Out.(*secp256k1fx.TransferOutput) + utxos, err := avax.GetAllUTXOs( + vm.state, + genesisOut.OutputOwners.AddressesSet(), + ) require.NoError(err) require.Len(utxos, 1) out := utxos[0].Out.(*secp256k1fx.TransferOutput) - if out.Amount() != uint64(utxo.Amount) { - id := keys[0].PublicKey().Address() - addr, err := address.FormatBech32(constants.UnitTestHRP, id.Bytes()) - require.NoError(err) - - require.Equal(utxo.Address, addr) - require.Equal(uint64(utxo.Amount)-vm.StaticFeeConfig.CreateSubnetTxFee, out.Amount()) + if out.Amt != genesisOut.Amt { + require.Equal( + []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, + out.OutputOwners.Addrs, + ) + require.Equal(genesisOut.Amt-vm.StaticFeeConfig.CreateSubnetTxFee, out.Amt) } } // Ensure current validator set of primary network is correct require.Len(genesisState.Validators, vm.Validators.Count(constants.PrimaryNetworkID)) - for _, nodeID := range genesisNodeIDs { + for _, nodeID := range genesistest.DefaultNodeIDs { _, ok := vm.Validators.GetValidator(constants.PrimaryNetworkID, nodeID) require.True(ok) } @@ -399,7 +305,7 @@ func TestAddValidatorCommit(t *testing.T) { require.NoError(err) // create valid tx - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -454,11 +360,11 @@ func TestInvalidAddValidatorCommit(t *testing.T) { defer vm.ctx.Lock.Unlock() nodeID := ids.GenerateTestNodeID() - startTime := defaultGenesisTime.Add(-txexecutor.SyncBound).Add(-1 * time.Second) + startTime := genesistest.DefaultValidatorStartTime.Add(-txexecutor.SyncBound).Add(-1 * time.Second) endTime := startTime.Add(defaultMinStakingDuration) // create invalid tx - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -517,7 +423,7 @@ func TestAddValidatorReject(t *testing.T) { ) // create valid tx - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddValidatorTx( &txs.Validator{ NodeID: nodeID, @@ -561,7 +467,7 @@ func TestAddValidatorInvalidNotReissued(t *testing.T) { defer vm.ctx.Lock.Unlock() // Use nodeID that is already in the genesis - repeatNodeID := genesisNodeIDs[0] + repeatNodeID := genesistest.DefaultNodeIDs[0] startTime := latestForkTime.Add(txexecutor.SyncBound).Add(1 * time.Second) endTime := startTime.Add(defaultMinStakingDuration) @@ -570,7 +476,7 @@ func TestAddValidatorInvalidNotReissued(t *testing.T) { require.NoError(err) // create valid tx - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -614,12 +520,12 @@ func TestAddSubnetValidatorAccept(t *testing.T) { var ( startTime = vm.clock.Time().Add(txexecutor.SyncBound).Add(1 * time.Second) endTime = startTime.Add(defaultMinStakingDuration) - nodeID = genesisNodeIDs[0] + nodeID = genesistest.DefaultNodeIDs[0] ) // create valid tx // note that [startTime, endTime] is a subset of time that keys[0] - // validates primary network ([defaultValidateStartTime, defaultValidateEndTime]) + // validates primary network ([genesistest.DefaultValidatorStartTime, genesistest.DefaultValidatorEndTime]) builder, txSigner := factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ @@ -627,7 +533,7 @@ func TestAddSubnetValidatorAccept(t *testing.T) { NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(endTime.Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -666,12 +572,12 @@ func TestAddSubnetValidatorReject(t *testing.T) { var ( startTime = vm.clock.Time().Add(txexecutor.SyncBound).Add(1 * time.Second) endTime = startTime.Add(defaultMinStakingDuration) - nodeID = genesisNodeIDs[0] + nodeID = genesistest.DefaultNodeIDs[0] ) // create valid tx // note that [startTime, endTime] is a subset of time that keys[0] - // validates primary network ([defaultValidateStartTime, defaultValidateEndTime]) + // validates primary network ([genesistest.DefaultValidatorStartTime, genesistest.DefaultValidatorEndTime]) builder, txSigner := factory.NewWallet(testSubnet1ControlKeys[1], testSubnet1ControlKeys[2]) utx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ @@ -679,7 +585,7 @@ func TestAddSubnetValidatorReject(t *testing.T) { NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(endTime.Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: testSubnet1.ID(), }, @@ -715,7 +621,7 @@ func TestRewardValidatorAccept(t *testing.T) { defer vm.ctx.Lock.Unlock() // Fast forward clock to time for genesis validators to leave - vm.clock.Set(defaultValidateEndTime) + vm.clock.Set(genesistest.DefaultValidatorEndTime) // Advance time and create proposal to reward a genesis validator blk, err := vm.Builder.BuildBlock(context.Background()) @@ -753,7 +659,7 @@ func TestRewardValidatorAccept(t *testing.T) { // Verify that chain's timestamp has advanced timestamp := vm.state.GetTimestamp() - require.Equal(defaultValidateEndTime.Unix(), timestamp.Unix()) + require.Equal(genesistest.DefaultValidatorEndTimeUnix, uint64(timestamp.Unix())) // Verify that rewarded validator has been removed. // Note that test genesis has multiple validators @@ -783,7 +689,7 @@ func TestRewardValidatorReject(t *testing.T) { defer vm.ctx.Lock.Unlock() // Fast forward clock to time for genesis validators to leave - vm.clock.Set(defaultValidateEndTime) + vm.clock.Set(genesistest.DefaultValidatorEndTime) // Advance time and create proposal to reward a genesis validator blk, err := vm.Builder.BuildBlock(context.Background()) @@ -823,7 +729,7 @@ func TestRewardValidatorReject(t *testing.T) { // Verify that chain's timestamp has advanced timestamp := vm.state.GetTimestamp() - require.Equal(defaultValidateEndTime.Unix(), timestamp.Unix()) + require.Equal(genesistest.DefaultValidatorEndTimeUnix, uint64(timestamp.Unix())) // Verify that rewarded validator has been removed. // Note that test genesis has multiple validators @@ -913,18 +819,18 @@ func TestCreateSubnet(t *testing.T) { vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) uCreateSubnetTx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ - keys[0].PublicKey().Address(), - keys[1].PublicKey().Address(), + genesistest.DefaultFundedKeys[0].Address(), + genesistest.DefaultFundedKeys[1].Address(), }, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -953,7 +859,7 @@ func TestCreateSubnet(t *testing.T) { require.Contains(subnetIDs, subnetID) // Now that we've created a new subnet, add a validator to that subnet - nodeID := genesisNodeIDs[0] + nodeID := genesistest.DefaultNodeIDs[0] startTime := vm.clock.Time().Add(txexecutor.SyncBound).Add(1 * time.Second) endTime := startTime.Add(defaultMinStakingDuration) // [startTime, endTime] is subset of time keys[0] validates default subnet so tx is valid @@ -963,7 +869,7 @@ func TestCreateSubnet(t *testing.T) { NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(endTime.Unix()), - Wght: defaultWeight, + Wght: genesistest.DefaultValidatorWeight, }, Subnet: subnetID, }, @@ -1020,19 +926,19 @@ func TestAtomicImport(t *testing.T) { OutputIndex: 1, } amount := uint64(50000) - recipientKey := keys[1] + recipientKey := genesistest.DefaultFundedKeys[1] m := atomic.NewMemory(prefixdb.New([]byte{5}, baseDB)) mutableSharedMemory.SharedMemory = m.NewSharedMemory(vm.ctx.ChainID) peerSharedMemory := m.NewSharedMemory(vm.ctx.XChainID) - builder, _ := factory.NewWallet(keys[0]) + builder, _ := factory.NewWallet(genesistest.DefaultFundedKeys[0]) _, err := builder.NewImportTx( vm.ctx.XChainID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{recipientKey.PublicKey().Address()}, + Addrs: []ids.ShortID{recipientKey.Address()}, }, ) require.ErrorIs(err, walletbuilder.ErrInsufficientFunds) @@ -1046,7 +952,7 @@ func TestAtomicImport(t *testing.T) { Amt: amount, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{recipientKey.PublicKey().Address()}, + Addrs: []ids.ShortID{recipientKey.Address()}, }, }, } @@ -1061,7 +967,7 @@ func TestAtomicImport(t *testing.T) { Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - recipientKey.PublicKey().Address().Bytes(), + recipientKey.Address().Bytes(), }, }, }, @@ -1073,7 +979,7 @@ func TestAtomicImport(t *testing.T) { vm.ctx.XChainID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{recipientKey.PublicKey().Address()}, + Addrs: []ids.ShortID{recipientKey.Address()}, }, ) require.NoError(err) @@ -1175,7 +1081,7 @@ func TestRestartFullyAccepted(t *testing.T) { firstCtx := snowtest.Context(t, snowtest.PChainID) - _, genesisBytes := defaultGenesis(t, firstCtx.AVAXAssetID) + genesisBytes := genesistest.NewBytes(t, genesistest.Config{}) baseDB := memdb.New() atomicDB := prefixdb.New([]byte{1}, baseDB) @@ -1308,8 +1214,6 @@ func TestBootstrapPartiallyAccepted(t *testing.T) { vm.clock.Set(initialClkTime) ctx := snowtest.Context(t, snowtest.PChainID) - _, genesisBytes := defaultGenesis(t, ctx.AVAXAssetID) - atomicDB := prefixdb.New([]byte{1}, baseDB) m := atomic.NewMemory(atomicDB) ctx.SharedMemory = m.NewSharedMemory(ctx.ChainID) @@ -1322,7 +1226,7 @@ func TestBootstrapPartiallyAccepted(t *testing.T) { context.Background(), ctx, vmDB, - genesisBytes, + genesistest.NewBytes(t, genesistest.Config{}), nil, nil, msgChan, @@ -1659,14 +1563,12 @@ func TestUnverifiedParent(t *testing.T) { ctx.Lock.Unlock() }() - _, genesisBytes := defaultGenesis(t, ctx.AVAXAssetID) - msgChan := make(chan common.Message, 1) require.NoError(vm.Initialize( context.Background(), ctx, memdb.New(), - genesisBytes, + genesistest.NewBytes(t, genesistest.Config{}), nil, nil, msgChan, @@ -1750,7 +1652,7 @@ func TestMaxStakeAmount(t *testing.T) { vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - nodeID := genesisNodeIDs[0] + nodeID := genesistest.DefaultNodeIDs[0] tests := []struct { description string @@ -1759,23 +1661,23 @@ func TestMaxStakeAmount(t *testing.T) { }{ { description: "[validator.StartTime] == [startTime] < [endTime] == [validator.EndTime]", - startTime: defaultValidateStartTime, - endTime: defaultValidateEndTime, + startTime: genesistest.DefaultValidatorStartTime, + endTime: genesistest.DefaultValidatorEndTime, }, { description: "[validator.StartTime] < [startTime] < [endTime] == [validator.EndTime]", - startTime: defaultValidateStartTime.Add(time.Minute), - endTime: defaultValidateEndTime, + startTime: genesistest.DefaultValidatorStartTime.Add(time.Minute), + endTime: genesistest.DefaultValidatorEndTime, }, { description: "[validator.StartTime] == [startTime] < [endTime] < [validator.EndTime]", - startTime: defaultValidateStartTime, - endTime: defaultValidateEndTime.Add(-time.Minute), + startTime: genesistest.DefaultValidatorStartTime, + endTime: genesistest.DefaultValidatorEndTime.Add(-time.Minute), }, { description: "[validator.StartTime] < [startTime] < [endTime] < [validator.EndTime]", - startTime: defaultValidateStartTime.Add(time.Minute), - endTime: defaultValidateEndTime.Add(-time.Minute), + startTime: genesistest.DefaultValidatorStartTime.Add(time.Minute), + endTime: genesistest.DefaultValidatorEndTime.Add(-time.Minute), }, } @@ -1787,14 +1689,14 @@ func TestMaxStakeAmount(t *testing.T) { amount, err := txexecutor.GetMaxWeight(vm.state, staker, test.startTime, test.endTime) require.NoError(err) - require.Equal(defaultWeight, amount) + require.Equal(genesistest.DefaultValidatorWeight, amount) }) } } func TestUptimeDisallowedWithRestart(t *testing.T) { require := require.New(t) - latestForkTime = defaultValidateStartTime.Add(defaultMinStakingDuration) + latestForkTime = genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) db := memdb.New() firstDB := prefixdb.New([]byte{}, db) @@ -1811,7 +1713,7 @@ func TestUptimeDisallowedWithRestart(t *testing.T) { firstCtx := snowtest.Context(t, snowtest.PChainID) firstCtx.Lock.Lock() - _, genesisBytes := defaultGenesis(t, firstCtx.AVAXAssetID) + genesisBytes := genesistest.NewBytes(t, genesistest.Config{}) firstMsgChan := make(chan common.Message, 1) require.NoError(firstVM.Initialize( @@ -1834,8 +1736,8 @@ func TestUptimeDisallowedWithRestart(t *testing.T) { require.NoError(firstVM.SetState(context.Background(), snow.NormalOp)) // Fast forward clock so that validators meet 20% uptime required for reward - durationForReward := defaultValidateEndTime.Sub(defaultValidateStartTime) * firstUptimePercentage / 100 - vmStopTime := defaultValidateStartTime.Add(durationForReward) + durationForReward := genesistest.DefaultValidatorEndTime.Sub(genesistest.DefaultValidatorStartTime) * firstUptimePercentage / 100 + vmStopTime := genesistest.DefaultValidatorStartTime.Add(durationForReward) firstVM.clock.Set(vmStopTime) // Shutdown VM to stop all genesis validator uptime. @@ -1885,7 +1787,7 @@ func TestUptimeDisallowedWithRestart(t *testing.T) { require.NoError(secondVM.SetState(context.Background(), snow.NormalOp)) // after restart and change of uptime required for reward, push validators to their end of life - secondVM.clock.Set(defaultValidateEndTime) + secondVM.clock.Set(genesistest.DefaultValidatorEndTime) // evaluate a genesis validator for reward blk, err := secondVM.Builder.BuildBlock(context.Background()) @@ -1938,7 +1840,7 @@ func TestUptimeDisallowedWithRestart(t *testing.T) { func TestUptimeDisallowedAfterNeverConnecting(t *testing.T) { require := require.New(t) - latestForkTime = defaultValidateStartTime.Add(defaultMinStakingDuration) + latestForkTime = genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) db := memdb.New() @@ -1954,8 +1856,6 @@ func TestUptimeDisallowedAfterNeverConnecting(t *testing.T) { ctx := snowtest.Context(t, snowtest.PChainID) ctx.Lock.Lock() - _, genesisBytes := defaultGenesis(t, ctx.AVAXAssetID) - atomicDB := prefixdb.New([]byte{1}, db) m := atomic.NewMemory(atomicDB) ctx.SharedMemory = m.NewSharedMemory(ctx.ChainID) @@ -1966,7 +1866,7 @@ func TestUptimeDisallowedAfterNeverConnecting(t *testing.T) { context.Background(), ctx, db, - genesisBytes, + genesistest.NewBytes(t, genesistest.Config{}), nil, nil, msgChan, @@ -1987,7 +1887,7 @@ func TestUptimeDisallowedAfterNeverConnecting(t *testing.T) { require.NoError(vm.SetState(context.Background(), snow.NormalOp)) // Fast forward clock to time for genesis validators to leave - vm.clock.Set(defaultValidateEndTime) + vm.clock.Set(genesistest.DefaultValidatorEndTime) // evaluate a genesis validator for reward blk, err := vm.Builder.BuildBlock(context.Background()) @@ -2051,12 +1951,12 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { key, err := secp256k1.NewPrivateKey() require.NoError(err) - id := key.PublicKey().Address() + id := key.Address() nodeID := ids.GenerateTestNodeID() sk, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) uAddValTx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -2080,7 +1980,7 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { reward.PercentDenominator, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -2105,7 +2005,7 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -2123,7 +2023,7 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { require.NoError(createSubnetBlock.Accept(context.Background())) require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) - builder, txSigner = factory.NewWallet(key, keys[1]) + builder, txSigner = factory.NewWallet(key, genesistest.DefaultFundedKeys[1]) uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -2136,20 +2036,20 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[1].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[1].Address()}, }), ) require.NoError(err) addSubnetValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddSubnetValTx) require.NoError(err) - builder, txSigner = factory.NewWallet(key, keys[2]) + builder, txSigner = factory.NewWallet(key, genesistest.DefaultFundedKeys[2]) uRemoveSubnetValTx, err := builder.NewRemoveSubnetValidatorTx( nodeID, createSubnetTx.ID(), walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[2].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, }), ) require.NoError(err) @@ -2184,15 +2084,15 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) uCreateSubnetTx, err := builder.NewCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[0].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }), ) require.NoError(err) @@ -2221,7 +2121,7 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { Locktime: 0, Threshold: 1, Addrs: []ids.ShortID{ - keys[0].PublicKey().Address(), + genesistest.DefaultFundedKeys[0].Address(), }, } ctx, err := walletbuilder.NewSnowContext(vm.ctx.NetworkID, vm.ctx.AVAXAssetID) @@ -2233,7 +2133,7 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { subnetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[1].PublicKey().Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[1].Address()}, }, ) require.NoError(err) @@ -2260,7 +2160,7 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { Locktime: 0, Threshold: 1, Addrs: []ids.ShortID{ - keys[1].PublicKey().Address(), + genesistest.DefaultFundedKeys[1].Address(), }, } expectedOwner.InitCtx(ctx) @@ -2276,7 +2176,7 @@ func TestBaseTx(t *testing.T) { sendAmt := uint64(100000) changeAddr := ids.ShortEmpty - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewBaseTx( []*avax.TransferableOutput{ { @@ -2286,7 +2186,7 @@ func TestBaseTx(t *testing.T) { OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ - keys[1].Address(), + genesistest.DefaultFundedKeys[1].Address(), }, }, }, @@ -2308,7 +2208,7 @@ func TestBaseTx(t *testing.T) { require.NoError(err) require.IsType(&secp256k1fx.TransferOutput{}, utxo.Out) castOut := utxo.Out.(*secp256k1fx.TransferOutput) - if castOut.AddressesSet().Equals(set.Of(keys[0].Address())) { + if castOut.AddressesSet().Equals(set.Of(genesistest.DefaultFundedKeys[0].Address())) { key0InputAmt += castOut.Amt } totalInputAmt += castOut.Amt @@ -2322,10 +2222,10 @@ func TestBaseTx(t *testing.T) { for _, output := range baseTx.Unsigned.Outputs() { require.IsType(&secp256k1fx.TransferOutput{}, output.Out) castOut := output.Out.(*secp256k1fx.TransferOutput) - if castOut.AddressesSet().Equals(set.Of(keys[0].Address())) { + if castOut.AddressesSet().Equals(set.Of(genesistest.DefaultFundedKeys[0].Address())) { key0OutputAmt += castOut.Amt } - if castOut.AddressesSet().Equals(set.Of(keys[1].Address())) { + if castOut.AddressesSet().Equals(set.Of(genesistest.DefaultFundedKeys[1].Address())) { key1OutputAmt += castOut.Amt } if castOut.AddressesSet().Equals(set.Of(changeAddr)) { @@ -2363,7 +2263,7 @@ func TestPruneMempool(t *testing.T) { sendAmt := uint64(100000) changeAddr := ids.ShortEmpty - builder, txSigner := factory.NewWallet(keys[0]) + builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) utx, err := builder.NewBaseTx( []*avax.TransferableOutput{ { @@ -2373,7 +2273,7 @@ func TestPruneMempool(t *testing.T) { OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ - keys[1].Address(), + genesistest.DefaultFundedKeys[1].Address(), }, }, }, @@ -2406,7 +2306,7 @@ func TestPruneMempool(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner = factory.NewWallet(keys[1]) + builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[1]) uAddValTx, err := builder.NewAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ @@ -2421,11 +2321,11 @@ func TestPruneMempool(t *testing.T) { vm.ctx.AVAXAssetID, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[2].Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{keys[2].Address()}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, }, 20000, ) From c359dbb80cc19300ee795f662380b0e75e3c2602 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Sat, 24 Aug 2024 00:01:46 -0400 Subject: [PATCH 43/69] Simplify P-Chain transaction creation in unit tests (#3327) --- vms/platformvm/service_test.go | 166 ++-- vms/platformvm/txs/txstest/wallet.go | 121 +++ vms/platformvm/validator_set_property_test.go | 109 +-- vms/platformvm/vm_regression_test.go | 894 +++++------------- vms/platformvm/vm_test.go | 592 ++++-------- 5 files changed, 681 insertions(+), 1201 deletions(-) create mode 100644 vms/platformvm/txs/txstest/wallet.go diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index 47e8a48ef578..24edafbeca83 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -43,7 +43,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" @@ -53,7 +52,6 @@ import ( blockbuilder "github.com/ava-labs/avalanchego/vms/platformvm/block/builder" blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) var ( @@ -80,22 +78,21 @@ var ( } ) -func defaultService(t *testing.T) (*Service, *mutableSharedMemory, *txstest.WalletFactory) { - vm, factory, _, mutableSharedMemory := defaultVM(t, upgradetest.Latest) - +func defaultService(t *testing.T) (*Service, *mutableSharedMemory) { + vm, _, mutableSharedMemory := defaultVM(t, upgradetest.Latest) return &Service{ vm: vm, addrManager: avax.NewAddressManager(vm.ctx), stakerAttributesCache: &cache.LRU[ids.ID, *stakerAttributes]{ Size: stakerAttributesCacheSize, }, - }, mutableSharedMemory, factory + }, mutableSharedMemory } func TestExportKey(t *testing.T) { require := require.New(t) - service, _, _ := defaultService(t) + service, _ := defaultService(t) service.vm.ctx.Lock.Lock() ks := keystore.New(logging.NoLog{}, memdb.New()) @@ -125,7 +122,7 @@ func TestExportKey(t *testing.T) { // Test issuing a tx and accepted func TestGetTxStatus(t *testing.T) { require := require.New(t) - service, mutableSharedMemory, factory := defaultService(t) + service, mutableSharedMemory := defaultService(t) service.vm.ctx.Lock.Lock() recipientKey, err := secp256k1.NewPrivateKey() @@ -173,8 +170,10 @@ func TestGetTxStatus(t *testing.T) { mutableSharedMemory.SharedMemory = sm - builder, signer := factory.NewWallet(recipientKey) - utx, err := builder.NewImportTx( + wallet := newWallet(t, service.vm, walletConfig{ + keys: []*secp256k1.PrivateKey{recipientKey}, + }) + tx, err := wallet.IssueImportTx( service.vm.ctx.XChainID, &secp256k1fx.OutputOwners{ Threshold: 1, @@ -182,8 +181,6 @@ func TestGetTxStatus(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) service.vm.ctx.Lock.Unlock() @@ -219,32 +216,34 @@ func TestGetTxStatus(t *testing.T) { func TestGetTx(t *testing.T) { type test struct { description string - createTx func(service *Service, factory *txstest.WalletFactory) (*txs.Tx, error) + createTx func(t testing.TB, s *Service) *txs.Tx } tests := []test{ { "standard block", - func(_ *Service, factory *txstest.WalletFactory) (*txs.Tx, error) { - builder, signer := factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + func(t testing.TB, s *Service) *txs.Tx { + subnetID := testSubnet1.ID() + wallet := newWallet(t, s.vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueCreateChainTx( + subnetID, []byte{}, constants.AVMID, []ids.ID{}, "chain name", - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(t, err) - return walletsigner.SignUnsigned(context.Background(), signer, utx) + return tx }, }, { "proposal block", - func(service *Service, factory *txstest.WalletFactory) (*txs.Tx, error) { + func(t testing.TB, s *Service) *txs.Tx { + wallet := newWallet(t, s.vm, walletConfig{}) + sk, err := bls.NewSecretKey() require.NoError(t, err) @@ -252,40 +251,35 @@ func TestGetTx(t *testing.T) { Threshold: 1, Addrs: []ids.ShortID{ids.GenerateTestShortID()}, } - - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddPermissionlessValidatorTx( + tx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: ids.GenerateTestNodeID(), - Start: uint64(service.vm.clock.Time().Add(txexecutor.SyncBound).Unix()), - End: uint64(service.vm.clock.Time().Add(txexecutor.SyncBound).Add(defaultMinStakingDuration).Unix()), - Wght: service.vm.MinValidatorStake, + Start: uint64(s.vm.clock.Time().Add(txexecutor.SyncBound).Unix()), + End: uint64(s.vm.clock.Time().Add(txexecutor.SyncBound).Add(defaultMinStakingDuration).Unix()), + Wght: s.vm.MinValidatorStake, }, Subnet: constants.PrimaryNetworkID, }, signer.NewProofOfPossession(sk), - service.vm.ctx.AVAXAssetID, + s.vm.ctx.AVAXAssetID, rewardsOwner, rewardsOwner, 0, - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(t, err) - return walletsigner.SignUnsigned(context.Background(), txSigner, utx) + return tx }, }, { "atomic block", - func(service *Service, factory *txstest.WalletFactory) (*txs.Tx, error) { - builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewExportTx( - service.vm.ctx.XChainID, + func(t testing.TB, s *Service) *txs.Tx { + wallet := newWallet(t, s.vm, walletConfig{}) + + tx, err := wallet.IssueExportTx( + s.vm.ctx.XChainID, []*avax.TransferableOutput{{ - Asset: avax.Asset{ID: service.vm.ctx.AVAXAssetID}, + Asset: avax.Asset{ID: s.vm.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ Amt: 100, OutputOwners: secp256k1fx.OutputOwners{ @@ -295,13 +289,9 @@ func TestGetTx(t *testing.T) { }, }, }}, - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(t, err) - return walletsigner.SignUnsigned(context.Background(), signer, utx) + return tx }, }, } @@ -314,12 +304,10 @@ func TestGetTx(t *testing.T) { ) t.Run(testName, func(t *testing.T) { require := require.New(t) - service, _, txBuilder := defaultService(t) - service.vm.ctx.Lock.Lock() - - tx, err := test.createTx(service, txBuilder) - require.NoError(err) + service, _ := defaultService(t) + service.vm.ctx.Lock.Lock() + tx := test.createTx(t, service) service.vm.ctx.Lock.Unlock() arg := &api.GetTxArgs{ @@ -327,7 +315,7 @@ func TestGetTx(t *testing.T) { Encoding: encoding, } var response api.GetTxReply - err = service.GetTx(nil, arg, &response) + err := service.GetTx(nil, arg, &response) require.ErrorIs(err, database.ErrNotFound) // We haven't issued the tx yet require.NoError(service.vm.Network.IssueTxFromRPC(tx)) @@ -378,7 +366,7 @@ func TestGetTx(t *testing.T) { func TestGetBalance(t *testing.T) { require := require.New(t) - service, _, _ := defaultService(t) + service, _ := defaultService(t) feeCalculator := state.PickFeeCalculator(&service.vm.Config, service.vm.state) createSubnetFee, err := feeCalculator.CalculateFee(&txs.CreateSubnetTx{}) @@ -417,7 +405,7 @@ func TestGetBalance(t *testing.T) { func TestGetStake(t *testing.T) { require := require.New(t) - service, _, factory := defaultService(t) + service, _ := defaultService(t) // Ensure GetStake is correct for each of the genesis validators genesis := genesistest.New(t, genesistest.Config{}) @@ -503,30 +491,31 @@ func TestGetStake(t *testing.T) { service.vm.ctx.Lock.Lock() + wallet := newWallet(t, service.vm, walletConfig{}) + // Add a delegator stakeAmount := service.vm.MinDelegatorStake + 12345 delegatorNodeID := genesistest.DefaultNodeIDs[0] delegatorEndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) - builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddDelegatorTx( + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } + withChangeOwner := common.WithChangeOwner(&secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, + }) + tx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: delegatorNodeID, Start: genesistest.DefaultValidatorStartTimeUnix, End: uint64(delegatorEndTime.Unix()), Wght: stakeAmount, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), + rewardsOwner, + withChangeOwner, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addDelTx := tx.Unsigned.(*txs.AddDelegatorTx) staker, err := state.NewCurrentStaker( @@ -571,26 +560,18 @@ func TestGetStake(t *testing.T) { stakeAmount = service.vm.MinValidatorStake + 54321 pendingStakerNodeID := ids.GenerateTestNodeID() pendingStakerEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration).Unix()) - utx2, err := builder.NewAddValidatorTx( + tx, err = wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: pendingStakerNodeID, Start: uint64(genesistest.DefaultValidatorStartTime.Unix()), End: pendingStakerEndTime, Wght: stakeAmount, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, 0, - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), + withChangeOwner, ) require.NoError(err) - tx, err = walletsigner.SignUnsigned(context.Background(), signer, utx2) - require.NoError(err) staker, err = state.NewPendingStaker( tx.ID(), @@ -624,7 +605,7 @@ func TestGetStake(t *testing.T) { func TestGetCurrentValidators(t *testing.T) { require := require.New(t) - service, _, factory := defaultService(t) + service, _ := defaultService(t) genesis := genesistest.New(t, genesistest.Config{}) @@ -661,8 +642,8 @@ func TestGetCurrentValidators(t *testing.T) { service.vm.ctx.Lock.Lock() - builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddDelegatorTx( + wallet := newWallet(t, service.vm, walletConfig{}) + delTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: validatorNodeID, Start: genesistest.DefaultValidatorStartTimeUnix, @@ -679,8 +660,6 @@ func TestGetCurrentValidators(t *testing.T) { }), ) require.NoError(err) - delTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addDelTx := delTx.Unsigned.(*txs.AddDelegatorTx) staker, err := state.NewCurrentStaker( @@ -762,7 +741,7 @@ func TestGetCurrentValidators(t *testing.T) { func TestGetTimestamp(t *testing.T) { require := require.New(t) - service, _, _ := defaultService(t) + service, _ := defaultService(t) reply := GetTimestampReply{} require.NoError(service.GetTimestamp(nil, nil, &reply)) @@ -798,26 +777,23 @@ func TestGetBlock(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { require := require.New(t) - service, _, factory := defaultService(t) + service, _ := defaultService(t) service.vm.ctx.Lock.Lock() service.vm.Config.CreateAssetTxFee = 100 * defaultTxFee - builder, signer := factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + subnetID := testSubnet1.ID() + wallet := newWallet(t, service.vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueCreateChainTx( + subnetID, []byte{}, constants.AVMID, []ids.ID{}, "chain name", - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) preferredID := service.vm.manager.Preferred() preferred, err := service.vm.manager.GetBlock(preferredID) @@ -1090,7 +1066,7 @@ func TestServiceGetBlockByHeight(t *testing.T) { func TestServiceGetSubnets(t *testing.T) { require := require.New(t) - service, _, _ := defaultService(t) + service, _ := defaultService(t) testSubnet1ID := testSubnet1.ID() @@ -1162,7 +1138,7 @@ func TestGetFeeConfig(t *testing.T) { t.Run(test.name, func(t *testing.T) { require := require.New(t) - service, _, _ := defaultService(t) + service, _ := defaultService(t) service.vm.Config.UpgradeConfig.EtnaTime = test.etnaTime var reply gas.Config @@ -1176,7 +1152,7 @@ func FuzzGetFeeState(f *testing.F) { f.Fuzz(func(t *testing.T, capacity, excess uint64) { require := require.New(t) - service, _, _ := defaultService(t) + service, _ := defaultService(t) var ( expectedState = gas.State{ diff --git a/vms/platformvm/txs/txstest/wallet.go b/vms/platformvm/txs/txstest/wallet.go new file mode 100644 index 000000000000..8f16b40719b3 --- /dev/null +++ b/vms/platformvm/txs/txstest/wallet.go @@ -0,0 +1,121 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package txstest + +import ( + "context" + "math" + "testing" + + "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/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/fx" + "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/wallet/chain/p/builder" + "github.com/ava-labs/avalanchego/wallet/chain/p/signer" + "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" + "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" +) + +func NewWallet( + t testing.TB, + ctx *snow.Context, + config *config.Config, + state state.State, + kc *secp256k1fx.Keychain, + subnetIDs []ids.ID, + chainIDs []ids.ID, +) wallet.Wallet { + var ( + require = require.New(t) + addrs = kc.Addresses() + utxos = common.NewUTXOs() + ) + + pChainUTXOs, err := avax.GetAllUTXOs(state, addrs) + require.NoError(err) + + for _, utxo := range pChainUTXOs { + require.NoError(utxos.AddUTXO( + context.Background(), + constants.PlatformChainID, + constants.PlatformChainID, + utxo, + )) + } + + for _, chainID := range chainIDs { + remoteChainUTXOs, _, _, err := avax.GetAtomicUTXOs( + ctx.SharedMemory, + txs.Codec, + chainID, + addrs, + ids.ShortEmpty, + ids.Empty, + math.MaxInt, + ) + require.NoError(err) + + for _, utxo := range remoteChainUTXOs { + require.NoError(utxos.AddUTXO( + context.Background(), + chainID, + constants.PlatformChainID, + utxo, + )) + } + } + + owners := make(map[ids.ID]fx.Owner, len(subnetIDs)) + for _, subnetID := range subnetIDs { + owner, err := state.GetSubnetOwner(subnetID) + require.NoError(err) + owners[subnetID] = owner + } + + builderContext := newContext(ctx, config, state.GetTimestamp()) + backend := wallet.NewBackend( + builderContext, + common.NewChainUTXOs(constants.PlatformChainID, utxos), + owners, + ) + return wallet.New( + &client{ + backend: backend, + }, + builder.New( + addrs, + builderContext, + backend, + ), + signer.New( + kc, + backend, + ), + ) +} + +type client struct { + backend wallet.Backend +} + +func (c *client) IssueTx( + tx *txs.Tx, + options ...common.Option, +) error { + ops := common.NewOptions(options) + if f := ops.PostIssuanceFunc(); f != nil { + txID := tx.ID() + f(txID) + } + ctx := ops.Context() + return c.backend.AcceptTx(ctx, tx) +} diff --git a/vms/platformvm/validator_set_property_test.go b/vms/platformvm/validator_set_property_test.go index 44ba02e0e1a7..9a3e84392724 100644 --- a/vms/platformvm/validator_set_property_test.go +++ b/vms/platformvm/validator_set_property_test.go @@ -15,6 +15,7 @@ import ( "github.com/leanovate/gopter" "github.com/leanovate/gopter/gen" "github.com/leanovate/gopter/prop" + "github.com/stretchr/testify/require" "golang.org/x/exp/maps" "github.com/ava-labs/avalanchego/chains" @@ -41,12 +42,10 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/secp256k1fx" blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) @@ -122,10 +121,7 @@ func TestGetValidatorsSetProperty(t *testing.T) { switch ev.eventType { case startSubnetValidator: - currentSubnetValidator, err = addSubnetValidator(vm, ev, subnetID) - if err != nil { - return "could not add subnet validator: " + err.Error() - } + currentSubnetValidator = addSubnetValidator(t, vm, ev, subnetID) if err := takeValidatorsSnapshotAtCurrentHeight(vm, validatorSetByHeightAndSubnet); err != nil { return failedValidatorSnapshotString + err.Error() } @@ -145,10 +141,7 @@ func TestGetValidatorsSetProperty(t *testing.T) { return failedValidatorSnapshotString + err.Error() } } - currentPrimaryValidator, err = addPrimaryValidatorWithBLSKey(vm, ev) - if err != nil { - return "could not add primary validator with BLS key: " + err.Error() - } + currentPrimaryValidator = addPrimaryValidatorWithBLSKey(t, vm, ev) if err := takeValidatorsSnapshotAtCurrentHeight(vm, validatorSetByHeightAndSubnet); err != nil { return failedValidatorSnapshotString + err.Error() } @@ -254,10 +247,13 @@ func takeValidatorsSnapshotAtCurrentHeight(vm *VM, validatorsSetByHeightAndSubne return nil } -func addSubnetValidator(vm *VM, data *validatorInputData, subnetID ids.ID) (*state.Staker, error) { - factory := txstest.NewWalletFactory(vm.ctx, &vm.Config, vm.state) - builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( +func addSubnetValidator(t testing.TB, vm *VM, data *validatorInputData, subnetID ids.ID) *state.Staker { + require := require.New(t) + + wallet := newWallet(t, vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: data.nodeID, @@ -267,32 +263,28 @@ func addSubnetValidator(vm *VM, data *validatorInputData, subnetID ids.ID) (*sta }, Subnet: subnetID, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) - if err != nil { - return nil, fmt.Errorf("could not build AddSubnetValidatorTx: %w", err) - } - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - if err != nil { - return nil, fmt.Errorf("could not sign AddSubnetValidatorTx: %w", err) - } - return internalAddValidator(vm, tx) + require.NoError(err) + + staker, err := internalAddValidator(vm, tx) + require.NoError(err) + return staker } -func addPrimaryValidatorWithBLSKey(vm *VM, data *validatorInputData) (*state.Staker, error) { - addr := genesistest.DefaultFundedKeys[0].Address() +func addPrimaryValidatorWithBLSKey(t testing.TB, vm *VM, data *validatorInputData) *state.Staker { + require := require.New(t) + + wallet := newWallet(t, vm, walletConfig{}) sk, err := bls.NewSecretKey() - if err != nil { - return nil, fmt.Errorf("failed to generate BLS key: %w", err) + require.NoError(err) + + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, } - factory := txstest.NewWalletFactory(vm.ctx, &vm.Config, vm.state) - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddPermissionlessValidatorTx( + tx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: data.nodeID, @@ -304,28 +296,15 @@ func addPrimaryValidatorWithBLSKey(vm *VM, data *validatorInputData) (*state.Sta }, signer.NewProofOfPossession(sk), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) - if err != nil { - return nil, fmt.Errorf("could not build AddPermissionlessValidatorTx: %w", err) - } - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - if err != nil { - return nil, fmt.Errorf("could not sign AddPermissionlessValidatorTx: %w", err) - } - return internalAddValidator(vm, tx) + require.NoError(err) + + staker, err := internalAddValidator(vm, tx) + require.NoError(err) + return staker } func internalAddValidator(vm *VM, signedTx *txs.Tx) (*state.Staker, error) { @@ -708,25 +687,19 @@ func buildVM(t *testing.T) (*VM, ids.ID, error) { // Create a subnet and store it in testSubnet1 // Note: following Banff activation, block acceptance will move // chain time ahead - factory := txstest.NewWalletFactory(vm.ctx, &vm.Config, vm.state) - builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[len(genesistest.DefaultFundedKeys)-1]) - utx, err := builder.NewCreateSubnetTx( - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), + wallet := newWallet(t, vm, walletConfig{}) + owner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, + } + testSubnet1, err = wallet.IssueCreateSubnetTx( + owner, + walletcommon.WithChangeOwner(owner), ) if err != nil { return nil, ids.Empty, err } - testSubnet1, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - if err != nil { - return nil, ids.Empty, err - } + vm.ctx.Lock.Unlock() err = vm.issueTxFromRPC(testSubnet1) vm.ctx.Lock.Lock() diff --git a/vms/platformvm/vm_regression_test.go b/vms/platformvm/vm_regression_test.go index 9b4d8b19a5a6..811dc2dfb91a 100644 --- a/vms/platformvm/vm_regression_test.go +++ b/vms/platformvm/vm_regression_test.go @@ -31,6 +31,7 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/crypto/bls" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" + "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/version" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/block" @@ -41,111 +42,80 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/secp256k1fx" blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) func TestAddDelegatorTxOverDelegatedRegression(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() + wallet := newWallet(t, vm, walletConfig{}) + validatorStartTime := vm.clock.Time().Add(executor.SyncBound).Add(1 * time.Second) validatorEndTime := validatorStartTime.Add(360 * 24 * time.Hour) nodeID := ids.GenerateTestNodeID() - changeAddr := genesistest.DefaultFundedKeys[0].Address() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } // create valid tx - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + addValidatorTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(validatorStartTime.Unix()), End: uint64(validatorEndTime.Unix()), Wght: vm.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addValidatorTx)) vm.ctx.Lock.Lock() - addValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addValidatorBlock.Verify(context.Background())) - require.NoError(addValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) + // Advance the time vm.clock.Set(validatorStartTime) - - firstAdvanceTimeBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(firstAdvanceTimeBlock.Verify(context.Background())) - require.NoError(firstAdvanceTimeBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + require.NoError(buildAndAcceptStandardBlock(vm)) firstDelegatorStartTime := validatorStartTime.Add(executor.SyncBound).Add(1 * time.Second) firstDelegatorEndTime := firstDelegatorStartTime.Add(vm.MinStakeDuration) // create valid tx - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - uDelTx1, err := builder.NewAddDelegatorTx( + addFirstDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(firstDelegatorStartTime.Unix()), End: uint64(firstDelegatorEndTime.Unix()), Wght: 4 * vm.MinValidatorStake, // maximum amount of stake this delegator can provide }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addFirstDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx1) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addFirstDelegatorTx)) vm.ctx.Lock.Lock() - addFirstDelegatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addFirstDelegatorBlock.Verify(context.Background())) - require.NoError(addFirstDelegatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addFirstDelegatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) + // Advance the time vm.clock.Set(firstDelegatorStartTime) - - secondAdvanceTimeBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(secondAdvanceTimeBlock.Verify(context.Background())) - require.NoError(secondAdvanceTimeBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + require.NoError(buildAndAcceptStandardBlock(vm)) secondDelegatorStartTime := firstDelegatorEndTime.Add(2 * time.Second) secondDelegatorEndTime := secondDelegatorStartTime.Add(vm.MinStakeDuration) @@ -153,62 +123,39 @@ func TestAddDelegatorTxOverDelegatedRegression(t *testing.T) { vm.clock.Set(secondDelegatorStartTime.Add(-10 * executor.SyncBound)) // create valid tx - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[3]) - uDelTx2, err := builder.NewAddDelegatorTx( + addSecondDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(secondDelegatorStartTime.Unix()), End: uint64(secondDelegatorEndTime.Unix()), Wght: vm.MinDelegatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addSecondDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx2) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addSecondDelegatorTx)) vm.ctx.Lock.Lock() - addSecondDelegatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addSecondDelegatorBlock.Verify(context.Background())) - require.NoError(addSecondDelegatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addSecondDelegatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) thirdDelegatorStartTime := firstDelegatorEndTime.Add(-time.Second) thirdDelegatorEndTime := thirdDelegatorStartTime.Add(vm.MinStakeDuration) - // create valid tx - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) - uDelTx3, err := builder.NewAddDelegatorTx( + // create invalid tx + addThirdDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(thirdDelegatorStartTime.Unix()), End: uint64(thirdDelegatorEndTime.Unix()), Wght: vm.MinDelegatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addThirdDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx3) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() @@ -256,185 +203,120 @@ func TestAddDelegatorTxHeapCorruption(t *testing.T) { t.Run(test.name, func(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.ApricotPhase3) + vm, _, _ := defaultVM(t, upgradetest.ApricotPhase3) vm.UpgradeConfig.ApricotPhase3Time = test.ap3Time vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - key, err := secp256k1.NewPrivateKey() - require.NoError(err) + wallet := newWallet(t, vm, walletConfig{}) - id := key.Address() nodeID := ids.GenerateTestNodeID() - changeAddr := genesistest.DefaultFundedKeys[0].Address() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } // create valid tx - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddValidatorTx( + addValidatorTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(validatorStartTime.Unix()), End: uint64(validatorEndTime.Unix()), Wght: validatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{id}, - }, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // issue the add validator tx vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addValidatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the validator tx - addValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addValidatorBlock.Verify(context.Background())) - require.NoError(addValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) // create valid tx - uDelTx1, err := builder.NewAddDelegatorTx( + addFirstDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(delegator1StartTime.Unix()), End: uint64(delegator1EndTime.Unix()), Wght: delegator1Stake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addFirstDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx1) - require.NoError(err) // issue the first add delegator tx vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addFirstDelegatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the first add delegator tx - addFirstDelegatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addFirstDelegatorBlock.Verify(context.Background())) - require.NoError(addFirstDelegatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addFirstDelegatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) // create valid tx - uDelTx2, err := builder.NewAddDelegatorTx( + addSecondDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(delegator2StartTime.Unix()), End: uint64(delegator2EndTime.Unix()), Wght: delegator2Stake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addSecondDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx2) - require.NoError(err) // issue the second add delegator tx vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addSecondDelegatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the second add delegator tx - addSecondDelegatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addSecondDelegatorBlock.Verify(context.Background())) - require.NoError(addSecondDelegatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addSecondDelegatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) // create valid tx - uDelTx3, err := builder.NewAddDelegatorTx( + addThirdDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(delegator3StartTime.Unix()), End: uint64(delegator3EndTime.Unix()), Wght: delegator3Stake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addThirdDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx3) - require.NoError(err) // issue the third add delegator tx vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addThirdDelegatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the third add delegator tx - addThirdDelegatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addThirdDelegatorBlock.Verify(context.Background())) - require.NoError(addThirdDelegatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addThirdDelegatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) // create valid tx - uDelTx4, err := builder.NewAddDelegatorTx( + addFourthDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(delegator4StartTime.Unix()), End: uint64(delegator4EndTime.Unix()), Wght: delegator4Stake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addFourthDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx4) - require.NoError(err) // issue the fourth add delegator tx vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addFourthDelegatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the fourth add delegator tx - addFourthDelegatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addFourthDelegatorBlock.Verify(context.Background())) - require.NoError(addFourthDelegatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addFourthDelegatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) }) } } @@ -484,59 +366,47 @@ func TestUnverifiedParentPanicRegression(t *testing.T) { vm.clock.Set(latestForkTime.Add(time.Second)) vm.state.SetTimestamp(latestForkTime.Add(time.Second)) - key0 := genesistest.DefaultFundedKeys[0] - key1 := genesistest.DefaultFundedKeys[1] - addr0 := key0.Address() - addr1 := key1.Address() - - factory := txstest.NewWalletFactory( - vm.ctx, - &vm.Config, - vm.state, - ) - - builder, txSigner := factory.NewWallet(key0) - utx0, err := builder.NewCreateSubnetTx( - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr0}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ + var ( + key0 = genesistest.DefaultFundedKeys[0] + addr0 = key0.Address() + owners0 = &secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{addr0}, - }), - ) - require.NoError(err) - addSubnetTx0, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx0) - require.NoError(err) + } - builder, txSigner = factory.NewWallet(key1) - utx1, err := builder.NewCreateSubnetTx( - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr1}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ + key1 = genesistest.DefaultFundedKeys[1] + addr1 = key1.Address() + owners1 = &secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{addr1}, - }), + } + ) + + wallet := newWallet(t, vm, walletConfig{}) + addSubnetTx0, err := wallet.IssueCreateSubnetTx( + owners0, + walletcommon.WithCustomAddresses(set.Of( + addr0, + )), ) - require.NoError(err) - addSubnetTx1, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx1) require.NoError(err) - utx2, err := builder.NewCreateSubnetTx( - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr1}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr0}, - }), + addSubnetTx1, err := wallet.IssueCreateSubnetTx( + owners1, + walletcommon.WithCustomAddresses(set.Of( + addr1, + )), ) require.NoError(err) - addSubnetTx2, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx2) + + // Wallet needs to be re-created to generate a conflicting transaction + wallet = newWallet(t, vm, walletConfig{}) + addSubnetTx2, err := wallet.IssueCreateSubnetTx( + owners1, + walletcommon.WithCustomAddresses(set.Of( + addr0, + )), + ) require.NoError(err) preferredID := vm.manager.Preferred() @@ -591,17 +461,18 @@ func TestUnverifiedParentPanicRegression(t *testing.T) { func TestRejectedStateRegressionInvalidValidatorTimestamp(t *testing.T) { require := require.New(t) - vm, factory, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Cortina) + vm, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() + wallet := newWallet(t, vm, walletConfig{}) + nodeID := ids.GenerateTestNodeID() newValidatorStartTime := vm.clock.Time().Add(executor.SyncBound).Add(1 * time.Second) newValidatorEndTime := newValidatorStartTime.Add(defaultMinStakingDuration) // Create the tx to add a new validator - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + addValidatorTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(newValidatorStartTime.Unix()), @@ -615,8 +486,6 @@ func TestRejectedStateRegressionInvalidValidatorTimestamp(t *testing.T) { reward.PercentDenominator, ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // Create the standard block to add the new validator preferredID := vm.manager.Preferred() @@ -785,35 +654,35 @@ func TestRejectedStateRegressionInvalidValidatorTimestamp(t *testing.T) { func TestRejectedStateRegressionInvalidValidatorReward(t *testing.T) { require := require.New(t) - vm, factory, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Cortina) + vm, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() vm.state.SetCurrentSupply(constants.PrimaryNetworkID, defaultRewardConfig.SupplyCap/2) + wallet := newWallet(t, vm, walletConfig{}) + + nodeID0 := ids.GenerateTestNodeID() newValidatorStartTime0 := vm.clock.Time().Add(executor.SyncBound).Add(1 * time.Second) newValidatorEndTime0 := newValidatorStartTime0.Add(defaultMaxStakingDuration) - nodeID0 := ids.GenerateTestNodeID() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } // Create the tx to add the first new validator - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + addValidatorTx0, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID0, Start: uint64(newValidatorStartTime0.Unix()), End: uint64(newValidatorEndTime0.Unix()), Wght: vm.MaxValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - addValidatorTx0, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // Create the standard block to add the first new validator preferredID := vm.manager.Preferred() @@ -966,23 +835,17 @@ func TestRejectedStateRegressionInvalidValidatorReward(t *testing.T) { nodeID1 := ids.GenerateTestNodeID() // Create the tx to add the second new validator - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[1]) - utx1, err := builder.NewAddValidatorTx( + addValidatorTx1, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID1, Start: uint64(newValidatorStartTime1.Unix()), End: uint64(newValidatorEndTime1.Unix()), Wght: vm.MaxValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - addValidatorTx1, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx1) - require.NoError(err) // Create the standard block to add the second new validator preferredChainTime = importBlk.Timestamp() @@ -1092,7 +955,7 @@ func TestRejectedStateRegressionInvalidValidatorReward(t *testing.T) { func TestValidatorSetAtCacheOverwriteRegression(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1113,14 +976,15 @@ func TestValidatorSetAtCacheOverwriteRegression(t *testing.T) { require.Equal(weight, validators[nodeID].Weight) } + wallet := newWallet(t, vm, walletConfig{}) + newValidatorStartTime0 := vm.clock.Time().Add(executor.SyncBound).Add(1 * time.Second) newValidatorEndTime0 := newValidatorStartTime0.Add(defaultMaxStakingDuration) extraNodeID := ids.GenerateTestNodeID() // Create the tx to add the first new validator - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + addValidatorTx0, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: extraNodeID, Start: uint64(newValidatorStartTime0.Unix()), @@ -1134,8 +998,6 @@ func TestValidatorSetAtCacheOverwriteRegression(t *testing.T) { reward.PercentDenominator, ) require.NoError(err) - addValidatorTx0, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // Create the standard block to add the first new validator preferredID := vm.manager.Preferred() @@ -1234,105 +1096,70 @@ func TestAddDelegatorTxAddBeforeRemove(t *testing.T) { delegator2EndTime := delegator2StartTime.Add(3 * defaultMinStakingDuration) delegator2Stake := defaultMaxValidatorStake - validatorStake - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - key, err := secp256k1.NewPrivateKey() - require.NoError(err) + wallet := newWallet(t, vm, walletConfig{}) - id := key.Address() nodeID := ids.GenerateTestNodeID() - changeAddr := genesistest.DefaultFundedKeys[0].Address() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } // create valid tx - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddValidatorTx( + addValidatorTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(validatorStartTime.Unix()), End: uint64(validatorEndTime.Unix()), Wght: validatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{id}, - }, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // issue the add validator tx vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addValidatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the validator tx - addValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addValidatorBlock.Verify(context.Background())) - require.NoError(addValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) // create valid tx - uDelTx, err := builder.NewAddDelegatorTx( + addFirstDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(delegator1StartTime.Unix()), End: uint64(delegator1EndTime.Unix()), Wght: delegator1Stake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addFirstDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx) - require.NoError(err) // issue the first add delegator tx vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addFirstDelegatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the first add delegator tx - addFirstDelegatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addFirstDelegatorBlock.Verify(context.Background())) - require.NoError(addFirstDelegatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addFirstDelegatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) - // create valid tx - uDelTx, err = builder.NewAddDelegatorTx( + // create invalid tx + addSecondDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(delegator2StartTime.Unix()), End: uint64(delegator2EndTime.Unix()), Wght: delegator2Stake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + rewardsOwner, ) require.NoError(err) - addSecondDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx) - require.NoError(err) // attempting to issue the second add delegator tx should fail because the // total stake weight would go over the limit. @@ -1348,19 +1175,14 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionNotTracked(t validatorStartTime := latestForkTime.Add(executor.SyncBound).Add(1 * time.Second) validatorEndTime := validatorStartTime.Add(360 * 24 * time.Hour) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - key, err := secp256k1.NewPrivateKey() - require.NoError(err) + wallet := newWallet(t, vm, walletConfig{}) - id := key.Address() nodeID := ids.GenerateTestNodeID() - changeAddr := genesistest.DefaultFundedKeys[0].Address() - - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddValidatorTx( + addValidatorTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(validatorStartTime.Unix()), @@ -1369,55 +1191,36 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionNotTracked(t }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{id}, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, }, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addValidatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the validator tx - addValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addValidatorBlock.Verify(context.Background())) - require.NoError(addValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) - uSubnetTx, err := builder.NewCreateSubnetTx( + createSubnetTx, err := wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - createSubnetTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uSubnetTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(createSubnetTx)) vm.ctx.Lock.Lock() - // trigger block creation for the subnet tx - createSubnetBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(createSubnetBlock.Verify(context.Background())) - require.NoError(createSubnetBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept createSubnetTx + require.NoError(buildAndAcceptStandardBlock(vm)) - uSubnetValTx, err := builder.NewAddSubnetValidatorTx( + subnetID := createSubnetTx.ID() + addSubnetValidatorTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1425,47 +1228,34 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionNotTracked(t End: uint64(validatorEndTime.Unix()), Wght: defaultMaxValidatorStake, }, - Subnet: createSubnetTx.ID(), + Subnet: subnetID, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - addSubnetValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uSubnetValTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addSubnetValidatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the validator tx - addSubnetValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) + // Accept addSubnetValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) + + addSubnetValidatorHeight, err := vm.GetCurrentHeight(context.Background()) require.NoError(err) - require.NoError(addSubnetValidatorBlock.Verify(context.Background())) - require.NoError(addSubnetValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) emptyValidatorSet, err := vm.GetValidatorSet( context.Background(), - addSubnetValidatorBlock.Height(), - createSubnetTx.ID(), + addSubnetValidatorHeight, + subnetID, ) require.NoError(err) require.Empty(emptyValidatorSet) - uRemoveSubnetValTx, err := builder.NewRemoveSubnetValidatorTx( + removeSubnetValidatorTx, err := wallet.IssueRemoveSubnetValidatorTx( nodeID, - createSubnetTx.ID(), - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + subnetID, ) require.NoError(err) - removeSubnetValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uRemoveSubnetValTx) - require.NoError(err) // Set the clock so that the validator will be moved from the pending // validator set into the current validator set. @@ -1475,17 +1265,13 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionNotTracked(t require.NoError(vm.issueTxFromRPC(removeSubnetValidatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the validator tx - removeSubnetValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(removeSubnetValidatorBlock.Verify(context.Background())) - require.NoError(removeSubnetValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept removeSubnetValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) emptyValidatorSet, err = vm.GetValidatorSet( context.Background(), - addSubnetValidatorBlock.Height(), - createSubnetTx.ID(), + addSubnetValidatorHeight, + subnetID, ) require.NoError(err) require.Empty(emptyValidatorSet) @@ -1497,19 +1283,14 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t validatorStartTime := latestForkTime.Add(executor.SyncBound).Add(1 * time.Second) validatorEndTime := validatorStartTime.Add(360 * 24 * time.Hour) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - key, err := secp256k1.NewPrivateKey() - require.NoError(err) + wallet := newWallet(t, vm, walletConfig{}) - id := key.Address() nodeID := ids.GenerateTestNodeID() - changeAddr := genesistest.DefaultFundedKeys[0].Address() - - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddValidatorTx( + addValidatorTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(validatorStartTime.Unix()), @@ -1518,55 +1299,36 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{id}, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, }, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addValidatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the validator tx - addValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addValidatorBlock.Verify(context.Background())) - require.NoError(addValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) - uCreateSubnetTx, err := builder.NewCreateSubnetTx( + createSubnetTx, err := wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - createSubnetTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uCreateSubnetTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(createSubnetTx)) vm.ctx.Lock.Lock() - // trigger block creation for the subnet tx - createSubnetBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(createSubnetBlock.Verify(context.Background())) - require.NoError(createSubnetBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept createSubnetTx + require.NoError(buildAndAcceptStandardBlock(vm)) - uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( + subnetID := createSubnetTx.ID() + addSubnetValidatorTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1574,39 +1336,23 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t End: uint64(validatorEndTime.Unix()), Wght: defaultMaxValidatorStake, }, - Subnet: createSubnetTx.ID(), + Subnet: subnetID, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - addSubnetValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddSubnetValTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addSubnetValidatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the validator tx - addSubnetValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addSubnetValidatorBlock.Verify(context.Background())) - require.NoError(addSubnetValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept addSubnetValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) - uRemoveSubnetValTx, err := builder.NewRemoveSubnetValidatorTx( + removeSubnetValidatorTx, err := wallet.IssueRemoveSubnetValidatorTx( nodeID, - createSubnetTx.ID(), - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + subnetID, ) require.NoError(err) - removeSubnetValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uRemoveSubnetValTx) - require.NoError(err) // Set the clock so that the validator will be moved from the pending // validator set into the current validator set. @@ -1616,12 +1362,8 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t require.NoError(vm.issueTxFromRPC(removeSubnetValidatorTx)) vm.ctx.Lock.Lock() - // trigger block creation for the validator tx - removeSubnetValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(removeSubnetValidatorBlock.Verify(context.Background())) - require.NoError(removeSubnetValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + // Accept removeSubnetValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) } // GetValidatorSet must return the BLS keys for a given validator correctly when @@ -1629,20 +1371,18 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { // setup require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() subnetID := testSubnet1.TxID - - // setup time - currentTime := genesistest.DefaultValidatorStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + wallet := newWallet(t, vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) // A subnet validator stakes and then stops; also its primary network counterpart stops staking var ( - primaryStartTime = currentTime.Add(executor.SyncBound) + primaryStartTime = genesistest.DefaultValidatorStartTime.Add(executor.SyncBound) subnetStartTime = primaryStartTime.Add(executor.SyncBound) subnetEndTime = subnetStartTime.Add(defaultMinStakingDuration) primaryEndTime = subnetEndTime.Add(time.Second) @@ -1652,15 +1392,18 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { // insert primary network validator var ( - nodeID = ids.GenerateTestNodeID() - addr = genesistest.DefaultFundedKeys[0].Address() + nodeID = ids.GenerateTestNodeID() + rewardsOwner = &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } ) sk1, err := bls.NewSecretKey() require.NoError(err) + pk1 := bls.PublicFromSecretKey(sk1) // build primary network validator with BLS key - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys...) - uPrimaryTx, err := builder.NewAddPermissionlessValidatorTx( + primaryTx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1672,23 +1415,11 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { }, signer.NewProofOfPossession(sk1), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - primaryTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uPrimaryTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(primaryTx)) @@ -1696,9 +1427,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting primary validator to current - currentTime = primaryStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(primaryStartTime) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(constants.PrimaryNetworkID, nodeID) @@ -1708,8 +1437,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { require.NoError(err) // insert the subnet validator - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( + subnetTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1719,14 +1447,8 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { }, Subnet: subnetID, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - subnetTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddSubnetValTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(subnetTx)) @@ -1734,9 +1456,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting the subnet validator to current - currentTime = subnetStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(subnetStartTime) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(subnetID, nodeID) @@ -1746,9 +1466,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { require.NoError(err) // move time ahead, terminating the subnet validator - currentTime = subnetEndTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(subnetEndTime) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(subnetID, nodeID) @@ -1758,10 +1476,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { require.NoError(err) // move time ahead, terminating primary network validator - currentTime = primaryEndTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) - + vm.clock.Set(primaryEndTime) blk, err := vm.Builder.BuildBlock(context.Background()) // must be a proposal block rewarding the primary validator require.NoError(err) require.NoError(blk.Verify(context.Background())) @@ -1787,10 +1502,9 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { // reinsert primary validator with a different BLS key sk2, err := bls.NewSecretKey() require.NoError(err) - require.NotEqual(sk1, sk2) + pk2 := bls.PublicFromSecretKey(sk2) - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys...) - uPrimaryRestartTx, err := builder.NewAddPermissionlessValidatorTx( + primaryRestartTx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1802,23 +1516,11 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { }, signer.NewProofOfPossession(sk2), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - primaryRestartTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uPrimaryRestartTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(primaryRestartTx)) @@ -1826,9 +1528,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting restarted primary validator to current - currentTime = primaryReStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(primaryReStartTime) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(constants.PrimaryNetworkID, nodeID) @@ -1844,7 +1544,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { nodeID, constants.PrimaryNetworkID, height, - uPrimaryTx.Signer.Key(), + pk1, )) } for height := primaryEndHeight; height < primaryRestartHeight; height++ { @@ -1853,7 +1553,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { nodeID, constants.PrimaryNetworkID, primaryEndHeight, - uPrimaryTx.Signer.Key(), + pk1, ) require.ErrorIs(err, database.ErrNotFound) } @@ -1862,7 +1562,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { nodeID, constants.PrimaryNetworkID, primaryRestartHeight, - uPrimaryRestartTx.Signer.Key(), + pk2, )) for height := subnetStartHeight; height < subnetEndHeight; height++ { @@ -1871,7 +1571,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { nodeID, subnetID, height, - uPrimaryTx.Signer.Key(), + pk1, )) } @@ -1881,7 +1581,7 @@ func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { nodeID, subnetID, primaryEndHeight, - uPrimaryTx.Signer.Key(), + pk1, ) require.ErrorIs(err, database.ErrNotFound) } @@ -1894,18 +1594,15 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { // setup require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - // setup time - currentTime := genesistest.DefaultValidatorStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + wallet := newWallet(t, vm, walletConfig{}) // A primary network validator stake twice var ( - primaryStartTime1 = currentTime.Add(executor.SyncBound) + primaryStartTime1 = genesistest.DefaultValidatorStartTime.Add(executor.SyncBound) primaryEndTime1 = primaryStartTime1.Add(defaultMinStakingDuration) primaryStartTime2 = primaryEndTime1.Add(executor.SyncBound) primaryEndTime2 = primaryStartTime2.Add(defaultMinStakingDuration) @@ -1913,29 +1610,22 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { // Add a primary network validator with no BLS key nodeID := ids.GenerateTestNodeID() - addr := genesistest.DefaultFundedKeys[0].Address() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uAddValTx1, err := builder.NewAddValidatorTx( + primaryTx1, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(primaryStartTime1.Unix()), End: uint64(primaryEndTime1.Unix()), Wght: vm.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - primaryTx1, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddValTx1) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(primaryTx1)) @@ -1943,9 +1633,7 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting primary validator to current - currentTime = primaryStartTime1 - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(primaryStartTime1) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(constants.PrimaryNetworkID, nodeID) @@ -1955,10 +1643,7 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(err) // move time ahead, terminating primary network validator - currentTime = primaryEndTime1 - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) - + vm.clock.Set(primaryEndTime1) blk, err := vm.Builder.BuildBlock(context.Background()) // must be a proposal block rewarding the primary validator require.NoError(err) require.NoError(blk.Verify(context.Background())) @@ -1982,11 +1667,10 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(err) // reinsert primary validator with a different BLS key - sk2, err := bls.NewSecretKey() + sk, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys...) - uPrimaryRestartTx, err := builder.NewAddPermissionlessValidatorTx( + primaryRestartTx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1996,25 +1680,13 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { }, Subnet: constants.PrimaryNetworkID, }, - signer.NewProofOfPossession(sk2), + signer.NewProofOfPossession(sk), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - primaryRestartTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uPrimaryRestartTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(primaryRestartTx)) @@ -2022,22 +1694,19 @@ func TestPrimaryNetworkValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting restarted primary validator to current - currentTime = primaryStartTime2 - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(primaryStartTime2) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(constants.PrimaryNetworkID, nodeID) require.NoError(err) - emptySigner := &signer.Empty{} for height := primaryStartHeight; height < primaryEndHeight; height++ { require.NoError(checkValidatorBlsKeyIsSet( vm.State, nodeID, constants.PrimaryNetworkID, height, - emptySigner.Key(), + nil, )) } } @@ -2050,20 +1719,18 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { // setup require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() subnetID := testSubnet1.TxID - - // setup time - currentTime := genesistest.DefaultValidatorStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + wallet := newWallet(t, vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) // A primary network validator stake twice var ( - primaryStartTime1 = currentTime.Add(executor.SyncBound) + primaryStartTime1 = genesistest.DefaultValidatorStartTime.Add(executor.SyncBound) subnetStartTime = primaryStartTime1.Add(executor.SyncBound) subnetEndTime = subnetStartTime.Add(defaultMinStakingDuration) primaryEndTime1 = subnetEndTime.Add(time.Second) @@ -2073,29 +1740,22 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { // Add a primary network validator with no BLS key nodeID := ids.GenerateTestNodeID() - addr := genesistest.DefaultFundedKeys[0].Address() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uPrimaryTx1, err := builder.NewAddValidatorTx( + primaryTx1, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(primaryStartTime1.Unix()), End: uint64(primaryEndTime1.Unix()), Wght: vm.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - primaryTx1, err := walletsigner.SignUnsigned(context.Background(), txSigner, uPrimaryTx1) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(primaryTx1)) @@ -2103,9 +1763,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting primary validator to current - currentTime = primaryStartTime1 - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(primaryStartTime1) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(constants.PrimaryNetworkID, nodeID) @@ -2115,8 +1773,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(err) // insert the subnet validator - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( + subnetTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -2126,14 +1783,8 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { }, Subnet: subnetID, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - subnetTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddSubnetValTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(subnetTx)) @@ -2141,9 +1792,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting the subnet validator to current - currentTime = subnetStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(subnetStartTime) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(subnetID, nodeID) @@ -2153,9 +1802,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(err) // move time ahead, terminating the subnet validator - currentTime = subnetEndTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(subnetEndTime) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(subnetID, nodeID) @@ -2165,10 +1812,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(err) // move time ahead, terminating primary network validator - currentTime = primaryEndTime1 - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) - + vm.clock.Set(primaryEndTime1) blk, err := vm.Builder.BuildBlock(context.Background()) // must be a proposal block rewarding the primary validator require.NoError(err) require.NoError(blk.Verify(context.Background())) @@ -2195,8 +1839,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { sk2, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys...) - uPrimaryRestartTx, err := builder.NewAddPermissionlessValidatorTx( + primaryRestartTx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -2208,23 +1851,11 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { }, signer.NewProofOfPossession(sk2), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - primaryRestartTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uPrimaryRestartTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(primaryRestartTx)) @@ -2232,22 +1863,19 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting restarted primary validator to current - currentTime = primaryStartTime2 - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) - + vm.clock.Set(primaryStartTime2) require.NoError(buildAndAcceptStandardBlock(vm)) + _, err = vm.state.GetCurrentValidator(constants.PrimaryNetworkID, nodeID) require.NoError(err) - emptySigner := &signer.Empty{} for height := primaryStartHeight; height < primaryEndHeight; height++ { require.NoError(checkValidatorBlsKeyIsSet( vm.State, nodeID, constants.PrimaryNetworkID, height, - emptySigner.Key(), + nil, )) } for height := subnetStartHeight; height < subnetEndHeight; height++ { @@ -2256,7 +1884,7 @@ func TestSubnetValidatorPopulatedToEmptyBLSKeyDiff(t *testing.T) { nodeID, subnetID, height, - emptySigner.Key(), + nil, )) } } @@ -2269,20 +1897,18 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { // setup require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() subnetID := testSubnet1.TxID - - // setup time - currentTime := genesistest.DefaultValidatorStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + wallet := newWallet(t, vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) // A primary network validator stake twice var ( - primaryStartTime1 = currentTime.Add(executor.SyncBound) + primaryStartTime1 = genesistest.DefaultValidatorStartTime.Add(executor.SyncBound) subnetStartTime = primaryStartTime1.Add(executor.SyncBound) subnetEndTime = subnetStartTime.Add(defaultMinStakingDuration) primaryEndTime1 = subnetEndTime.Add(time.Second) @@ -2290,10 +1916,8 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { // Add a primary network validator with no BLS key nodeID := ids.GenerateTestNodeID() - addr := genesistest.DefaultFundedKeys[0].Address() - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uPrimaryTx1, err := builder.NewAddValidatorTx( + primaryTx1, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(primaryStartTime1.Unix()), @@ -2302,17 +1926,11 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{addr}, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, }, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - primaryTx1, err := walletsigner.SignUnsigned(context.Background(), txSigner, uPrimaryTx1) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(primaryTx1)) @@ -2320,17 +1938,14 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting primary validator to current - currentTime = primaryStartTime1 - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(primaryStartTime1) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(constants.PrimaryNetworkID, nodeID) require.NoError(err) // insert the subnet validator - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( + subnetTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -2340,14 +1955,8 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { }, Subnet: subnetID, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{addr}, - }), ) require.NoError(err) - subnetTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddSubnetValTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(subnetTx)) @@ -2355,9 +1964,7 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { require.NoError(buildAndAcceptStandardBlock(vm)) // move time ahead, promoting the subnet validator to current - currentTime = subnetStartTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(subnetStartTime) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(subnetID, nodeID) @@ -2367,19 +1974,14 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { require.NoError(err) // move time ahead, terminating the subnet validator - currentTime = subnetEndTime - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) + vm.clock.Set(subnetEndTime) require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetCurrentValidator(subnetID, nodeID) require.ErrorIs(err, database.ErrNotFound) // move time ahead, terminating primary network validator - currentTime = primaryEndTime1 - vm.clock.Set(currentTime) - vm.state.SetTimestamp(currentTime) - + vm.clock.Set(primaryEndTime1) blk, err := vm.Builder.BuildBlock(context.Background()) // must be a proposal block rewarding the primary validator require.NoError(err) require.NoError(blk.Verify(context.Background())) @@ -2407,7 +2009,7 @@ func TestSubnetValidatorSetAfterPrimaryNetworkValidatorRemoval(t *testing.T) { func TestValidatorSetRaceCondition(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() diff --git a/vms/platformvm/vm_test.go b/vms/platformvm/vm_test.go index e6cfada5e7f7..d11141c923aa 100644 --- a/vms/platformvm/vm_test.go +++ b/vms/platformvm/vm_test.go @@ -59,6 +59,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" p2ppb "github.com/ava-labs/avalanchego/proto/pb/p2p" smcon "github.com/ava-labs/avalanchego/snow/consensus/snowman" @@ -69,7 +70,6 @@ import ( blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" walletbuilder "github.com/ava-labs/avalanchego/wallet/chain/p/builder" - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) @@ -115,17 +115,14 @@ var ( } // subnet that exists at genesis in defaultVM - // Its controlKeys are keys[0], keys[1], keys[2] - // Its threshold is 2 - testSubnet1 *txs.Tx - testSubnet1ControlKeys = genesistest.DefaultFundedKeys[0:3] + testSubnet1 *txs.Tx ) type mutableSharedMemory struct { atomic.SharedMemory } -func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, database.Database, *mutableSharedMemory) { +func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, database.Database, *mutableSharedMemory) { require := require.New(t) // always reset latestForkTime (a package level variable) @@ -190,17 +187,15 @@ func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, d require.NoError(vm.SetState(context.Background(), snow.NormalOp)) - factory := txstest.NewWalletFactory( - ctx, - &vm.Config, - vm.state, - ) + wallet := newWallet(t, vm, walletConfig{ + keys: []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, + }) // Create a subnet and store it in testSubnet1 // Note: following Banff activation, block acceptance will move // chain time ahead - builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewCreateSubnetTx( + var err error + testSubnet1, err = wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 2, Addrs: []ids.ShortID{ @@ -209,23 +204,13 @@ func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, d genesistest.DefaultFundedKeys[2].Address(), }, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(err) - testSubnet1, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(testSubnet1)) vm.ctx.Lock.Lock() - blk, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(blk.Verify(context.Background())) - require.NoError(blk.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + require.NoError(buildAndAcceptStandardBlock(vm)) t.Cleanup(func() { vm.ctx.Lock.Lock() @@ -234,13 +219,33 @@ func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, *txstest.WalletFactory, d require.NoError(vm.Shutdown(context.Background())) }) - return vm, factory, db, msm + return vm, db, msm +} + +type walletConfig struct { + keys []*secp256k1.PrivateKey + subnetIDs []ids.ID +} + +func newWallet(t testing.TB, vm *VM, c walletConfig) wallet.Wallet { + if len(c.keys) == 0 { + c.keys = genesistest.DefaultFundedKeys + } + return txstest.NewWallet( + t, + vm.ctx, + &vm.Config, + vm.state, + secp256k1fx.NewKeychain(c.keys...), + c.subnetIDs, + []ids.ID{vm.ctx.CChainID, vm.ctx.XChainID}, + ) } // Ensure genesis state is parsed from bytes and stored correctly func TestGenesis(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -290,27 +295,29 @@ func TestGenesis(t *testing.T) { // accept proposal to add validator to primary network func TestAddValidatorCommit(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() + wallet := newWallet(t, vm, walletConfig{}) + var ( - startTime = vm.clock.Time().Add(txexecutor.SyncBound).Add(1 * time.Second) - endTime = startTime.Add(defaultMinStakingDuration) - nodeID = ids.GenerateTestNodeID() - rewardAddress = ids.GenerateTestShortID() + endTime = vm.clock.Time().Add(defaultMinStakingDuration) + nodeID = ids.GenerateTestNodeID() + rewardsOwner = &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } ) sk, err := bls.NewSecretKey() require.NoError(err) // create valid tx - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddPermissionlessValidatorTx( + tx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, - Start: uint64(startTime.Unix()), End: uint64(endTime.Unix()), Wght: vm.MinValidatorStake, }, @@ -318,30 +325,17 @@ func TestAddValidatorCommit(t *testing.T) { }, signer.NewProofOfPossession(sk), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{rewardAddress}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{rewardAddress}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(tx)) vm.ctx.Lock.Lock() - - blk, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - - require.NoError(blk.Verify(context.Background())) - require.NoError(blk.Accept(context.Background())) + require.NoError(buildAndAcceptStandardBlock(vm)) _, txStatus, err := vm.state.GetTx(tx.ID()) require.NoError(err) @@ -355,17 +349,18 @@ func TestAddValidatorCommit(t *testing.T) { // verify invalid attempt to add validator to primary network func TestInvalidAddValidatorCommit(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() + wallet := newWallet(t, vm, walletConfig{}) + nodeID := ids.GenerateTestNodeID() startTime := genesistest.DefaultValidatorStartTime.Add(-txexecutor.SyncBound).Add(-1 * time.Second) endTime := startTime.Add(defaultMinStakingDuration) // create invalid tx - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), @@ -379,8 +374,6 @@ func TestInvalidAddValidatorCommit(t *testing.T) { reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) preferredID := vm.manager.Preferred() preferred, err := vm.manager.GetBlock(preferredID) @@ -411,10 +404,12 @@ func TestInvalidAddValidatorCommit(t *testing.T) { // Reject attempt to add validator to primary network func TestAddValidatorReject(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Cortina) + vm, _, _ := defaultVM(t, upgradetest.Cortina) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() + wallet := newWallet(t, vm, walletConfig{}) + var ( startTime = vm.clock.Time().Add(txexecutor.SyncBound).Add(1 * time.Second) endTime = startTime.Add(defaultMinStakingDuration) @@ -423,8 +418,7 @@ func TestAddValidatorReject(t *testing.T) { ) // create valid tx - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), @@ -438,8 +432,6 @@ func TestAddValidatorReject(t *testing.T) { reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() @@ -462,10 +454,12 @@ func TestAddValidatorReject(t *testing.T) { // Reject proposal to add validator to primary network func TestAddValidatorInvalidNotReissued(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() + wallet := newWallet(t, vm, walletConfig{}) + // Use nodeID that is already in the genesis repeatNodeID := genesistest.DefaultNodeIDs[0] @@ -475,9 +469,13 @@ func TestAddValidatorInvalidNotReissued(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } + // create valid tx - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddPermissionlessValidatorTx( + tx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: repeatNodeID, @@ -489,19 +487,11 @@ func TestAddValidatorInvalidNotReissued(t *testing.T) { }, signer.NewProofOfPossession(sk), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() @@ -513,10 +503,15 @@ func TestAddValidatorInvalidNotReissued(t *testing.T) { // Accept proposal to add validator to subnet func TestAddSubnetValidatorAccept(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() + subnetID := testSubnet1.ID() + wallet := newWallet(t, vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + var ( startTime = vm.clock.Time().Add(txexecutor.SyncBound).Add(1 * time.Second) endTime = startTime.Add(defaultMinStakingDuration) @@ -526,8 +521,7 @@ func TestAddSubnetValidatorAccept(t *testing.T) { // create valid tx // note that [startTime, endTime] is a subset of time that keys[0] // validates primary network ([genesistest.DefaultValidatorStartTime, genesistest.DefaultValidatorEndTime]) - builder, txSigner := factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -535,40 +529,38 @@ func TestAddSubnetValidatorAccept(t *testing.T) { End: uint64(endTime.Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(tx)) vm.ctx.Lock.Lock() - - blk, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - - require.NoError(blk.Verify(context.Background())) - require.NoError(blk.Accept(context.Background())) + require.NoError(buildAndAcceptStandardBlock(vm)) _, txStatus, err := vm.state.GetTx(tx.ID()) require.NoError(err) require.Equal(status.Committed, txStatus) // Verify that new validator is in current validator set - _, err = vm.state.GetCurrentValidator(testSubnet1.ID(), nodeID) + _, err = vm.state.GetCurrentValidator(subnetID, nodeID) require.NoError(err) } // Reject proposal to add validator to subnet func TestAddSubnetValidatorReject(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() + subnetID := testSubnet1.ID() + wallet := newWallet(t, vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + var ( startTime = vm.clock.Time().Add(txexecutor.SyncBound).Add(1 * time.Second) endTime = startTime.Add(defaultMinStakingDuration) @@ -578,8 +570,7 @@ func TestAddSubnetValidatorReject(t *testing.T) { // create valid tx // note that [startTime, endTime] is a subset of time that keys[0] // validates primary network ([genesistest.DefaultValidatorStartTime, genesistest.DefaultValidatorEndTime]) - builder, txSigner := factory.NewWallet(testSubnet1ControlKeys[1], testSubnet1ControlKeys[2]) - utx, err := builder.NewAddSubnetValidatorTx( + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -591,8 +582,6 @@ func TestAddSubnetValidatorReject(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // trigger block creation vm.ctx.Lock.Unlock() @@ -616,7 +605,7 @@ func TestAddSubnetValidatorReject(t *testing.T) { // Test case where primary network validator rewarded func TestRewardValidatorAccept(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -684,7 +673,7 @@ func TestRewardValidatorAccept(t *testing.T) { // Test case where primary network validator not rewarded func TestRewardValidatorReject(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -754,7 +743,7 @@ func TestRewardValidatorReject(t *testing.T) { // Ensure BuildBlock errors when there is no block to build func TestUnneededBuildBlock(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -765,39 +754,35 @@ func TestUnneededBuildBlock(t *testing.T) { // test acceptance of proposal to create a new chain func TestCreateChain(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - builder, txSigner := factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + subnetID := testSubnet1.ID() + wallet := newWallet(t, vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, ids.ID{'t', 'e', 's', 't', 'v', 'm'}, nil, "name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(tx)) vm.ctx.Lock.Lock() - - blk, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) // should contain proposal to create chain - - require.NoError(blk.Verify(context.Background())) - - require.NoError(blk.Accept(context.Background())) + require.NoError(buildAndAcceptStandardBlock(vm)) _, txStatus, err := vm.state.GetTx(tx.ID()) require.NoError(err) require.Equal(status.Committed, txStatus) // Verify chain was created - chains, err := vm.state.GetChains(testSubnet1.ID()) + chains, err := vm.state.GetChains(subnetID) require.NoError(err) foundNewChain := false @@ -815,12 +800,12 @@ func TestCreateChain(t *testing.T) { // 3) Advance timestamp to validator's end time (removing validator from current) func TestCreateSubnet(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uCreateSubnetTx, err := builder.NewCreateSubnetTx( + wallet := newWallet(t, vm, walletConfig{}) + createSubnetTx, err := wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ @@ -828,28 +813,15 @@ func TestCreateSubnet(t *testing.T) { genesistest.DefaultFundedKeys[1].Address(), }, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(err) - createSubnetTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uCreateSubnetTx) - require.NoError(err) - subnetID := createSubnetTx.ID() vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(createSubnetTx)) vm.ctx.Lock.Lock() + require.NoError(buildAndAcceptStandardBlock(vm)) - // should contain the CreateSubnetTx - blk, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - - require.NoError(blk.Verify(context.Background())) - require.NoError(blk.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) - + subnetID := createSubnetTx.ID() _, txStatus, err := vm.state.GetTx(subnetID) require.NoError(err) require.Equal(status.Committed, txStatus) @@ -863,7 +835,7 @@ func TestCreateSubnet(t *testing.T) { startTime := vm.clock.Time().Add(txexecutor.SyncBound).Add(1 * time.Second) endTime := startTime.Add(defaultMinStakingDuration) // [startTime, endTime] is subset of time keys[0] validates default subnet so tx is valid - uAddValTx, err := builder.NewAddSubnetValidatorTx( + addValidatorTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -875,21 +847,13 @@ func TestCreateSubnet(t *testing.T) { }, ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddValTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addValidatorTx)) vm.ctx.Lock.Lock() + require.NoError(buildAndAcceptStandardBlock(vm)) - blk, err = vm.Builder.BuildBlock(context.Background()) // should add validator to the new subnet - require.NoError(err) - - require.NoError(blk.Verify(context.Background())) - require.NoError(blk.Accept(context.Background())) // add the validator to current validator set - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) - - txID := blk.(block.Block).Txs()[0].ID() + txID := addValidatorTx.ID() _, txStatus, err = vm.state.GetTx(txID) require.NoError(err) require.Equal(status.Committed, txStatus) @@ -900,12 +864,9 @@ func TestCreateSubnet(t *testing.T) { _, err = vm.state.GetCurrentValidator(subnetID, nodeID) require.NoError(err) - // fast forward clock to time validator should stop validating + // remove validator from current validator set vm.clock.Set(endTime) - blk, err = vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(blk.Verify(context.Background())) - require.NoError(blk.Accept(context.Background())) // remove validator from current validator set + require.NoError(buildAndAcceptStandardBlock(vm)) _, err = vm.state.GetPendingValidator(subnetID, nodeID) require.ErrorIs(err, database.ErrNotFound) @@ -917,43 +878,38 @@ func TestCreateSubnet(t *testing.T) { // test asset import func TestAtomicImport(t *testing.T) { require := require.New(t) - vm, factory, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Latest) + vm, baseDB, mutableSharedMemory := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - utxoID := avax.UTXOID{ - TxID: ids.Empty.Prefix(1), - OutputIndex: 1, - } - amount := uint64(50000) recipientKey := genesistest.DefaultFundedKeys[1] + importOwners := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{recipientKey.Address()}, + } m := atomic.NewMemory(prefixdb.New([]byte{5}, baseDB)) - mutableSharedMemory.SharedMemory = m.NewSharedMemory(vm.ctx.ChainID) - peerSharedMemory := m.NewSharedMemory(vm.ctx.XChainID) - builder, _ := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - _, err := builder.NewImportTx( + wallet := newWallet(t, vm, walletConfig{}) + _, err := wallet.IssueImportTx( vm.ctx.XChainID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{recipientKey.Address()}, - }, + importOwners, ) require.ErrorIs(err, walletbuilder.ErrInsufficientFunds) // Provide the avm UTXO - + peerSharedMemory := m.NewSharedMemory(vm.ctx.XChainID) + utxoID := avax.UTXOID{ + TxID: ids.GenerateTestID(), + OutputIndex: 1, + } utxo := &avax.UTXO{ UTXOID: utxoID, Asset: avax.Asset{ID: vm.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: amount, - OutputOwners: secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{recipientKey.Address()}, - }, + Amt: 50 * units.MicroAvax, + OutputOwners: *importOwners, }, } utxoBytes, err := txs.Codec.Marshal(txs.CodecVersion, utxo) @@ -974,28 +930,18 @@ func TestAtomicImport(t *testing.T) { }, })) - builder, txSigner := factory.NewWallet(recipientKey) - utx, err := builder.NewImportTx( + // The wallet must be re-loaded because the shared memory has changed + wallet = newWallet(t, vm, walletConfig{}) + tx, err := wallet.IssueImportTx( vm.ctx.XChainID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{recipientKey.Address()}, - }, + importOwners, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(tx)) vm.ctx.Lock.Lock() - - blk, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - - require.NoError(blk.Verify(context.Background())) - - require.NoError(blk.Accept(context.Background())) + require.NoError(buildAndAcceptStandardBlock(vm)) _, txStatus, err := vm.state.GetTx(tx.ID()) require.NoError(err) @@ -1009,7 +955,7 @@ func TestAtomicImport(t *testing.T) { // test optimistic asset import func TestOptimisticAtomicImport(t *testing.T) { require := require.New(t) - vm, _, _, _ := defaultVM(t, upgradetest.ApricotPhase3) + vm, _, _ := defaultVM(t, upgradetest.ApricotPhase3) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1648,7 +1594,7 @@ func TestUnverifiedParent(t *testing.T) { } func TestMaxStakeAmount(t *testing.T) { - vm, _, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -1944,20 +1890,21 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { validatorStartTime := latestForkTime.Add(txexecutor.SyncBound).Add(1 * time.Second) validatorEndTime := validatorStartTime.Add(360 * 24 * time.Hour) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - key, err := secp256k1.NewPrivateKey() - require.NoError(err) + wallet := newWallet(t, vm, walletConfig{}) - id := key.Address() nodeID := ids.GenerateTestNodeID() sk, err := bls.NewSecretKey() require.NoError(err) + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uAddValTx, err := builder.NewAddPermissionlessValidatorTx( + addValidatorTx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1969,62 +1916,32 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { }, signer.NewProofOfPossession(sk), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{id}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{id}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddValTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addValidatorTx)) vm.ctx.Lock.Lock() + require.NoError(buildAndAcceptStandardBlock(vm)) - // trigger block creation for the validator tx - addValidatorBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(addValidatorBlock.Verify(context.Background())) - require.NoError(addValidatorBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) - - uCreateSubnetTx, err := builder.NewCreateSubnetTx( + createSubnetTx, err := wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{id}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), + }, ) require.NoError(err) - createSubnetTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uCreateSubnetTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(createSubnetTx)) vm.ctx.Lock.Lock() + require.NoError(buildAndAcceptStandardBlock(vm)) - // trigger block creation for the subnet tx - createSubnetBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - require.NoError(createSubnetBlock.Verify(context.Background())) - require.NoError(createSubnetBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) - - builder, txSigner = factory.NewWallet(key, genesistest.DefaultFundedKeys[1]) - uAddSubnetValTx, err := builder.NewAddSubnetValidatorTx( + subnetID := createSubnetTx.ID() + addSubnetValidatorTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -2032,34 +1949,24 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { End: uint64(validatorEndTime.Unix()), Wght: defaultMaxValidatorStake, }, - Subnet: createSubnetTx.ID(), + Subnet: subnetID, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[1].Address()}, - }), ) require.NoError(err) - addSubnetValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddSubnetValTx) - require.NoError(err) - builder, txSigner = factory.NewWallet(key, genesistest.DefaultFundedKeys[2]) - uRemoveSubnetValTx, err := builder.NewRemoveSubnetValidatorTx( + removeSubnetValidatorTx, err := wallet.IssueRemoveSubnetValidatorTx( nodeID, - createSubnetTx.ID(), - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, - }), + subnetID, ) require.NoError(err) - removeSubnetValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uRemoveSubnetValTx) - require.NoError(err) + lastAcceptedID := vm.state.GetLastAccepted() + lastAcceptedHeight, err := vm.GetCurrentHeight(context.Background()) + require.NoError(err) statelessBlock, err := block.NewBanffStandardBlock( vm.state.GetTimestamp(), - createSubnetBlock.ID(), - createSubnetBlock.Height()+1, + lastAcceptedID, + lastAcceptedHeight+1, []*txs.Tx{ addSubnetValidatorTx, removeSubnetValidatorTx, @@ -2074,219 +1981,122 @@ func TestRemovePermissionedValidatorDuringAddPending(t *testing.T) { require.NoError(block.Accept(context.Background())) require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) - _, err = vm.state.GetPendingValidator(createSubnetTx.ID(), nodeID) + _, err = vm.state.GetPendingValidator(subnetID, nodeID) require.ErrorIs(err, database.ErrNotFound) } func TestTransferSubnetOwnershipTx(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uCreateSubnetTx, err := builder.NewCreateSubnetTx( - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), + wallet := newWallet(t, vm, walletConfig{}) + + expectedSubnetOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, + } + createSubnetTx, err := wallet.IssueCreateSubnetTx( + expectedSubnetOwner, ) require.NoError(err) - createSubnetTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uCreateSubnetTx) - require.NoError(err) - - subnetID := createSubnetTx.ID() vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(createSubnetTx)) vm.ctx.Lock.Lock() - createSubnetBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - - createSubnetRawBlock := createSubnetBlock.(*blockexecutor.Block).Block - require.IsType(&block.BanffStandardBlock{}, createSubnetRawBlock) - require.Contains(createSubnetRawBlock.Txs(), createSubnetTx) - - require.NoError(createSubnetBlock.Verify(context.Background())) - require.NoError(createSubnetBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + require.NoError(buildAndAcceptStandardBlock(vm)) + subnetID := createSubnetTx.ID() subnetOwner, err := vm.state.GetSubnetOwner(subnetID) require.NoError(err) - expectedOwner := &secp256k1fx.OutputOwners{ - Locktime: 0, + require.Equal(expectedSubnetOwner, subnetOwner) + + expectedSubnetOwner = &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{ - genesistest.DefaultFundedKeys[0].Address(), - }, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, } - ctx, err := walletbuilder.NewSnowContext(vm.ctx.NetworkID, vm.ctx.AVAXAssetID) - require.NoError(err) - expectedOwner.InitCtx(ctx) - require.Equal(expectedOwner, subnetOwner) - - uTransferSubnetOwnershipTx, err := builder.NewTransferSubnetOwnershipTx( + transferSubnetOwnershipTx, err := wallet.IssueTransferSubnetOwnershipTx( subnetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[1].Address()}, - }, + expectedSubnetOwner, ) require.NoError(err) - transferSubnetOwnershipTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uTransferSubnetOwnershipTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(transferSubnetOwnershipTx)) vm.ctx.Lock.Lock() - transferSubnetOwnershipBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) - - transferSubnetOwnershipRawBlock := transferSubnetOwnershipBlock.(*blockexecutor.Block).Block - require.IsType(&block.BanffStandardBlock{}, transferSubnetOwnershipRawBlock) - require.Contains(transferSubnetOwnershipRawBlock.Txs(), transferSubnetOwnershipTx) - - require.NoError(transferSubnetOwnershipBlock.Verify(context.Background())) - require.NoError(transferSubnetOwnershipBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + require.NoError(buildAndAcceptStandardBlock(vm)) subnetOwner, err = vm.state.GetSubnetOwner(subnetID) require.NoError(err) - expectedOwner = &secp256k1fx.OutputOwners{ - Locktime: 0, - Threshold: 1, - Addrs: []ids.ShortID{ - genesistest.DefaultFundedKeys[1].Address(), - }, - } - expectedOwner.InitCtx(ctx) - require.Equal(expectedOwner, subnetOwner) + require.Equal(expectedSubnetOwner, subnetOwner) } func TestBaseTx(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - sendAmt := uint64(100000) - changeAddr := ids.ShortEmpty + wallet := newWallet(t, vm, walletConfig{}) - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewBaseTx( + baseTx, err := wallet.IssueBaseTx( []*avax.TransferableOutput{ { Asset: avax.Asset{ID: vm.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: sendAmt, + Amt: 100 * units.MicroAvax, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ - genesistest.DefaultFundedKeys[1].Address(), + ids.GenerateTestShortID(), }, }, }, }, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), ) require.NoError(err) - baseTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) - - totalInputAmt := uint64(0) - key0InputAmt := uint64(0) - for inputID := range baseTx.Unsigned.InputIDs() { - utxo, err := vm.state.GetUTXO(inputID) - require.NoError(err) - require.IsType(&secp256k1fx.TransferOutput{}, utxo.Out) - castOut := utxo.Out.(*secp256k1fx.TransferOutput) - if castOut.AddressesSet().Equals(set.Of(genesistest.DefaultFundedKeys[0].Address())) { - key0InputAmt += castOut.Amt - } - totalInputAmt += castOut.Amt - } - require.Equal(totalInputAmt, key0InputAmt) - - totalOutputAmt := uint64(0) - key0OutputAmt := uint64(0) - key1OutputAmt := uint64(0) - changeAddrOutputAmt := uint64(0) - for _, output := range baseTx.Unsigned.Outputs() { - require.IsType(&secp256k1fx.TransferOutput{}, output.Out) - castOut := output.Out.(*secp256k1fx.TransferOutput) - if castOut.AddressesSet().Equals(set.Of(genesistest.DefaultFundedKeys[0].Address())) { - key0OutputAmt += castOut.Amt - } - if castOut.AddressesSet().Equals(set.Of(genesistest.DefaultFundedKeys[1].Address())) { - key1OutputAmt += castOut.Amt - } - if castOut.AddressesSet().Equals(set.Of(changeAddr)) { - changeAddrOutputAmt += castOut.Amt - } - totalOutputAmt += castOut.Amt - } - require.Equal(totalOutputAmt, key0OutputAmt+key1OutputAmt+changeAddrOutputAmt) - - require.Equal(vm.StaticFeeConfig.TxFee, totalInputAmt-totalOutputAmt) - require.Equal(sendAmt, key1OutputAmt) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(baseTx)) vm.ctx.Lock.Lock() - baseTxBlock, err := vm.Builder.BuildBlock(context.Background()) - require.NoError(err) + require.NoError(buildAndAcceptStandardBlock(vm)) - baseTxRawBlock := baseTxBlock.(*blockexecutor.Block).Block - require.IsType(&block.BanffStandardBlock{}, baseTxRawBlock) - require.Contains(baseTxRawBlock.Txs(), baseTx) - - require.NoError(baseTxBlock.Verify(context.Background())) - require.NoError(baseTxBlock.Accept(context.Background())) - require.NoError(vm.SetPreference(context.Background(), vm.manager.LastAccepted())) + _, txStatus, err := vm.state.GetTx(baseTx.ID()) + require.NoError(err) + require.Equal(status.Committed, txStatus) } func TestPruneMempool(t *testing.T) { require := require.New(t) - vm, factory, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Latest) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() - // Create a tx that will be valid regardless of timestamp. - sendAmt := uint64(100000) - changeAddr := ids.ShortEmpty + wallet := newWallet(t, vm, walletConfig{}) - builder, txSigner := factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewBaseTx( + // Create a tx that will be valid regardless of timestamp. + baseTx, err := wallet.IssueBaseTx( []*avax.TransferableOutput{ { Asset: avax.Asset{ID: vm.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: sendAmt, + Amt: 100 * units.MicroAvax, OutputOwners: secp256k1fx.OutputOwners{ Threshold: 1, Addrs: []ids.ShortID{ - genesistest.DefaultFundedKeys[1].Address(), + genesistest.DefaultFundedKeys[0].Address(), }, }, }, }, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{changeAddr}, - }), + walletcommon.WithCustomAddresses(set.Of( + genesistest.DefaultFundedKeys[0].Address(), + )), ) require.NoError(err) - baseTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(baseTx)) @@ -2306,8 +2116,11 @@ func TestPruneMempool(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner = factory.NewWallet(genesistest.DefaultFundedKeys[1]) - uAddValTx, err := builder.NewAddPermissionlessValidatorTx( + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } + addValidatorTx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: ids.GenerateTestNodeID(), @@ -2319,34 +2132,29 @@ func TestPruneMempool(t *testing.T) { }, signer.NewProofOfPossession(sk), vm.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, - }, + rewardsOwner, + rewardsOwner, 20000, + walletcommon.WithCustomAddresses(set.Of( + genesistest.DefaultFundedKeys[1].Address(), + )), ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uAddValTx) - require.NoError(err) vm.ctx.Lock.Unlock() require.NoError(vm.issueTxFromRPC(addValidatorTx)) vm.ctx.Lock.Lock() - // Advance clock to [endTime], making [addValidatorTx] invalid. - vm.clock.Set(endTime) - - // [addValidatorTx] and [baseTx] should still be in the mempool. + // [addValidatorTx] and [baseTx] should be in the mempool. addValidatorTxID := addValidatorTx.ID() _, ok = vm.Builder.Get(addValidatorTxID) require.True(ok) _, ok = vm.Builder.Get(baseTxID) require.True(ok) + // Advance clock to [endTime], making [addValidatorTx] invalid. + vm.clock.Set(endTime) + vm.ctx.Lock.Unlock() require.NoError(vm.pruneMempool()) vm.ctx.Lock.Lock() From 3272f3ae39801d12f0f0bc5a64cc82336b03efb4 Mon Sep 17 00:00:00 2001 From: marun Date: Mon, 26 Aug 2024 10:54:55 -0700 Subject: [PATCH 44/69] [tmpnet] Ensure nodes are stopped in the event of bootstrap failure (#3332) --- tests/fixture/e2e/helpers.go | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/tests/fixture/e2e/helpers.go b/tests/fixture/e2e/helpers.go index d0e9bf23399b..f26795c52801 100644 --- a/tests/fixture/e2e/helpers.go +++ b/tests/fixture/e2e/helpers.go @@ -204,16 +204,22 @@ func StartNetwork( ) { require := require.New(tc) - require.NoError( - tmpnet.BootstrapNewNetwork( - tc.DefaultContext(), - tc.GetWriter(), - network, - DefaultNetworkDir, - avalancheGoExecPath, - pluginDir, - ), + err := tmpnet.BootstrapNewNetwork( + tc.DefaultContext(), + tc.GetWriter(), + network, + DefaultNetworkDir, + avalancheGoExecPath, + pluginDir, ) + if err != nil { + // Ensure nodes are stopped if bootstrap fails. The network configuration + // will remain on disk to enable troubleshooting. + if stopErr := network.Stop(tc.DefaultContext()); stopErr != nil { + tc.Outf("failed to stop network after bootstrap failure: %v", stopErr) + } + require.FailNow("failed to bootstrap network: %s", err) + } tc.Outf("{{green}}Successfully started network{{/}}\n") From e6b59d737eea6a4a38195f7bc74c337c94093cef Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Mon, 26 Aug 2024 16:51:32 -0400 Subject: [PATCH 45/69] Add tx complexity helper (#3334) --- vms/platformvm/txs/fee/complexity.go | 22 +++++++-- vms/platformvm/txs/fee/complexity_test.go | 58 ++++++++++++++++++++++- 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/vms/platformvm/txs/fee/complexity.go b/vms/platformvm/txs/fee/complexity.go index 4b06417b8462..adae002e0009 100644 --- a/vms/platformvm/txs/fee/complexity.go +++ b/vms/platformvm/txs/fee/complexity.go @@ -183,10 +183,24 @@ var ( errUnsupportedSigner = errors.New("unsupported signer type") ) -func TxComplexity(tx txs.UnsignedTx) (gas.Dimensions, error) { - c := complexityVisitor{} - err := tx.Visit(&c) - return c.output, err +func TxComplexity(txs ...txs.UnsignedTx) (gas.Dimensions, error) { + var ( + c complexityVisitor + complexity gas.Dimensions + ) + for _, tx := range txs { + c = complexityVisitor{} + err := tx.Visit(&c) + if err != nil { + return gas.Dimensions{}, err + } + + complexity, err = complexity.Add(&c.output) + if err != nil { + return gas.Dimensions{}, err + } + } + return complexity, nil } // OutputComplexity returns the complexity outputs add to a transaction. diff --git a/vms/platformvm/txs/fee/complexity_test.go b/vms/platformvm/txs/fee/complexity_test.go index 08bb3b2fc920..0dd9ba90b3f0 100644 --- a/vms/platformvm/txs/fee/complexity_test.go +++ b/vms/platformvm/txs/fee/complexity_test.go @@ -23,7 +23,7 @@ import ( "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) -func TestTxComplexity(t *testing.T) { +func TestTxComplexity_Individual(t *testing.T) { for _, test := range txTests { t.Run(test.name, func(t *testing.T) { require := require.New(t) @@ -52,7 +52,37 @@ func TestTxComplexity(t *testing.T) { } } -func BenchmarkTxComplexity(b *testing.B) { +func TestTxComplexity_Batch(t *testing.T) { + require := require.New(t) + + var ( + unsignedTxs = make([]txs.UnsignedTx, 0, len(txTests)) + expectedComplexity gas.Dimensions + ) + for _, test := range txTests { + if test.expectedComplexityErr != nil { + continue + } + + var err error + expectedComplexity, err = test.expectedComplexity.Add(&expectedComplexity) + require.NoError(err) + + txBytes, err := hex.DecodeString(test.tx) + require.NoError(err) + + tx, err := txs.Parse(txs.Codec, txBytes) + require.NoError(err) + + unsignedTxs = append(unsignedTxs, tx.Unsigned) + } + + complexity, err := TxComplexity(unsignedTxs...) + require.NoError(err) + require.Equal(expectedComplexity, complexity) +} + +func BenchmarkTxComplexity_Individual(b *testing.B) { for _, test := range txTests { b.Run(test.name, func(b *testing.B) { require := require.New(b) @@ -71,6 +101,30 @@ func BenchmarkTxComplexity(b *testing.B) { } } +func BenchmarkTxComplexity_Batch(b *testing.B) { + require := require.New(b) + + unsignedTxs := make([]txs.UnsignedTx, 0, len(txTests)) + for _, test := range txTests { + if test.expectedComplexityErr != nil { + continue + } + + txBytes, err := hex.DecodeString(test.tx) + require.NoError(err) + + tx, err := txs.Parse(txs.Codec, txBytes) + require.NoError(err) + + unsignedTxs = append(unsignedTxs, tx.Unsigned) + } + + b.ResetTimer() + for i := 0; i < b.N; i++ { + _, _ = TxComplexity(unsignedTxs...) + } +} + func TestOutputComplexity(t *testing.T) { tests := []struct { name string From 4647158bffbb0134ea5677473587a767f24ee521 Mon Sep 17 00:00:00 2001 From: Zalan Blenessy Date: Tue, 27 Aug 2024 00:12:33 +0200 Subject: [PATCH 46/69] Fixed segfault when --tracing-enabled is set (#3330) --- snow/engine/common/traced_bootstrapable_engine.go | 1 + 1 file changed, 1 insertion(+) diff --git a/snow/engine/common/traced_bootstrapable_engine.go b/snow/engine/common/traced_bootstrapable_engine.go index 4c64206ae081..4185d0291a96 100644 --- a/snow/engine/common/traced_bootstrapable_engine.go +++ b/snow/engine/common/traced_bootstrapable_engine.go @@ -21,6 +21,7 @@ func TraceBootstrapableEngine(bootstrapableEngine BootstrapableEngine, tracer tr return &tracedBootstrapableEngine{ Engine: TraceEngine(bootstrapableEngine, tracer), bootstrapableEngine: bootstrapableEngine, + tracer: tracer, } } From 105713233a29c41432da9db55b164499c41fedfe Mon Sep 17 00:00:00 2001 From: Arran Schlosberg <519948+ARR4N@users.noreply.github.com> Date: Tue, 27 Aug 2024 15:12:55 +0100 Subject: [PATCH 47/69] chore: remove deprecated `validatorstest.TestState` (#3301) Signed-off-by: Arran Schlosberg <519948+ARR4N@users.noreply.github.com> --- snow/validators/validatorstest/state.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/snow/validators/validatorstest/state.go b/snow/validators/validatorstest/state.go index 64abbc515e5b..aa85160af791 100644 --- a/snow/validators/validatorstest/state.go +++ b/snow/validators/validatorstest/state.go @@ -23,12 +23,6 @@ var ( var _ validators.State = (*State)(nil) -// TestState is an alias for State because ava-labs/coreth uses the original -// identifier and this change would otherwise break the build. -// -// Deprecated: use [State]. -type TestState = State - type State struct { T testing.TB From f30febb9f453cab02fb514153ae0a64fe00e6367 Mon Sep 17 00:00:00 2001 From: Ian Suvak Date: Tue, 27 Aug 2024 12:34:37 -0400 Subject: [PATCH 48/69] Enforce network config not including `PrimaryNetworkID` in `trackedSubnets` (#3336) --- network/config.go | 1 + network/network.go | 13 +++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/network/config.go b/network/config.go index de8eb44e14a0..e0cdfd0a7432 100644 --- a/network/config.go +++ b/network/config.go @@ -131,6 +131,7 @@ type Config struct { BLSKey *bls.SecretKey `json:"-"` // TrackedSubnets of the node. + // It must not include the primary network ID. TrackedSubnets set.Set[ids.ID] `json:"-"` Beacons validators.Manager `json:"-"` diff --git a/network/network.go b/network/network.go index 9f785f34bd05..a7a1a0d03062 100644 --- a/network/network.go +++ b/network/network.go @@ -51,10 +51,11 @@ const ( var ( _ Network = (*network)(nil) - errNotValidator = errors.New("node is not a validator") - errNotTracked = errors.New("subnet is not tracked") - errExpectedProxy = errors.New("expected proxy") - errExpectedTCPProtocol = errors.New("expected TCP protocol") + errNotValidator = errors.New("node is not a validator") + errNotTracked = errors.New("subnet is not tracked") + errExpectedProxy = errors.New("expected proxy") + errExpectedTCPProtocol = errors.New("expected TCP protocol") + errTrackingPrimaryNetwork = errors.New("cannot track primary network") ) // Network defines the functionality of the networking library. @@ -202,6 +203,10 @@ func NewNetwork( } } + if config.TrackedSubnets.Contains(constants.PrimaryNetworkID) { + return nil, errTrackingPrimaryNetwork + } + inboundMsgThrottler, err := throttling.NewInboundMsgThrottler( log, metricsRegisterer, From 50421c6ec32a69040f811304a9a1b1f2d551a4be Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 27 Aug 2024 15:10:51 -0400 Subject: [PATCH 49/69] Use wallet in `platformvm/block` tests (#3328) --- vms/platformvm/block/builder/builder_test.go | 120 +++++------ vms/platformvm/block/builder/helpers_test.go | 45 +++-- .../block/builder/standard_block_test.go | 40 ++-- vms/platformvm/block/executor/helpers_test.go | 118 +++++------ .../block/executor/proposal_block_test.go | 186 +++++++----------- .../block/executor/standard_block_test.go | 54 +++-- 6 files changed, 245 insertions(+), 318 deletions(-) diff --git a/vms/platformvm/block/builder/builder_test.go b/vms/platformvm/block/builder/builder_test.go index 2d83b37615d0..e691c6f6ce2e 100644 --- a/vms/platformvm/block/builder/builder_test.go +++ b/vms/platformvm/block/builder/builder_test.go @@ -21,17 +21,14 @@ import ( "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/platformvm/block" - "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) func TestBuildBlockBasic(t *testing.T) { @@ -41,24 +38,27 @@ func TestBuildBlockBasic(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + // Create a valid transaction - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, constants.AVMID, nil, "chain name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) - txID := tx.ID() // Issue the transaction env.ctx.Lock.Unlock() require.NoError(env.network.IssueTxFromRPC(tx)) env.ctx.Lock.Lock() + + txID := tx.ID() _, ok := env.mempool.Get(txID) require.True(ok) @@ -101,6 +101,8 @@ func TestBuildBlockShouldReward(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() + wallet := newWallet(t, env, walletConfig{}) + var ( now = env.backend.Clk.Time() nodeID = ids.GenerateTestNodeID() @@ -113,9 +115,13 @@ func TestBuildBlockShouldReward(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) + rewardOwners := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } + // Create a valid [AddPermissionlessValidatorTx] - builder, txSigner := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddPermissionlessValidatorTx( + tx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -127,29 +133,18 @@ func TestBuildBlockShouldReward(t *testing.T) { }, signer.NewProofOfPossession(sk), env.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, + rewardOwners, + rewardOwners, reward.PercentDenominator, - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) - txID := tx.ID() // Issue the transaction env.ctx.Lock.Unlock() require.NoError(env.network.IssueTxFromRPC(tx)) env.ctx.Lock.Lock() + + txID := tx.ID() _, ok := env.mempool.Get(txID) require.True(ok) @@ -253,24 +248,27 @@ func TestBuildBlockForceAdvanceTime(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + // Create a valid transaction - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, constants.AVMID, nil, "chain name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) - txID := tx.ID() // Issue the transaction env.ctx.Lock.Unlock() require.NoError(env.network.IssueTxFromRPC(tx)) env.ctx.Lock.Lock() + + txID := tx.ID() _, ok := env.mempool.Get(txID) require.True(ok) @@ -312,6 +310,8 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { // based on the current chain timestamp and must be validated. env.config.UpgradeConfig.DurangoTime = time.Time{} + wallet := newWallet(t, env, walletConfig{}) + var ( now = env.backend.Clk.Time() defaultValidatorStake = 100 * units.MilliAvax @@ -323,8 +323,11 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) - builder1, signer1 := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx1, err := builder1.NewAddPermissionlessValidatorTx( + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } + tx1, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: ids.GenerateTestNodeID(), @@ -336,24 +339,13 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { }, signer.NewProofOfPossession(sk), env.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(err) - tx1, err := walletsigner.SignUnsigned(context.Background(), signer1, utx1) - require.NoError(err) require.NoError(env.mempool.Add(tx1)) + tx1ID := tx1.ID() _, ok := env.mempool.Get(tx1ID) require.True(ok) @@ -364,8 +356,7 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { sk, err = bls.NewSecretKey() require.NoError(err) - builder2, signer2 := env.factory.NewWallet(genesistest.DefaultFundedKeys[2]) - utx2, err := builder2.NewAddPermissionlessValidatorTx( + tx2, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: ids.GenerateTestNodeID(), @@ -377,24 +368,13 @@ func TestBuildBlockInvalidStakingDurations(t *testing.T) { }, signer.NewProofOfPossession(sk), env.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, - }, + rewardsOwner, + rewardsOwner, reward.PercentDenominator, - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[2].Address()}, - }), ) require.NoError(err) - tx2, err := walletsigner.SignUnsigned(context.Background(), signer2, utx2) - require.NoError(err) require.NoError(env.mempool.Add(tx2)) + tx2ID := tx2.ID() _, ok = env.mempool.Get(tx2ID) require.True(ok) @@ -428,9 +408,13 @@ func TestPreviouslyDroppedTxsCannotBeReAddedToMempool(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + // Create a valid transaction - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( + tx, err := wallet.IssueCreateChainTx( testSubnet1.ID(), nil, constants.AVMID, @@ -438,12 +422,10 @@ func TestPreviouslyDroppedTxsCannotBeReAddedToMempool(t *testing.T) { "chain name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) - txID := tx.ID() // Transaction should not be marked as dropped before being added to the // mempool + txID := tx.ID() require.NoError(env.mempool.GetDropReason(txID)) // Mark the transaction as dropped diff --git a/vms/platformvm/block/builder/helpers_test.go b/vms/platformvm/block/builder/helpers_test.go index 79b4453f6aa0..02f7102a562c 100644 --- a/vms/platformvm/block/builder/helpers_test.go +++ b/vms/platformvm/block/builder/helpers_test.go @@ -28,6 +28,7 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" @@ -46,12 +47,11 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/platformvm/utxo" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" txexecutor "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" pvalidators "github.com/ava-labs/avalanchego/vms/platformvm/validators" - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" - walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) const ( @@ -61,10 +61,7 @@ const ( defaultTxFee = 100 * units.NanoAvax ) -var ( - testSubnet1 *txs.Tx - testSubnet1ControlKeys = genesistest.DefaultFundedKeys[0:3] -) +var testSubnet1 *txs.Tx type mutableSharedMemory struct { atomic.SharedMemory @@ -87,7 +84,6 @@ type environment struct { state state.State uptimes uptime.Manager utxosVerifier utxo.Verifier - factory *txstest.WalletFactory backend txexecutor.Backend } @@ -127,7 +123,6 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { //nolint:un res.uptimes = uptime.NewManager(res.state, res.clk) res.utxosVerifier = utxo.NewVerifier(res.ctx, res.clk, res.fx) - res.factory = txstest.NewWalletFactory(res.ctx, res.config, res.state) genesisID := res.state.GetLastAccepted() res.backend = txexecutor.Backend{ @@ -207,11 +202,35 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { //nolint:un return res } +type walletConfig struct { + keys []*secp256k1.PrivateKey + subnetIDs []ids.ID +} + +func newWallet(t testing.TB, e *environment, c walletConfig) wallet.Wallet { + if len(c.keys) == 0 { + c.keys = genesistest.DefaultFundedKeys + } + return txstest.NewWallet( + t, + e.ctx, + e.config, + e.state, + secp256k1fx.NewKeychain(c.keys...), + c.subnetIDs, + []ids.ID{e.ctx.CChainID, e.ctx.XChainID}, + ) +} + func addSubnet(t *testing.T, env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewCreateSubnetTx( + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + + var err error + testSubnet1, err = wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 2, Addrs: []ids.ShortID{ @@ -220,14 +239,8 @@ func addSubnet(t *testing.T, env *environment) { genesistest.DefaultFundedKeys[2].Address(), }, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(err) - testSubnet1, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) genesisID := env.state.GetLastAccepted() stateDiff, err := state.NewDiff(genesisID, env.blkManager) diff --git a/vms/platformvm/block/builder/standard_block_test.go b/vms/platformvm/block/builder/standard_block_test.go index e97cbee313fd..12adfe6ff0d9 100644 --- a/vms/platformvm/block/builder/standard_block_test.go +++ b/vms/platformvm/block/builder/standard_block_test.go @@ -13,13 +13,12 @@ import ( "github.com/ava-labs/avalanchego/database/prefixdb" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/upgrade/upgradetest" + "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) func TestAtomicTxImports(t *testing.T) { @@ -29,26 +28,25 @@ func TestAtomicTxImports(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - utxoID := avax.UTXOID{ - TxID: ids.Empty.Prefix(1), - OutputIndex: 1, + addr := genesistest.DefaultFundedKeys[0].Address() + owner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{addr}, } - amount := uint64(70000) - recipientKey := genesistest.DefaultFundedKeys[1] m := atomic.NewMemory(prefixdb.New([]byte{5}, env.baseDB)) env.msm.SharedMemory = m.NewSharedMemory(env.ctx.ChainID) peerSharedMemory := m.NewSharedMemory(env.ctx.XChainID) utxo := &avax.UTXO{ - UTXOID: utxoID, - Asset: avax.Asset{ID: env.ctx.AVAXAssetID}, + UTXOID: avax.UTXOID{ + TxID: ids.GenerateTestID(), + OutputIndex: 1, + }, + Asset: avax.Asset{ID: env.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: amount, - OutputOwners: secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{recipientKey.Address()}, - }, + Amt: 70 * units.MicroAvax, + OutputOwners: *owner, }, } utxoBytes, err := txs.Codec.Marshal(txs.CodecVersion, utxo) @@ -60,22 +58,18 @@ func TestAtomicTxImports(t *testing.T) { Key: inputID[:], Value: utxoBytes, Traits: [][]byte{ - recipientKey.Address().Bytes(), + addr.Bytes(), }, }}}, })) - builder, signer := env.factory.NewWallet(recipientKey) - utx, err := builder.NewImportTx( + wallet := newWallet(t, env, walletConfig{}) + + tx, err := wallet.IssueImportTx( env.ctx.XChainID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{recipientKey.Address()}, - }, + owner, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) require.NoError(env.Builder.Add(tx)) b, err := env.Builder.BuildBlock(context.Background()) diff --git a/vms/platformvm/block/executor/helpers_test.go b/vms/platformvm/block/executor/helpers_test.go index 947fd15a8691..f066b1fc13c7 100644 --- a/vms/platformvm/block/executor/helpers_test.go +++ b/vms/platformvm/block/executor/helpers_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "fmt" "testing" "time" @@ -48,10 +47,9 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/platformvm/utxo" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" pvalidators "github.com/ava-labs/avalanchego/vms/platformvm/validators" - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" - walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) const ( @@ -98,7 +96,6 @@ type environment struct { mockedState *state.MockState uptimes uptime.Manager utxosVerifier utxo.Verifier - factory *txstest.WalletFactory backend *executor.Backend } @@ -132,20 +129,10 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * res.uptimes = uptime.NewManager(res.state, res.clk) res.utxosVerifier = utxo.NewVerifier(res.ctx, res.clk, res.fx) - res.factory = txstest.NewWalletFactory( - res.ctx, - res.config, - res.state, - ) } else { res.mockedState = state.NewMockState(ctrl) res.uptimes = uptime.NewManager(res.mockedState, res.clk) res.utxosVerifier = utxo.NewVerifier(res.ctx, res.clk, res.fx) - res.factory = txstest.NewWalletFactory( - res.ctx, - res.config, - res.mockedState, - ) // setup expectations strictly needed for environment creation res.mockedState.EXPECT().GetLastAccepted().Return(ids.GenerateTestID()).Times(1) @@ -181,7 +168,7 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * res.backend, pvalidators.TestManager, ) - addSubnet(res) + addSubnet(t, res) } else { res.blkManager = NewManager( res.mempool, @@ -222,9 +209,35 @@ func newEnvironment(t *testing.T, ctrl *gomock.Controller, f upgradetest.Fork) * return res } -func addSubnet(env *environment) { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewCreateSubnetTx( +type walletConfig struct { + keys []*secp256k1.PrivateKey + subnetIDs []ids.ID +} + +func newWallet(t testing.TB, e *environment, c walletConfig) wallet.Wallet { + if len(c.keys) == 0 { + c.keys = genesistest.DefaultFundedKeys + } + return txstest.NewWallet( + t, + e.ctx, + e.config, + e.state, + secp256k1fx.NewKeychain(c.keys...), + c.subnetIDs, + []ids.ID{e.ctx.CChainID, e.ctx.XChainID}, + ) +} + +func addSubnet(t testing.TB, env *environment) { + require := require.New(t) + + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + + var err error + testSubnet1, err = wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 2, Addrs: []ids.ShortID{ @@ -233,24 +246,13 @@ func addSubnet(env *environment) { genesistest.DefaultFundedKeys[2].Address(), }, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) - if err != nil { - panic(err) - } - testSubnet1, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - if err != nil { - panic(err) - } + require.NoError(err) genesisID := env.state.GetLastAccepted() stateDiff, err := state.NewDiff(genesisID, env.blkManager) - if err != nil { - panic(err) - } + require.NoError(err) + feeCalculator := state.PickFeeCalculator(env.config, stateDiff) executor := executor.StandardTxExecutor{ Backend: env.backend, @@ -258,18 +260,11 @@ func addSubnet(env *environment) { FeeCalculator: feeCalculator, Tx: testSubnet1, } - err = testSubnet1.Unsigned.Visit(&executor) - if err != nil { - panic(err) - } + require.NoError(testSubnet1.Unsigned.Visit(&executor)) stateDiff.AddTx(testSubnet1, status.Committed) - if err := stateDiff.Apply(env.state); err != nil { - panic(err) - } - if err := env.state.Commit(); err != nil { - panic(err) - } + require.NoError(stateDiff.Apply(env.state)) + require.NoError(env.state.Commit()) } func defaultConfig(f upgradetest.Fork) *config.Config { @@ -348,15 +343,21 @@ func defaultFx(clk *mockable.Clock, log logging.Logger, isBootstrapped bool) fx. } func addPendingValidator( + t testing.TB, env *environment, startTime time.Time, endTime time.Time, nodeID ids.NodeID, rewardAddress ids.ShortID, keys []*secp256k1.PrivateKey, -) (*txs.Tx, error) { - builder, signer := env.factory.NewWallet(keys...) - utx, err := builder.NewAddValidatorTx( +) *txs.Tx { + require := require.New(t) + + wallet := newWallet(t, env, walletConfig{ + keys: keys, + }) + + addValidatorTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), @@ -369,28 +370,17 @@ func addPendingValidator( }, reward.PercentDenominator, ) - if err != nil { - return nil, err - } - addPendingValidatorTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - if err != nil { - return nil, err - } + require.NoError(err) staker, err := state.NewPendingStaker( - addPendingValidatorTx.ID(), - addPendingValidatorTx.Unsigned.(*txs.AddValidatorTx), + addValidatorTx.ID(), + addValidatorTx.Unsigned.(*txs.AddValidatorTx), ) - if err != nil { - return nil, err - } + require.NoError(err) env.state.PutPendingValidator(staker) - env.state.AddTx(addPendingValidatorTx, status.Committed) - dummyHeight := uint64(1) - env.state.SetHeight(dummyHeight) - if err := env.state.Commit(); err != nil { - return nil, err - } - return addPendingValidatorTx, nil + env.state.AddTx(addValidatorTx, status.Committed) + env.state.SetHeight(1) + require.NoError(env.state.Commit()) + return addValidatorTx } diff --git a/vms/platformvm/block/executor/proposal_block_test.go b/vms/platformvm/block/executor/proposal_block_test.go index 1060c1c59be0..397802cf0faa 100644 --- a/vms/platformvm/block/executor/proposal_block_test.go +++ b/vms/platformvm/block/executor/proposal_block_test.go @@ -33,7 +33,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" walletcommon "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" ) @@ -521,8 +520,9 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) for _, staker := range test.stakers { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: staker.nodeID, Start: uint64(staker.startTime.Unix()), @@ -534,14 +534,8 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { Addrs: []ids.ShortID{staker.rewardAddress}, }, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }), ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( tx.ID(), @@ -555,8 +549,11 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { } for _, subStaker := range test.subnetStakers { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subStaker.nodeID, @@ -566,14 +563,8 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { }, Subnet: subnetID, }, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }), ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) subnetStaker, err := state.NewPendingStaker( tx.ID(), @@ -592,8 +583,10 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance staker0.endTime = newTime - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddValidatorTx( + + wallet := newWallet(t, env, walletConfig{}) + + addStaker0, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: staker0.nodeID, Start: uint64(staker0.startTime.Unix()), @@ -605,14 +598,8 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { Addrs: []ids.ShortID{staker0.rewardAddress}, }, reward.PercentDenominator, - walletcommon.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }), ) require.NoError(err) - addStaker0, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // store Staker0 to state addValTx := addStaker0.Unsigned.(*txs.AddValidatorTx) @@ -696,13 +683,16 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { env := newEnvironment(t, nil, upgradetest.Banff) subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + env.config.TrackedSubnets.Add(subnetID) // Add a subnet validator to the staker set subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, @@ -714,8 +704,6 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addSubnetValTx := tx.Unsigned.(*txs.AddSubnetValidatorTx) staker, err := state.NewCurrentStaker( @@ -734,7 +722,7 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { // Queue a staker that joins the staker set after the above validator leaves subnetVdr2NodeID := genesistest.DefaultNodeIDs[1] - utx, err = builder.NewAddSubnetValidatorTx( + tx, err = wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetVdr2NodeID, @@ -746,8 +734,6 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { }, ) require.NoError(err) - tx, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err = state.NewPendingStaker( tx.ID(), @@ -767,7 +753,7 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance staker0EndTime := subnetVdr1EndTime - uVdrTx, err := builder.NewAddValidatorTx( + addStaker0, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), Start: genesistest.DefaultValidatorStartTimeUnix, @@ -785,8 +771,6 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { }), ) require.NoError(err) - addStaker0, err := walletsigner.SignUnsigned(context.Background(), signer, uVdrTx) - require.NoError(err) // store Staker0 to state addValTx := addStaker0.Unsigned.(*txs.AddValidatorTx) @@ -855,13 +839,16 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) } + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + // Add a subnet validator to the staker set subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] subnetVdr1StartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Minute) subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, @@ -873,8 +860,6 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( tx.ID(), @@ -894,7 +879,7 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { staker0StartTime := genesistest.DefaultValidatorStartTime staker0EndTime := subnetVdr1StartTime - uVdrTx, err := builder.NewAddValidatorTx( + addStaker0, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), Start: uint64(staker0StartTime.Unix()), @@ -908,8 +893,6 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { reward.PercentDenominator, ) require.NoError(err) - addStaker0, err := walletsigner.SignUnsigned(context.Background(), signer, uVdrTx) - require.NoError(err) // store Staker0 to state addValTx := addStaker0.Unsigned.(*txs.AddValidatorTx) @@ -970,7 +953,8 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMaxStakingDuration) nodeID := ids.GenerateTestNodeID() rewardAddress := ids.GenerateTestShortID() - _, err := addPendingValidator( + addPendingValidator( + t, env, pendingValidatorStartTime, pendingValidatorEndTime, @@ -978,29 +962,29 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { rewardAddress, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) - require.NoError(err) + + wallet := newWallet(t, env, walletConfig{}) + + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } // add Staker0 (with the right end time) to state // just to allow proposalBlk issuance (with a reward Tx) staker0StartTime := genesistest.DefaultValidatorStartTime staker0EndTime := pendingValidatorStartTime - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddValidatorTx( + addStaker0, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), Start: uint64(staker0StartTime.Unix()), End: uint64(staker0EndTime.Unix()), Wght: 10, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - addStaker0, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // store Staker0 to state addValTx := addStaker0.Unsigned.(*txs.AddValidatorTx) @@ -1054,23 +1038,16 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { // Add delegator pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(1 * time.Second) - - builder, signer = env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) - uDelTx, err := builder.NewAddDelegatorTx( + addDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(pendingDelegatorStartTime.Unix()), End: uint64(pendingDelegatorEndTime.Unix()), Wght: env.config.MinDelegatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, + rewardsOwner, ) require.NoError(err) - addDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), signer, uDelTx) - require.NoError(err) staker, err = state.NewPendingStaker( addDelegatorTx.ID(), @@ -1086,23 +1063,17 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance staker0EndTime = pendingDelegatorStartTime - builder, signer = env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err = builder.NewAddValidatorTx( + addStaker0, err = wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), Start: uint64(staker0StartTime.Unix()), End: uint64(staker0EndTime.Unix()), Wght: 10, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - addStaker0, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // store Staker0 to state addValTx = addStaker0.Unsigned.(*txs.AddValidatorTx) @@ -1167,7 +1138,8 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { rewardAddress := nodeIDKey.Address() nodeID := ids.BuildTestNodeID(rewardAddress[:]) - _, err := addPendingValidator( + addPendingValidator( + t, env, pendingValidatorStartTime, pendingValidatorEndTime, @@ -1175,29 +1147,29 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { rewardAddress, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) - require.NoError(err) + + wallet := newWallet(t, env, walletConfig{}) + + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance staker0StartTime := genesistest.DefaultValidatorStartTime staker0EndTime := pendingValidatorStartTime - builder, txSigner := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddValidatorTx( + addStaker0, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), Start: uint64(staker0StartTime.Unix()), End: uint64(staker0EndTime.Unix()), Wght: 10, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - addStaker0, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // store Staker0 to state addValTx := addStaker0.Unsigned.(*txs.AddValidatorTx) @@ -1251,22 +1223,16 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { // Add delegator pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(defaultMinStakingDuration) - builder, txSigner = env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) - uDelTx, err := builder.NewAddDelegatorTx( + addDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(pendingDelegatorStartTime.Unix()), End: uint64(pendingDelegatorEndTime.Unix()), Wght: env.config.MinDelegatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, + rewardsOwner, ) require.NoError(err) - addDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, uDelTx) - require.NoError(err) staker, err = state.NewPendingStaker( addDelegatorTx.ID(), @@ -1282,23 +1248,17 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { // add Staker0 (with the right end time) to state // so to allow proposalBlk issuance staker0EndTime = pendingDelegatorStartTime - builder, txSigner = env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err = builder.NewAddValidatorTx( + addStaker0, err = wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), Start: uint64(staker0StartTime.Unix()), End: uint64(staker0EndTime.Unix()), Wght: 10, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - addStaker0, err = walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // store Staker0 to state addValTx = addStaker0.Unsigned.(*txs.AddValidatorTx) @@ -1354,6 +1314,8 @@ func TestAddValidatorProposalBlock(t *testing.T) { require := require.New(t) env := newEnvironment(t, nil, upgradetest.Durango) + wallet := newWallet(t, env, walletConfig{}) + now := env.clk.Time() // Create validator tx @@ -1366,8 +1328,12 @@ func TestAddValidatorProposalBlock(t *testing.T) { sk, err := bls.NewSecretKey() require.NoError(err) - builder, txSigner := env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) - utx, err := builder.NewAddPermissionlessValidatorTx( + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } + + addValidatorTx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1379,19 +1345,11 @@ func TestAddValidatorProposalBlock(t *testing.T) { }, signer.NewProofOfPossession(sk), env.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, + rewardsOwner, + rewardsOwner, 10000, ) require.NoError(err) - addValidatorTx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(err) // Add validator through a [StandardBlock] preferredID := env.blkManager.Preferred() @@ -1451,7 +1409,7 @@ func TestAddValidatorProposalBlock(t *testing.T) { sk, err = bls.NewSecretKey() require.NoError(err) - utx2, err := builder.NewAddPermissionlessValidatorTx( + addValidatorTx2, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1463,19 +1421,11 @@ func TestAddValidatorProposalBlock(t *testing.T) { }, signer.NewProofOfPossession(sk), env.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }, + rewardsOwner, + rewardsOwner, 10000, ) require.NoError(err) - addValidatorTx2, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx2) - require.NoError(err) // Add validator through a [ProposalBlock] and reward the last one preferredID = env.blkManager.Preferred() diff --git a/vms/platformvm/block/executor/standard_block_test.go b/vms/platformvm/block/executor/standard_block_test.go index 3b9b55408ef1..15cc43cdad93 100644 --- a/vms/platformvm/block/executor/standard_block_test.go +++ b/vms/platformvm/block/executor/standard_block_test.go @@ -28,8 +28,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) func TestApricotStandardBlockTimeVerification(t *testing.T) { @@ -302,7 +300,8 @@ func TestBanffStandardBlockUpdatePrimaryNetworkStakers(t *testing.T) { pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeID := ids.GenerateTestNodeID() rewardAddress := ids.GenerateTestShortID() - addPendingValidatorTx, err := addPendingValidator( + addPendingValidatorTx := addPendingValidator( + t, env, pendingValidatorStartTime, pendingValidatorEndTime, @@ -310,7 +309,6 @@ func TestBanffStandardBlockUpdatePrimaryNetworkStakers(t *testing.T) { rewardAddress, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) - require.NoError(err) // build standard block moving ahead chain time preferredID := env.state.GetLastAccepted() @@ -501,7 +499,8 @@ func TestBanffStandardBlockUpdateStakers(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) for _, staker := range test.stakers { - _, err := addPendingValidator( + addPendingValidator( + t, env, staker.startTime, staker.endTime, @@ -509,12 +508,14 @@ func TestBanffStandardBlockUpdateStakers(t *testing.T) { staker.rewardAddress, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) - require.NoError(err) } for _, staker := range test.subnetStakers { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: staker.nodeID, @@ -526,8 +527,6 @@ func TestBanffStandardBlockUpdateStakers(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( tx.ID(), @@ -603,11 +602,14 @@ func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { subnetID := testSubnet1.ID() env.config.TrackedSubnets.Add(subnetID) + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + // Add a subnet validator to the staker set subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, @@ -619,8 +621,6 @@ func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addSubnetValTx := tx.Unsigned.(*txs.AddSubnetValidatorTx) staker, err := state.NewCurrentStaker( @@ -639,7 +639,7 @@ func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { // Queue a staker that joins the staker set after the above validator leaves subnetVdr2NodeID := genesistest.DefaultNodeIDs[1] - utx, err = builder.NewAddSubnetValidatorTx( + tx, err = wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetVdr2NodeID, @@ -651,8 +651,6 @@ func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { }, ) require.NoError(err) - tx, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err = state.NewPendingStaker( tx.ID(), @@ -708,12 +706,15 @@ func TestBanffStandardBlockTrackedSubnet(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) } + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + // Add a subnet validator to the staker set subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] subnetVdr1StartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Minute) subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, @@ -725,8 +726,6 @@ func TestBanffStandardBlockTrackedSubnet(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( tx.ID(), @@ -773,7 +772,8 @@ func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMaxStakingDuration) nodeID := ids.GenerateTestNodeID() rewardAddress := ids.GenerateTestShortID() - _, err := addPendingValidator( + addPendingValidator( + t, env, pendingValidatorStartTime, pendingValidatorEndTime, @@ -781,7 +781,6 @@ func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { rewardAddress, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) - require.NoError(err) // build standard block moving ahead chain time preferredID := env.state.GetLastAccepted() @@ -803,12 +802,13 @@ func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { vdrWeight := env.config.Validators.GetWeight(constants.PrimaryNetworkID, nodeID) require.Equal(env.config.MinValidatorStake, vdrWeight) + wallet := newWallet(t, env, walletConfig{}) + // Add delegator pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) - utx, err := builder.NewAddDelegatorTx( + addDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(pendingDelegatorStartTime.Unix()), @@ -817,12 +817,10 @@ func TestBanffStandardBlockDelegatorStakerWeight(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, }, ) require.NoError(err) - addDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( addDelegatorTx.ID(), From 33cc086168adeb9392b7fd1d4e8390ff7f85ce85 Mon Sep 17 00:00:00 2001 From: marun Date: Tue, 27 Aug 2024 12:26:42 -0700 Subject: [PATCH 50/69] [ci] Stop using setup-go-v3 (#3339) --- .../setup-go-for-project-v3/action.yml | 24 ------------------- .github/workflows/build-linux-binaries.yml | 2 +- .../workflows/build-ubuntu-arm64-release.yml | 4 ++-- .github/workflows/ci.yml | 2 +- 4 files changed, 4 insertions(+), 28 deletions(-) delete mode 100644 .github/actions/setup-go-for-project-v3/action.yml diff --git a/.github/actions/setup-go-for-project-v3/action.yml b/.github/actions/setup-go-for-project-v3/action.yml deleted file mode 100644 index b92bbdfb2aec..000000000000 --- a/.github/actions/setup-go-for-project-v3/action.yml +++ /dev/null @@ -1,24 +0,0 @@ -# This action targets setup-go@v3 to support workers with old NodeJS -# incompabible with newer versions of setup-go. -# -# Since github actions do not support dynamically configuring the -# versions in a uses statement (e.g. `actions/setup-go@${{ var }}`) it -# is necessary to define an action per version rather than one action -# that can be parameterized. -# -# Must be run after actions/checkout to ensure go.mod is available to -# source the project's go version from. - -name: 'Install Go toolchain with project defaults' -description: 'Install a go toolchain with project defaults' - -runs: - using: composite - steps: - - name: Set the project Go version in the environment - uses: ./.github/actions/set-go-version-in-env - - name: Set up Go - uses: actions/setup-go@v3 - with: - go-version: '${{ env.GO_VERSION }}' - check-latest: true diff --git a/.github/workflows/build-linux-binaries.yml b/.github/workflows/build-linux-binaries.yml index bcaf374f3935..08936031d3b0 100644 --- a/.github/workflows/build-linux-binaries.yml +++ b/.github/workflows/build-linux-binaries.yml @@ -78,7 +78,7 @@ jobs: - uses: ./.github/actions/install-focal-deps - - uses: ./.github/actions/setup-go-for-project-v3 + - uses: ./.github/actions/setup-go-for-project - run: go version diff --git a/.github/workflows/build-ubuntu-arm64-release.yml b/.github/workflows/build-ubuntu-arm64-release.yml index 4d8fa841cbd8..514813c82cce 100644 --- a/.github/workflows/build-ubuntu-arm64-release.yml +++ b/.github/workflows/build-ubuntu-arm64-release.yml @@ -16,7 +16,7 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: ./.github/actions/setup-go-for-project-v3 + - uses: ./.github/actions/setup-go-for-project - run: go version - name: Build the avalanchego binaries @@ -74,7 +74,7 @@ jobs: steps: - uses: actions/checkout@v4 - uses: ./.github/actions/install-focal-deps - - uses: ./.github/actions/setup-go-for-project-v3 + - uses: ./.github/actions/setup-go-for-project - run: go version - name: Build the avalanchego binaries diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ffc4a0ae5530..07edd1b0443a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,7 +30,7 @@ jobs: - uses: actions/checkout@v4 - uses: ./.github/actions/install-focal-deps if: matrix.os == 'custom-arm64-focal' - - uses: ./.github/actions/setup-go-for-project-v3 + - uses: ./.github/actions/setup-go-for-project - name: Set timeout on Windows # Windows UT run slower and need a longer timeout shell: bash if: matrix.os == 'windows-2022' From 0117ab96791c9e3b2a35c51b4315e3928dffb983 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 27 Aug 2024 15:40:54 -0400 Subject: [PATCH 51/69] Use wallet in `platformvm/txs` tests (#3333) --- .../txs/executor/advance_time_test.go | 99 ++- .../txs/executor/create_chain_test.go | 83 +-- .../txs/executor/create_subnet_test.go | 18 +- vms/platformvm/txs/executor/export_test.go | 26 +- vms/platformvm/txs/executor/helpers_test.go | 52 +- vms/platformvm/txs/executor/import_test.go | 18 +- .../txs/executor/proposal_tx_executor_test.go | 229 ++++--- .../txs/executor/reward_validator_test.go | 47 +- .../txs/executor/standard_tx_executor_test.go | 578 ++++++++---------- vms/platformvm/txs/txstest/backend.go | 81 --- vms/platformvm/txs/txstest/builder.go | 43 -- 11 files changed, 532 insertions(+), 742 deletions(-) delete mode 100644 vms/platformvm/txs/txstest/backend.go delete mode 100644 vms/platformvm/txs/txstest/builder.go diff --git a/vms/platformvm/txs/executor/advance_time_test.go b/vms/platformvm/txs/executor/advance_time_test.go index c10c76ec7bac..aadf84136615 100644 --- a/vms/platformvm/txs/executor/advance_time_test.go +++ b/vms/platformvm/txs/executor/advance_time_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "fmt" "testing" "time" @@ -23,8 +22,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) func newAdvanceTimeTx(t testing.TB, timestamp time.Time) (*txs.Tx, error) { @@ -50,14 +47,14 @@ func TestAdvanceTimeTxUpdatePrimaryNetworkStakers(t *testing.T) { pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeID := ids.GenerateTestNodeID() - addPendingValidatorTx, err := addPendingValidator( + addPendingValidatorTx := addPendingValidator( + t, env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) - require.NoError(err) tx, err := newAdvanceTimeTx(t, pendingValidatorStartTime) require.NoError(err) @@ -140,8 +137,7 @@ func TestAdvanceTimeTxTimestampTooLate(t *testing.T) { pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeID := ids.GenerateTestNodeID() - _, err := addPendingValidator(env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}) - require.NoError(err) + addPendingValidator(t, env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}) { tx, err := newAdvanceTimeTx(t, pendingValidatorStartTime.Add(1*time.Second)) @@ -378,19 +374,22 @@ func TestAdvanceTimeTxUpdateStakers(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) for _, staker := range test.stakers { - _, err := addPendingValidator( + addPendingValidator( + t, env, staker.startTime, staker.endTime, staker.nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) - require.NoError(err) } for _, staker := range test.subnetStakers { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: staker.nodeID, @@ -402,8 +401,6 @@ func TestAdvanceTimeTxUpdateStakers(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( tx.ID(), @@ -485,13 +482,16 @@ func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { subnetID := testSubnet1.ID() env.config.TrackedSubnets.Add(subnetID) + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + dummyHeight := uint64(1) // Add a subnet validator to the staker set subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, @@ -503,8 +503,6 @@ func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addSubnetValTx := tx.Unsigned.(*txs.AddSubnetValidatorTx) staker, err := state.NewCurrentStaker( @@ -524,7 +522,7 @@ func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { // Queue a staker that joins the staker set after the above validator leaves subnetVdr2NodeID := genesistest.DefaultNodeIDs[1] - utx, err = builder.NewAddSubnetValidatorTx( + tx, err = wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetVdr2NodeID, @@ -536,8 +534,6 @@ func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { }, ) require.NoError(err) - tx, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err = state.NewPendingStaker( tx.ID(), @@ -601,13 +597,16 @@ func TestTrackedSubnet(t *testing.T) { env.config.TrackedSubnets.Add(subnetID) } + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + // Add a subnet validator to the staker set subnetValidatorNodeID := genesistest.DefaultNodeIDs[0] subnetVdr1StartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Minute) subnetVdr1EndTime := genesistest.DefaultValidatorStartTime.Add(10 * defaultMinStakingDuration).Add(1 * time.Minute) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewAddSubnetValidatorTx( + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: subnetValidatorNodeID, @@ -619,8 +618,6 @@ func TestTrackedSubnet(t *testing.T) { }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( tx.ID(), @@ -676,14 +673,14 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMaxStakingDuration) nodeID := ids.GenerateTestNodeID() - _, err := addPendingValidator( + addPendingValidator( + t, env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}, ) - require.NoError(err) tx, err := newAdvanceTimeTx(t, pendingValidatorStartTime) require.NoError(err) @@ -709,6 +706,8 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) + wallet := newWallet(t, env, walletConfig{}) + // Test validator weight before delegation vdrWeight := env.config.Validators.GetWeight(constants.PrimaryNetworkID, nodeID) require.Equal(env.config.MinValidatorStake, vdrWeight) @@ -717,8 +716,7 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) - utx, err := builder.NewAddDelegatorTx( + addDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(pendingDelegatorStartTime.Unix()), @@ -727,12 +725,10 @@ func TestAdvanceTimeTxDelegatorStakerWeight(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, }, ) require.NoError(err) - addDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( addDelegatorTx.ID(), @@ -786,8 +782,7 @@ func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { pendingValidatorStartTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) pendingValidatorEndTime := pendingValidatorStartTime.Add(defaultMinStakingDuration) nodeID := ids.GenerateTestNodeID() - _, err := addPendingValidator(env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}) - require.NoError(err) + addPendingValidator(t, env, pendingValidatorStartTime, pendingValidatorEndTime, nodeID, []*secp256k1.PrivateKey{genesistest.DefaultFundedKeys[0]}) tx, err := newAdvanceTimeTx(t, pendingValidatorStartTime) require.NoError(err) @@ -813,6 +808,8 @@ func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) + wallet := newWallet(t, env, walletConfig{}) + // Test validator weight before delegation vdrWeight := env.config.Validators.GetWeight(constants.PrimaryNetworkID, nodeID) require.Equal(env.config.MinValidatorStake, vdrWeight) @@ -820,8 +817,7 @@ func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { // Add delegator pendingDelegatorStartTime := pendingValidatorStartTime.Add(1 * time.Second) pendingDelegatorEndTime := pendingDelegatorStartTime.Add(defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0], genesistest.DefaultFundedKeys[1], genesistest.DefaultFundedKeys[4]) - utx, err := builder.NewAddDelegatorTx( + addDelegatorTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(pendingDelegatorStartTime.Unix()), @@ -830,12 +826,10 @@ func TestAdvanceTimeTxDelegatorStakers(t *testing.T) { }, &secp256k1fx.OutputOwners{ Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, }, ) require.NoError(err) - addDelegatorTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( addDelegatorTx.ID(), @@ -935,14 +929,19 @@ func TestAdvanceTimeTxUnmarshal(t *testing.T) { } func addPendingValidator( + t testing.TB, env *environment, startTime time.Time, endTime time.Time, nodeID ids.NodeID, keys []*secp256k1.PrivateKey, -) (*txs.Tx, error) { - builder, signer := env.factory.NewWallet(keys...) - utx, err := builder.NewAddValidatorTx( +) *txs.Tx { + require := require.New(t) + + wallet := newWallet(t, env, walletConfig{ + keys: keys, + }) + addPendingValidatorTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), @@ -955,28 +954,18 @@ func addPendingValidator( }, reward.PercentDenominator, ) - if err != nil { - return nil, err - } - addPendingValidatorTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - if err != nil { - return nil, err - } + require.NoError(err) staker, err := state.NewPendingStaker( addPendingValidatorTx.ID(), addPendingValidatorTx.Unsigned.(*txs.AddValidatorTx), ) - if err != nil { - return nil, err - } + require.NoError(err) env.state.PutPendingValidator(staker) env.state.AddTx(addPendingValidatorTx, status.Committed) dummyHeight := uint64(1) env.state.SetHeight(dummyHeight) - if err := env.state.Commit(); err != nil { - return nil, err - } - return addPendingValidatorTx, nil + require.NoError(env.state.Commit()) + return addPendingValidatorTx } diff --git a/vms/platformvm/txs/executor/create_chain_test.go b/vms/platformvm/txs/executor/create_chain_test.go index d454cda30a78..61fead2677a7 100644 --- a/vms/platformvm/txs/executor/create_chain_test.go +++ b/vms/platformvm/txs/executor/create_chain_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "testing" "time" @@ -21,11 +20,8 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/txs" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/platformvm/utxo" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) // Ensure Execute fails when there are not enough control sigs @@ -35,17 +31,19 @@ func TestCreateChainTxInsufficientControlSigs(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[:2]...) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, constants.AVMID, nil, "chain name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Remove a signature tx.Creds[0].(*secp256k1fx.Credential).Sigs = tx.Creds[0].(*secp256k1fx.Credential).Sigs[1:] @@ -71,17 +69,19 @@ func TestCreateChainTxWrongControlSig(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, constants.AVMID, nil, "chain name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Generate new, random key to sign tx with key, err := secp256k1.NewPrivateKey() @@ -114,17 +114,19 @@ func TestCreateChainTxNoSuchSubnet(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, constants.AVMID, nil, "chain name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) tx.Unsigned.(*txs.CreateChainTx).SubnetID = ids.GenerateTestID() @@ -152,17 +154,19 @@ func TestCreateChainTxValid(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, constants.AVMID, nil, "chain name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) stateDiff, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -221,21 +225,22 @@ func TestCreateChainTxAP3FeeChange(t *testing.T) { env.state.SetTimestamp(test.time) // to duly set fee - cfg := *env.config + config := *env.config + config.StaticFeeConfig.CreateBlockchainTxFee = test.fee + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + config: &config, + subnetIDs: []ids.ID{subnetID}, + }) - cfg.StaticFeeConfig.CreateBlockchainTxFee = test.fee - factory := txstest.NewWalletFactory(env.ctx, &cfg, env.state) - builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, ids.GenerateTestID(), nil, "", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) stateDiff, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -261,17 +266,19 @@ func TestEtnaCreateChainTxInvalidWithManagedSubnet(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewCreateChainTx( - testSubnet1.ID(), + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueCreateChainTx( + subnetID, nil, constants.AVMID, nil, "chain name", ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) stateDiff, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -279,7 +286,7 @@ func TestEtnaCreateChainTxInvalidWithManagedSubnet(t *testing.T) { builderDiff, err := state.NewDiffOn(stateDiff) require.NoError(err) - stateDiff.SetSubnetManager(testSubnet1.ID(), ids.GenerateTestID(), []byte{'a', 'd', 'd', 'r', 'e', 's', 's'}) + stateDiff.SetSubnetManager(subnetID, ids.GenerateTestID(), []byte{'a', 'd', 'd', 'r', 'e', 's', 's'}) feeCalculator := state.PickFeeCalculator(env.config, builderDiff) executor := StandardTxExecutor{ diff --git a/vms/platformvm/txs/executor/create_subnet_test.go b/vms/platformvm/txs/executor/create_subnet_test.go index ad51fdc0b2b0..0290d1811401 100644 --- a/vms/platformvm/txs/executor/create_subnet_test.go +++ b/vms/platformvm/txs/executor/create_subnet_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "testing" "time" @@ -16,11 +15,8 @@ import ( "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/platformvm/utxo" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) func TestCreateSubnetTxAP3FeeChange(t *testing.T) { @@ -66,16 +62,16 @@ func TestCreateSubnetTxAP3FeeChange(t *testing.T) { addrs.Add(key.Address()) } - cfg := *env.config - cfg.StaticFeeConfig.CreateSubnetTxFee = test.fee - factory := txstest.NewWalletFactory(env.ctx, &cfg, env.state) - builder, signer := factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewCreateSubnetTx( + config := *env.config + config.StaticFeeConfig.CreateSubnetTxFee = test.fee + wallet := newWallet(t, env, walletConfig{ + config: &config, + }) + + tx, err := wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{}, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) stateDiff, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) diff --git a/vms/platformvm/txs/executor/export_test.go b/vms/platformvm/txs/executor/export_test.go index a6f292c92c33..34b1e8046454 100644 --- a/vms/platformvm/txs/executor/export_test.go +++ b/vms/platformvm/txs/executor/export_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "testing" "time" @@ -12,13 +11,10 @@ import ( "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/upgrade/upgradetest" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) func TestNewExportTx(t *testing.T) { @@ -26,53 +22,43 @@ func TestNewExportTx(t *testing.T) { env.ctx.Lock.Lock() defer env.ctx.Lock.Unlock() - type test struct { + tests := []struct { description string destinationChainID ids.ID - sourceKeys []*secp256k1.PrivateKey timestamp time.Time - } - - sourceKey := genesistest.DefaultFundedKeys[0] - - tests := []test{ + }{ { description: "P->X export", destinationChainID: env.ctx.XChainID, - sourceKeys: []*secp256k1.PrivateKey{sourceKey}, timestamp: genesistest.DefaultValidatorStartTime, }, { description: "P->C export", destinationChainID: env.ctx.CChainID, - sourceKeys: []*secp256k1.PrivateKey{sourceKey}, timestamp: env.config.UpgradeConfig.ApricotPhase5Time, }, } - to := ids.GenerateTestShortID() for _, tt := range tests { t.Run(tt.description, func(t *testing.T) { require := require.New(t) - builder, signer := env.factory.NewWallet(tt.sourceKeys...) - utx, err := builder.NewExportTx( + wallet := newWallet(t, env, walletConfig{}) + + tx, err := wallet.IssueExportTx( tt.destinationChainID, []*avax.TransferableOutput{{ Asset: avax.Asset{ID: env.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ Amt: genesistest.DefaultInitialBalance - defaultTxFee, OutputOwners: secp256k1fx.OutputOwners{ - Locktime: 0, Threshold: 1, - Addrs: []ids.ShortID{to}, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, }, }, }}, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) stateDiff, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) diff --git a/vms/platformvm/txs/executor/helpers_test.go b/vms/platformvm/txs/executor/helpers_test.go index e740178fbe48..595f4cc2ae62 100644 --- a/vms/platformvm/txs/executor/helpers_test.go +++ b/vms/platformvm/txs/executor/helpers_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "math" "testing" "time" @@ -25,6 +24,7 @@ import ( "github.com/ava-labs/avalanchego/upgrade/upgradetest" "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" @@ -40,9 +40,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" "github.com/ava-labs/avalanchego/vms/platformvm/utxo" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" + "github.com/ava-labs/avalanchego/wallet/chain/p/wallet" ) const ( @@ -57,8 +55,7 @@ const ( var ( lastAcceptedID = ids.GenerateTestID() - testSubnet1 *txs.Tx - testSubnet1ControlKeys = genesistest.DefaultFundedKeys[0:3] + testSubnet1 *txs.Tx ) type mutableSharedMemory struct { @@ -77,7 +74,6 @@ type environment struct { states map[ids.ID]state.Chain uptimes uptime.Manager utxosHandler utxo.Verifier - factory *txstest.WalletFactory backend Backend } @@ -124,8 +120,6 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { uptimes := uptime.NewManager(baseState, clk) utxosVerifier := utxo.NewVerifier(ctx, clk, fx) - factory := txstest.NewWalletFactory(ctx, config, baseState) - backend := Backend{ Config: config, Ctx: ctx, @@ -149,7 +143,6 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { states: make(map[ids.ID]state.Chain), uptimes: uptimes, utxosHandler: utxosVerifier, - factory: factory, backend: backend, } @@ -182,11 +175,40 @@ func newEnvironment(t *testing.T, f upgradetest.Fork) *environment { return env } +type walletConfig struct { + config *config.Config + keys []*secp256k1.PrivateKey + subnetIDs []ids.ID + chainIDs []ids.ID +} + +func newWallet(t testing.TB, e *environment, c walletConfig) wallet.Wallet { + if c.config == nil { + c.config = e.config + } + if len(c.keys) == 0 { + c.keys = genesistest.DefaultFundedKeys + } + return txstest.NewWallet( + t, + e.ctx, + c.config, + e.state, + secp256k1fx.NewKeychain(c.keys...), + c.subnetIDs, + c.chainIDs, + ) +} + func addSubnet(t *testing.T, env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewCreateSubnetTx( + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + + var err error + testSubnet1, err = wallet.IssueCreateSubnetTx( &secp256k1fx.OutputOwners{ Threshold: 2, Addrs: []ids.ShortID{ @@ -195,14 +217,8 @@ func addSubnet(t *testing.T, env *environment) { genesistest.DefaultFundedKeys[2].Address(), }, }, - common.WithChangeOwner(&secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{genesistest.DefaultFundedKeys[0].Address()}, - }), ) require.NoError(err) - testSubnet1, err = walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) stateDiff, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) diff --git a/vms/platformvm/txs/executor/import_test.go b/vms/platformvm/txs/executor/import_test.go index 6cc5c8a0cb38..d3c48f17e186 100644 --- a/vms/platformvm/txs/executor/import_test.go +++ b/vms/platformvm/txs/executor/import_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "math/rand" "testing" "time" @@ -21,8 +20,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/chain/p/builder" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) var fundedSharedMemoryCalls byte @@ -34,7 +31,6 @@ func TestNewImportTx(t *testing.T) { description string sourceChainID ids.ID sharedMemory atomic.SharedMemory - sourceKeys []*secp256k1.PrivateKey timestamp time.Time expectedErr error } @@ -59,7 +55,6 @@ func TestNewImportTx(t *testing.T) { }, randSrc, ), - sourceKeys: []*secp256k1.PrivateKey{sourceKey}, expectedErr: builder.ErrInsufficientFunds, }, { @@ -75,7 +70,6 @@ func TestNewImportTx(t *testing.T) { }, randSrc, ), - sourceKeys: []*secp256k1.PrivateKey{sourceKey}, expectedErr: nil, }, { @@ -91,7 +85,6 @@ func TestNewImportTx(t *testing.T) { }, randSrc, ), - sourceKeys: []*secp256k1.PrivateKey{sourceKey}, timestamp: env.config.UpgradeConfig.ApricotPhase5Time, expectedErr: nil, }, @@ -109,7 +102,6 @@ func TestNewImportTx(t *testing.T) { }, randSrc, ), - sourceKeys: []*secp256k1.PrivateKey{sourceKey}, timestamp: env.config.UpgradeConfig.ApricotPhase5Time, expectedErr: nil, }, @@ -125,8 +117,12 @@ func TestNewImportTx(t *testing.T) { env.msm.SharedMemory = tt.sharedMemory - builder, signer := env.factory.NewWallet(tt.sourceKeys...) - utx, err := builder.NewImportTx( + wallet := newWallet(t, env, walletConfig{ + keys: []*secp256k1.PrivateKey{sourceKey}, + chainIDs: []ids.ID{tt.sourceChainID}, + }) + + tx, err := wallet.IssueImportTx( tt.sourceChainID, to, ) @@ -134,8 +130,6 @@ func TestNewImportTx(t *testing.T) { if tt.expectedErr != nil { return } - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) unsignedTx := tx.Unsigned.(*txs.ImportTx) require.NotEmpty(unsignedTx.ImportedInputs) diff --git a/vms/platformvm/txs/executor/proposal_tx_executor_test.go b/vms/platformvm/txs/executor/proposal_tx_executor_test.go index e7d79ca58eba..70687a965836 100644 --- a/vms/platformvm/txs/executor/proposal_tx_executor_test.go +++ b/vms/platformvm/txs/executor/proposal_tx_executor_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "math" "testing" "time" @@ -22,13 +21,14 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) func TestProposalTxExecuteAddDelegator(t *testing.T) { dummyHeight := uint64(1) - rewardAddress := genesistest.DefaultFundedKeys[0].Address() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } nodeID := genesistest.DefaultNodeIDs[0] newValidatorID := ids.GenerateTestNodeID() @@ -40,23 +40,21 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { addMinStakeValidator := func(env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: newValidatorID, Start: newValidatorStartTime, End: newValidatorEndTime, Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{rewardAddress}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addValTx := tx.Unsigned.(*txs.AddValidatorTx) staker, err := state.NewCurrentStaker( @@ -78,23 +76,21 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { addMaxStakeValidator := func(env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: newValidatorID, Start: newValidatorStartTime, End: newValidatorEndTime, Wght: env.config.MaxValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{rewardAddress}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addValTx := tx.Unsigned.(*txs.AddValidatorTx) staker, err := state.NewCurrentStaker( @@ -246,22 +242,20 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { env := newEnvironment(t, upgradetest.ApricotPhase5) env.config.UpgradeConfig.ApricotPhase3Time = tt.AP3Time - builder, signer := env.factory.NewWallet(tt.feeKeys...) - utx, err := builder.NewAddDelegatorTx( + wallet := newWallet(t, env, walletConfig{ + keys: tt.feeKeys, + }) + + tx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: tt.nodeID, Start: tt.startTime, End: tt.endTime, Wght: tt.stakeAmount, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{rewardAddress}, - }, + rewardsOwner, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) if tt.setup != nil { tt.setup(env) @@ -294,12 +288,15 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { defer env.ctx.Lock.Unlock() nodeID := genesistest.DefaultNodeIDs[0] + subnetID := testSubnet1.ID() { // Case: Proposed validator currently validating primary network // but stops validating subnet after stops validating primary network // (note that keys[0] is a genesis validator) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -307,12 +304,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix + 1, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -337,8 +332,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { // and proposed subnet validation period is subset of // primary network validation period // (note that keys[0] is a genesis validator) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -346,12 +343,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -376,8 +371,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { dsStartTime := genesistest.DefaultValidatorStartTime.Add(10 * time.Second) dsEndTime := dsStartTime.Add(5 * defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + addDSTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()), @@ -391,13 +388,13 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { reward.PercentDenominator, ) require.NoError(err) - addDSTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) { // Case: Proposed validator isn't in pending or current validator sets - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: pendingDSValidatorID, @@ -405,12 +402,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: uint64(dsEndTime.Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -450,8 +445,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { { // Case: Proposed validator is pending validator of primary network // but starts validating subnet before primary network - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: pendingDSValidatorID, @@ -459,12 +456,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: uint64(dsEndTime.Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -487,8 +482,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { { // Case: Proposed validator is pending validator of primary network // but stops validating subnet after primary network - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: pendingDSValidatorID, @@ -496,12 +493,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: uint64(dsEndTime.Unix()) + 1, // stop validating subnet after stopping validating primary network Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -524,8 +519,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { { // Case: Proposed validator is pending validator of primary network and // period validating subnet is subset of time validating primary network - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: pendingDSValidatorID, @@ -533,12 +530,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: uint64(dsEndTime.Unix()), // same end time as for primary network Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -563,8 +558,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { env.state.SetTimestamp(newTimestamp) { - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -572,12 +569,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: uint64(newTimestamp.Add(defaultMinStakingDuration).Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -602,8 +597,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { // Case: Proposed validator already validating the subnet // First, add validator as validator of subnet - builder, signer = env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - uSubnetTx, err := builder.NewAddSubnetValidatorTx( + wallet = newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + subnetTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -611,12 +608,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - subnetTx, err := walletsigner.SignUnsigned(context.Background(), signer, uSubnetTx) - require.NoError(err) addSubnetValTx := subnetTx.Unsigned.(*txs.AddSubnetValidatorTx) staker, err = state.NewCurrentStaker( @@ -634,8 +629,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { { // Node with ID nodeIDKey.Address() now validating subnet with ID testSubnet1.ID - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet = newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + duplicateSubnetTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -643,12 +640,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - duplicateSubnetTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -674,8 +669,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { { // Case: Too few signatures - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet = newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -683,12 +680,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: uint64(genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration).Unix()) + 1, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Remove a signature addSubnetValidatorTx := tx.Unsigned.(*txs.AddSubnetValidatorTx) @@ -717,8 +712,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { { // Case: Control Signature from invalid key (keys[3] is not a control key) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], genesistest.DefaultFundedKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet = newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -726,12 +723,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: uint64(genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration).Unix()) + 1, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Replace a valid signature with one from keys[3] sig, err := genesistest.DefaultFundedKeys[3].SignHash(hashing.ComputeHash256(tx.Unsigned.Bytes())) @@ -759,8 +754,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { { // Case: Proposed validator in pending validator set for subnet // First, add validator to pending validator set of subnet - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet = newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -768,12 +765,10 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { End: uint64(genesistest.DefaultValidatorStartTime.Add(defaultMinStakingDuration).Unix()) + 1, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addSubnetValTx := subnetTx.Unsigned.(*txs.AddSubnetValidatorTx) staker, err = state.NewCurrentStaker( @@ -816,26 +811,25 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { nodeID := ids.GenerateTestNodeID() chainTime := env.state.GetTimestamp() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } { // Case: Validator's start time too early - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(chainTime.Unix()), End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -859,23 +853,18 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { nodeID := genesistest.DefaultNodeIDs[0] // Case: Validator already validating primary network - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: genesistest.DefaultValidatorStartTimeUnix + 1, End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onCommitState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -898,23 +887,18 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { { // Case: Validator in pending validator set of primary network startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(startTime.Add(defaultMinStakingDuration).Unix()), Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addValTx := tx.Unsigned.(*txs.AddValidatorTx) staker, err := state.NewCurrentStaker( @@ -951,23 +935,20 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { { // Case: Validator doesn't have enough tokens to cover stake amount - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: ids.GenerateTestNodeID(), Start: genesistest.DefaultValidatorStartTimeUnix + 1, End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Remove all UTXOs owned by preFundedKeys[0] utxoIDs, err := env.state.UTXOIDs(genesistest.DefaultFundedKeys[0].Address().Bytes(), ids.Empty, math.MaxInt32) diff --git a/vms/platformvm/txs/executor/reward_validator_test.go b/vms/platformvm/txs/executor/reward_validator_test.go index 27dd9d304937..55f210ebc95f 100644 --- a/vms/platformvm/txs/executor/reward_validator_test.go +++ b/vms/platformvm/txs/executor/reward_validator_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "testing" "time" @@ -24,8 +23,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) func newRewardValidatorTx(t testing.TB, txID ids.ID) (*txs.Tx, error) { @@ -244,6 +241,8 @@ func TestRewardDelegatorTxExecuteOnCommitPreDelegateeDeferral(t *testing.T) { env := newEnvironment(t, upgradetest.ApricotPhase5) dummyHeight := uint64(1) + wallet := newWallet(t, env, walletConfig{}) + vdrRewardAddress := ids.GenerateTestShortID() delRewardAddress := ids.GenerateTestShortID() @@ -251,8 +250,7 @@ func TestRewardDelegatorTxExecuteOnCommitPreDelegateeDeferral(t *testing.T) { vdrEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(2 * defaultMinStakingDuration).Unix()) vdrNodeID := ids.GenerateTestNodeID() - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uVdrTx, err := builder.NewAddValidatorTx( + vdrTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: vdrNodeID, Start: vdrStartTime, @@ -266,13 +264,11 @@ func TestRewardDelegatorTxExecuteOnCommitPreDelegateeDeferral(t *testing.T) { reward.PercentDenominator/4, ) require.NoError(err) - vdrTx, err := walletsigner.SignUnsigned(context.Background(), signer, uVdrTx) - require.NoError(err) delStartTime := vdrStartTime delEndTime := vdrEndTime - uDelTx, err := builder.NewAddDelegatorTx( + delTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: vdrNodeID, Start: delStartTime, @@ -285,8 +281,6 @@ func TestRewardDelegatorTxExecuteOnCommitPreDelegateeDeferral(t *testing.T) { }, ) require.NoError(err) - delTx, err := walletsigner.SignUnsigned(context.Background(), signer, uDelTx) - require.NoError(err) addValTx := vdrTx.Unsigned.(*txs.AddValidatorTx) vdrStaker, err := state.NewCurrentStaker( @@ -378,6 +372,8 @@ func TestRewardDelegatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { env := newEnvironment(t, upgradetest.Cortina) dummyHeight := uint64(1) + wallet := newWallet(t, env, walletConfig{}) + vdrRewardAddress := ids.GenerateTestShortID() delRewardAddress := ids.GenerateTestShortID() @@ -385,8 +381,7 @@ func TestRewardDelegatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { vdrEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(2 * defaultMinStakingDuration).Unix()) vdrNodeID := ids.GenerateTestNodeID() - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uVdrTx, err := builder.NewAddValidatorTx( + vdrTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: vdrNodeID, Start: vdrStartTime, @@ -400,13 +395,11 @@ func TestRewardDelegatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { reward.PercentDenominator/4, ) require.NoError(err) - vdrTx, err := walletsigner.SignUnsigned(context.Background(), signer, uVdrTx) - require.NoError(err) delStartTime := vdrStartTime delEndTime := vdrEndTime - uDelTx, err := builder.NewAddDelegatorTx( + delTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: vdrNodeID, Start: delStartTime, @@ -419,8 +412,6 @@ func TestRewardDelegatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { }, ) require.NoError(err) - delTx, err := walletsigner.SignUnsigned(context.Background(), signer, uDelTx) - require.NoError(err) addValTx := vdrTx.Unsigned.(*txs.AddValidatorTx) vdrRewardAmt := uint64(2000000) @@ -608,6 +599,8 @@ func TestRewardDelegatorTxAndValidatorTxExecuteOnCommitPostDelegateeDeferral(t * env := newEnvironment(t, upgradetest.Cortina) dummyHeight := uint64(1) + wallet := newWallet(t, env, walletConfig{}) + vdrRewardAddress := ids.GenerateTestShortID() delRewardAddress := ids.GenerateTestShortID() @@ -615,8 +608,7 @@ func TestRewardDelegatorTxAndValidatorTxExecuteOnCommitPostDelegateeDeferral(t * vdrEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(2 * defaultMinStakingDuration).Unix()) vdrNodeID := ids.GenerateTestNodeID() - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uVdrTx, err := builder.NewAddValidatorTx( + vdrTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: vdrNodeID, Start: vdrStartTime, @@ -630,13 +622,11 @@ func TestRewardDelegatorTxAndValidatorTxExecuteOnCommitPostDelegateeDeferral(t * reward.PercentDenominator/4, ) require.NoError(err) - vdrTx, err := walletsigner.SignUnsigned(context.Background(), signer, uVdrTx) - require.NoError(err) delStartTime := vdrStartTime delEndTime := vdrEndTime - uDelTx, err := builder.NewAddDelegatorTx( + delTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: vdrNodeID, Start: delStartTime, @@ -649,8 +639,6 @@ func TestRewardDelegatorTxAndValidatorTxExecuteOnCommitPostDelegateeDeferral(t * }, ) require.NoError(err) - delTx, err := walletsigner.SignUnsigned(context.Background(), signer, uDelTx) - require.NoError(err) addValTx := vdrTx.Unsigned.(*txs.AddValidatorTx) vdrRewardAmt := uint64(2000000) @@ -781,6 +769,8 @@ func TestRewardDelegatorTxExecuteOnAbort(t *testing.T) { env := newEnvironment(t, upgradetest.ApricotPhase5) dummyHeight := uint64(1) + wallet := newWallet(t, env, walletConfig{}) + initialSupply, err := env.state.GetCurrentSupply(constants.PrimaryNetworkID) require.NoError(err) @@ -791,8 +781,7 @@ func TestRewardDelegatorTxExecuteOnAbort(t *testing.T) { vdrEndTime := uint64(genesistest.DefaultValidatorStartTime.Add(2 * defaultMinStakingDuration).Unix()) vdrNodeID := ids.GenerateTestNodeID() - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - uVdrTx, err := builder.NewAddValidatorTx( + vdrTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: vdrNodeID, Start: vdrStartTime, @@ -806,13 +795,11 @@ func TestRewardDelegatorTxExecuteOnAbort(t *testing.T) { reward.PercentDenominator/4, ) require.NoError(err) - vdrTx, err := walletsigner.SignUnsigned(context.Background(), signer, uVdrTx) - require.NoError(err) delStartTime := vdrStartTime delEndTime := vdrEndTime - uDelTx, err := builder.NewAddDelegatorTx( + delTx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: vdrNodeID, Start: delStartTime, @@ -825,8 +812,6 @@ func TestRewardDelegatorTxExecuteOnAbort(t *testing.T) { }, ) require.NoError(err) - delTx, err := walletsigner.SignUnsigned(context.Background(), signer, uDelTx) - require.NoError(err) addValTx := vdrTx.Unsigned.(*txs.AddValidatorTx) vdrStaker, err := state.NewCurrentStaker( diff --git a/vms/platformvm/txs/executor/standard_tx_executor_test.go b/vms/platformvm/txs/executor/standard_tx_executor_test.go index d0652e6bd419..2b01148a7f76 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor_test.go +++ b/vms/platformvm/txs/executor/standard_tx_executor_test.go @@ -4,7 +4,6 @@ package executor import ( - "context" "errors" "math" "math/rand" @@ -37,8 +36,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/utxo/utxomock" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - walletsigner "github.com/ava-labs/avalanchego/wallet/chain/p/signer" ) // This tests that the math performed during TransformSubnetTx execution can @@ -57,28 +54,25 @@ func TestStandardTxExecutorAddValidatorTxEmptyID(t *testing.T) { startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) tests := []struct { - banffTime time.Time - expectedError error + banffTime time.Time }{ { // Case: Before banff - banffTime: chainTime.Add(1), - expectedError: errEmptyNodeID, + banffTime: chainTime.Add(1), }, { // Case: At banff - banffTime: chainTime, - expectedError: errEmptyNodeID, + banffTime: chainTime, }, { // Case: After banff - banffTime: chainTime.Add(-1), - expectedError: errEmptyNodeID, + banffTime: chainTime.Add(-1), }, } for _, test := range tests { // Case: Empty validator node ID after banff env.config.UpgradeConfig.BanffTime = test.banffTime - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: ids.EmptyNodeID, Start: uint64(startTime.Unix()), @@ -92,8 +86,6 @@ func TestStandardTxExecutorAddValidatorTxEmptyID(t *testing.T) { reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) stateDiff, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -106,13 +98,16 @@ func TestStandardTxExecutorAddValidatorTxEmptyID(t *testing.T) { Tx: tx, } err = tx.Unsigned.Visit(&executor) - require.ErrorIs(err, test.expectedError) + require.ErrorIs(err, errEmptyNodeID) } } func TestStandardTxExecutorAddDelegator(t *testing.T) { dummyHeight := uint64(1) - rewardAddress := genesistest.DefaultFundedKeys[0].Address() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } nodeID := genesistest.DefaultNodeIDs[0] newValidatorID := ids.GenerateTestNodeID() @@ -124,23 +119,20 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { addMinStakeValidator := func(env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: newValidatorID, Start: uint64(newValidatorStartTime.Unix()), End: uint64(newValidatorEndTime.Unix()), Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{rewardAddress}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addValTx := tx.Unsigned.(*txs.AddValidatorTx) staker, err := state.NewCurrentStaker( @@ -162,23 +154,20 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { addMaxStakeValidator := func(env *environment) { require := require.New(t) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: newValidatorID, Start: uint64(newValidatorStartTime.Unix()), End: uint64(newValidatorEndTime.Unix()), Wght: env.config.MaxValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{rewardAddress}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addValTx := tx.Unsigned.(*txs.AddValidatorTx) staker, err := state.NewCurrentStaker( @@ -330,22 +319,19 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { env := newEnvironment(t, upgradetest.ApricotPhase5) env.config.UpgradeConfig.ApricotPhase3Time = tt.AP3Time - builder, signer := env.factory.NewWallet(tt.feeKeys...) - utx, err := builder.NewAddDelegatorTx( + wallet := newWallet(t, env, walletConfig{ + keys: tt.feeKeys, + }) + tx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: tt.nodeID, Start: uint64(tt.startTime.Unix()), End: uint64(tt.endTime.Unix()), Wght: tt.stakeAmount, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{rewardAddress}, - }, + rewardsOwner, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) if tt.setup != nil { tt.setup(env) @@ -376,14 +362,18 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { defer env.ctx.Lock.Unlock() nodeID := genesistest.DefaultNodeIDs[0] + subnetID := testSubnet1.ID() { // Case: Proposed validator currently validating primary network // but stops validating subnet after stops validating primary network // (note that keys[0] is a genesis validator) startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -391,12 +381,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix + 1, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -417,8 +405,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { // and proposed subnet validation period is subset of // primary network validation period // (note that keys[0] is a genesis validator) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -426,12 +416,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -452,8 +440,8 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { dsStartTime := genesistest.DefaultValidatorStartTime.Add(10 * time.Second) dsEndTime := dsStartTime.Add(5 * defaultMinStakingDuration) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + addDSTx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: pendingDSValidatorID, Start: uint64(dsStartTime.Unix()), @@ -467,13 +455,13 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { reward.PercentDenominator, ) require.NoError(err) - addDSTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) { // Case: Proposed validator isn't in pending or current validator sets - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: pendingDSValidatorID, @@ -481,12 +469,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(dsEndTime.Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -522,8 +508,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Proposed validator is pending validator of primary network // but starts validating subnet before primary network - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: pendingDSValidatorID, @@ -531,12 +519,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(dsEndTime.Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -555,8 +541,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Proposed validator is pending validator of primary network // but stops validating subnet after primary network - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: pendingDSValidatorID, @@ -564,12 +552,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(dsEndTime.Unix()) + 1, // stop validating subnet after stopping validating primary network Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -588,8 +574,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Proposed validator is pending validator of primary network and // period validating subnet is subset of time validating primary network - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: pendingDSValidatorID, @@ -597,12 +585,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(dsEndTime.Unix()), // same end time as for primary network Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -623,8 +609,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { env.state.SetTimestamp(newTimestamp) { - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -632,12 +620,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(newTimestamp.Add(defaultMinStakingDuration).Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -658,8 +644,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { // Case: Proposed validator already validating the subnet // First, add validator as validator of subnet - builder, signer = env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - uSubnetTx, err := builder.NewAddSubnetValidatorTx( + wallet = newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + subnetTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -667,12 +655,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - subnetTx, err := walletsigner.SignUnsigned(context.Background(), signer, uSubnetTx) - require.NoError(err) addSubnetValTx := subnetTx.Unsigned.(*txs.AddSubnetValidatorTx) staker, err = state.NewCurrentStaker( @@ -691,8 +677,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Node with ID nodeIDKey.Address() now validating subnet with ID testSubnet1.ID startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -700,12 +688,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -728,8 +714,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Duplicate signatures startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1], testSubnet1ControlKeys[2]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -737,12 +725,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(startTime.Add(defaultMinStakingDuration).Unix()) + 1, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Duplicate a signature addSubnetValidatorTx := tx.Unsigned.(*txs.AddSubnetValidatorTx) @@ -768,8 +754,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Too few signatures startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[2]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -777,12 +765,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(startTime.Add(defaultMinStakingDuration).Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Remove a signature addSubnetValidatorTx := tx.Unsigned.(*txs.AddSubnetValidatorTx) @@ -808,8 +794,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { { // Case: Control Signature from invalid key (keys[3] is not a control key) startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], genesistest.DefaultFundedKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -817,12 +805,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(startTime.Add(defaultMinStakingDuration).Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Replace a valid signature with one from keys[3] sig, err := genesistest.DefaultFundedKeys[3].SignHash(hashing.ComputeHash256(tx.Unsigned.Bytes())) @@ -847,8 +833,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { // Case: Proposed validator in pending validator set for subnet // First, add validator to pending validator set of subnet startTime := genesistest.DefaultValidatorStartTime.Add(time.Second) - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -856,12 +844,10 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { End: uint64(startTime.Add(defaultMinStakingDuration).Unix()) + 1, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addSubnetValTx := subnetTx.Unsigned.(*txs.AddSubnetValidatorTx) staker, err = state.NewCurrentStaker( @@ -899,9 +885,12 @@ func TestEtnaStandardTxExecutorAddSubnetValidator(t *testing.T) { defer env.ctx.Lock.Unlock() nodeID := genesistest.DefaultNodeIDs[0] + subnetID := testSubnet1.ID() - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -909,17 +898,15 @@ func TestEtnaStandardTxExecutorAddSubnetValidator(t *testing.T) { End: genesistest.DefaultValidatorEndTimeUnix, Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) - onAcceptState.SetSubnetManager(testSubnet1.ID(), ids.GenerateTestID(), []byte{'a', 'd', 'd', 'r', 'e', 's', 's'}) + onAcceptState.SetSubnetManager(subnetID, ids.GenerateTestID(), []byte{'a', 'd', 'd', 'r', 'e', 's', 's'}) executor := StandardTxExecutor{ Backend: &env.backend, @@ -937,26 +924,25 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { defer env.ctx.Lock.Unlock() nodeID := ids.GenerateTestNodeID() + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } { // Case: Validator's start time too early - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: genesistest.DefaultValidatorStartTimeUnix - 1, End: genesistest.DefaultValidatorEndTimeUnix, Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) @@ -974,24 +960,20 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { { // Case: Validator in current validator set of primary network + wallet := newWallet(t, env, walletConfig{}) + startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(startTime.Add(defaultMinStakingDuration).Unix()), Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) addValTx := tx.Unsigned.(*txs.AddValidatorTx) staker, err := state.NewCurrentStaker( @@ -1021,24 +1003,20 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { { // Case: Validator in pending validator set of primary network + wallet := newWallet(t, env, walletConfig{}) + startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(startTime.Add(defaultMinStakingDuration).Unix()), Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) staker, err := state.NewPendingStaker( tx.ID(), @@ -1065,24 +1043,22 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { { // Case: Validator doesn't have enough tokens to cover stake amount + wallet := newWallet(t, env, walletConfig{ + keys: genesistest.DefaultFundedKeys[:1], + }) + startTime := genesistest.DefaultValidatorStartTime.Add(1 * time.Second) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys[0]) - utx, err := builder.NewAddValidatorTx( + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: uint64(startTime.Unix()), End: uint64(startTime.Add(defaultMinStakingDuration).Unix()), Wght: env.config.MinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(err) // Remove all UTXOs owned by preFundedKeys[0] utxoIDs, err := env.state.UTXOIDs(genesistest.DefaultFundedKeys[0].Address().Bytes(), ids.Empty, math.MaxInt32) @@ -1111,37 +1087,37 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { func TestDurangoDisabledTransactions(t *testing.T) { type test struct { name string - buildTx func(*environment) *txs.Tx + buildTx func(t *testing.T, env *environment) *txs.Tx expectedErr error } + rewardsOwner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, + } + tests := []test{ { name: "AddValidatorTx", - buildTx: func(env *environment) *txs.Tx { + buildTx: func(t *testing.T, env *environment) *txs.Tx { var ( nodeID = ids.GenerateTestNodeID() chainTime = env.state.GetTimestamp() endTime = chainTime.Add(defaultMaxStakingDuration) ) - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewAddValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueAddValidatorTx( &txs.Validator{ NodeID: nodeID, Start: 0, End: uint64(endTime.Unix()), Wght: defaultMinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + rewardsOwner, reward.PercentDenominator, ) require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) return tx }, @@ -1149,10 +1125,12 @@ func TestDurangoDisabledTransactions(t *testing.T) { }, { name: "AddDelegatorTx", - buildTx: func(env *environment) *txs.Tx { + buildTx: func(t *testing.T, env *environment) *txs.Tx { + require := require.New(t) + var primaryValidator *state.Staker it, err := env.state.GetCurrentStakerIterator() - require.NoError(t, err) + require.NoError(err) for it.Next() { staker := it.Value() if staker.Priority != txs.PrimaryNetworkValidatorCurrentPriority { @@ -1163,22 +1141,17 @@ func TestDurangoDisabledTransactions(t *testing.T) { } it.Release() - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewAddDelegatorTx( + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueAddDelegatorTx( &txs.Validator{ NodeID: primaryValidator.NodeID, Start: 0, End: uint64(primaryValidator.EndTime.Unix()), Wght: defaultMinValidatorStake, }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + rewardsOwner, ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) return tx }, @@ -1197,7 +1170,7 @@ func TestDurangoDisabledTransactions(t *testing.T) { onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) require.NoError(err) - tx := tt.buildTx(env) + tx := tt.buildTx(t, env) feeCalculator := state.PickFeeCalculator(env.config, onAcceptState) err = tx.Unsigned.Visit(&StandardTxExecutor{ @@ -1215,16 +1188,23 @@ func TestDurangoDisabledTransactions(t *testing.T) { func TestDurangoMemoField(t *testing.T) { type test struct { name string - setupTest func(env *environment, memoField []byte) (*txs.Tx, state.Diff) + setupTest func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) + } + + owners := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ids.GenerateTestShortID()}, } tests := []test{ { name: "AddSubnetValidatorTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + var primaryValidator *state.Staker it, err := env.state.GetCurrentStakerIterator() - require.NoError(t, err) + require.NoError(err) for it.Next() { staker := it.Value() if staker.Priority != txs.PrimaryNetworkValidatorCurrentPriority { @@ -1235,8 +1215,11 @@ func TestDurangoMemoField(t *testing.T) { } it.Release() - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewAddSubnetValidatorTx( + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + tx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: primaryValidator.NodeID, @@ -1244,67 +1227,63 @@ func TestDurangoMemoField(t *testing.T) { End: uint64(primaryValidator.EndTime.Unix()), Wght: defaultMinValidatorStake, }, - Subnet: testSubnet1.TxID, + Subnet: subnetID, }, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) + require.NoError(err) return tx, onAcceptState }, }, { name: "CreateChainTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewCreateChainTx( - testSubnet1.TxID, + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueCreateChainTx( + subnetID, []byte{}, ids.GenerateTestID(), []ids.ID{}, "aaa", common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "CreateSubnetTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewCreateSubnetTx( - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueCreateSubnetTx( + owners, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "ImportTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - // Skip shared memory checks - env.backend.Bootstrapped.Set(false) + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) var ( sourceChain = env.ctx.XChainID @@ -1324,61 +1303,54 @@ func TestDurangoMemoField(t *testing.T) { ) env.msm.SharedMemory = sharedMemory - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewImportTx( + wallet := newWallet(t, env, walletConfig{ + chainIDs: []ids.ID{sourceChain}, + }) + + tx, err := wallet.IssueImportTx( sourceChain, - &secp256k1fx.OutputOwners{ - Locktime: 0, - Threshold: 1, - Addrs: []ids.ShortID{sourceKey.Address()}, - }, + owners, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "ExportTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewExportTx( + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueExportTx( env.ctx.XChainID, []*avax.TransferableOutput{{ Asset: avax.Asset{ID: env.ctx.AVAXAssetID}, Out: &secp256k1fx.TransferOutput{ - Amt: units.Avax, - OutputOwners: secp256k1fx.OutputOwners{ - Locktime: 0, - Threshold: 1, - Addrs: []ids.ShortID{ids.GenerateTestShortID()}, - }, + Amt: units.Avax, + OutputOwners: *owners, }, }}, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "RemoveSubnetValidatorTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + var primaryValidator *state.Staker it, err := env.state.GetCurrentStakerIterator() - require.NoError(t, err) + require.NoError(err) for it.Next() { staker := it.Value() if staker.Priority != txs.PrimaryNetworkValidatorCurrentPriority { @@ -1390,8 +1362,12 @@ func TestDurangoMemoField(t *testing.T) { it.Release() endTime := primaryValidator.EndTime - builder, signer := env.factory.NewWallet(testSubnet1ControlKeys[0], testSubnet1ControlKeys[1]) - utx, err := builder.NewAddSubnetValidatorTx( + + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + subnetValTx, err := wallet.IssueAddSubnetValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: primaryValidator.NodeID, @@ -1399,43 +1375,43 @@ func TestDurangoMemoField(t *testing.T) { End: uint64(endTime.Unix()), Wght: genesistest.DefaultValidatorWeight, }, - Subnet: testSubnet1.ID(), + Subnet: subnetID, }, ) - require.NoError(t, err) - subnetValTx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) + require.NoError(err) feeCalculator := state.PickFeeCalculator(env.config, onAcceptState) - require.NoError(t, subnetValTx.Unsigned.Visit(&StandardTxExecutor{ + require.NoError(subnetValTx.Unsigned.Visit(&StandardTxExecutor{ Backend: &env.backend, State: onAcceptState, FeeCalculator: feeCalculator, Tx: subnetValTx, })) - builder, signer = env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx2, err := builder.NewRemoveSubnetValidatorTx( + tx, err := wallet.IssueRemoveSubnetValidatorTx( primaryValidator.NodeID, - testSubnet1.ID(), + subnetID, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx2) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "TransformSubnetTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewTransformSubnetTx( - testSubnet1.TxID, // subnetID + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueTransformSubnetTx( + subnetID, // subnetID ids.GenerateTestID(), // assetID 10, // initial supply 10, // max supply @@ -1451,29 +1427,27 @@ func TestDurangoMemoField(t *testing.T) { 80, // uptime requirement common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "AddPermissionlessValidatorTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) var ( nodeID = ids.GenerateTestNodeID() chainTime = env.state.GetTimestamp() endTime = chainTime.Add(defaultMaxStakingDuration) ) sk, err := bls.NewSecretKey() - require.NoError(t, err) + require.NoError(err) - builder, txSigner := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewAddPermissionlessValidatorTx( + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueAddPermissionlessValidatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: nodeID, @@ -1485,33 +1459,26 @@ func TestDurangoMemoField(t *testing.T) { }, signer.NewProofOfPossession(sk), env.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + owners, + owners, reward.PercentDenominator, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), txSigner, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "AddPermissionlessDelegatorTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + var primaryValidator *state.Staker it, err := env.state.GetCurrentStakerIterator() - require.NoError(t, err) + require.NoError(err) for it.Next() { staker := it.Value() if staker.Priority != txs.PrimaryNetworkValidatorCurrentPriority { @@ -1522,8 +1489,8 @@ func TestDurangoMemoField(t *testing.T) { } it.Release() - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewAddPermissionlessDelegatorTx( + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueAddPermissionlessDelegatorTx( &txs.SubnetValidator{ Validator: txs.Validator{ NodeID: primaryValidator.NodeID, @@ -1534,49 +1501,45 @@ func TestDurangoMemoField(t *testing.T) { Subnet: constants.PrimaryNetworkID, }, env.ctx.AVAXAssetID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + owners, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "TransferSubnetOwnershipTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewTransferSubnetOwnershipTx( - testSubnet1.TxID, - &secp256k1fx.OutputOwners{ - Threshold: 1, - Addrs: []ids.ShortID{ids.ShortEmpty}, - }, + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + + subnetID := testSubnet1.ID() + wallet := newWallet(t, env, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + tx, err := wallet.IssueTransferSubnetOwnershipTx( + subnetID, + owners, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, { name: "BaseTx", - setupTest: func(env *environment, memoField []byte) (*txs.Tx, state.Diff) { - builder, signer := env.factory.NewWallet(genesistest.DefaultFundedKeys...) - utx, err := builder.NewBaseTx( + setupTest: func(t *testing.T, env *environment, memoField []byte) (*txs.Tx, state.Diff) { + require := require.New(t) + + wallet := newWallet(t, env, walletConfig{}) + tx, err := wallet.IssueBaseTx( []*avax.TransferableOutput{ { Asset: avax.Asset{ID: env.ctx.AVAXAssetID}, @@ -1591,13 +1554,10 @@ func TestDurangoMemoField(t *testing.T) { }, common.WithMemo(memoField), ) - require.NoError(t, err) - tx, err := walletsigner.SignUnsigned(context.Background(), signer, utx) - require.NoError(t, err) + require.NoError(err) onAcceptState, err := state.NewDiff(env.state.GetLastAccepted(), env) - require.NoError(t, err) - + require.NoError(err) return tx, onAcceptState }, }, @@ -1614,7 +1574,7 @@ func TestDurangoMemoField(t *testing.T) { feeCalculator := state.PickFeeCalculator(env.config, env.state) // Populated memo field should error - tx, onAcceptState := tt.setupTest(env, []byte{'m', 'e', 'm', 'o'}) + tx, onAcceptState := tt.setupTest(t, env, []byte{'m', 'e', 'm', 'o'}) err := tx.Unsigned.Visit(&StandardTxExecutor{ Backend: &env.backend, State: onAcceptState, @@ -1624,7 +1584,7 @@ func TestDurangoMemoField(t *testing.T) { require.ErrorIs(err, avax.ErrMemoTooLarge) // Empty memo field should not error - tx, onAcceptState = tt.setupTest(env, []byte{}) + tx, onAcceptState = tt.setupTest(t, env, []byte{}) require.NoError(tx.Unsigned.Visit(&StandardTxExecutor{ Backend: &env.backend, State: onAcceptState, diff --git a/vms/platformvm/txs/txstest/backend.go b/vms/platformvm/txs/txstest/backend.go deleted file mode 100644 index 3ef798c0b69d..000000000000 --- a/vms/platformvm/txs/txstest/backend.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package txstest - -import ( - "context" - "math" - - "github.com/ava-labs/avalanchego/chains/atomic" - "github.com/ava-labs/avalanchego/ids" - "github.com/ava-labs/avalanchego/utils/constants" - "github.com/ava-labs/avalanchego/utils/set" - "github.com/ava-labs/avalanchego/vms/components/avax" - "github.com/ava-labs/avalanchego/vms/platformvm/fx" - "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/platformvm/txs" - "github.com/ava-labs/avalanchego/wallet/chain/p/builder" - "github.com/ava-labs/avalanchego/wallet/chain/p/signer" -) - -var ( - _ builder.Backend = (*Backend)(nil) - _ signer.Backend = (*Backend)(nil) -) - -func newBackend( - addrs set.Set[ids.ShortID], - state state.State, - sharedMemory atomic.SharedMemory, -) *Backend { - return &Backend{ - addrs: addrs, - state: state, - sharedMemory: sharedMemory, - } -} - -type Backend struct { - addrs set.Set[ids.ShortID] - state state.State - sharedMemory atomic.SharedMemory -} - -func (b *Backend) UTXOs(_ context.Context, sourceChainID ids.ID) ([]*avax.UTXO, error) { - if sourceChainID == constants.PlatformChainID { - return avax.GetAllUTXOs(b.state, b.addrs) - } - - utxos, _, _, err := avax.GetAtomicUTXOs( - b.sharedMemory, - txs.Codec, - sourceChainID, - b.addrs, - ids.ShortEmpty, - ids.Empty, - math.MaxInt, - ) - return utxos, err -} - -func (b *Backend) GetUTXO(_ context.Context, chainID, utxoID ids.ID) (*avax.UTXO, error) { - if chainID == constants.PlatformChainID { - return b.state.GetUTXO(utxoID) - } - - utxoBytes, err := b.sharedMemory.Get(chainID, [][]byte{utxoID[:]}) - if err != nil { - return nil, err - } - - utxo := avax.UTXO{} - if _, err := txs.Codec.Unmarshal(utxoBytes[0], &utxo); err != nil { - return nil, err - } - return &utxo, nil -} - -func (b *Backend) GetSubnetOwner(_ context.Context, subnetID ids.ID) (fx.Owner, error) { - return b.state.GetSubnetOwner(subnetID) -} diff --git a/vms/platformvm/txs/txstest/builder.go b/vms/platformvm/txs/txstest/builder.go deleted file mode 100644 index 532720be981f..000000000000 --- a/vms/platformvm/txs/txstest/builder.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. -// See the file LICENSE for licensing terms. - -package txstest - -import ( - "github.com/ava-labs/avalanchego/snow" - "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" - "github.com/ava-labs/avalanchego/vms/platformvm/config" - "github.com/ava-labs/avalanchego/vms/platformvm/state" - "github.com/ava-labs/avalanchego/vms/secp256k1fx" - "github.com/ava-labs/avalanchego/wallet/chain/p/builder" - "github.com/ava-labs/avalanchego/wallet/chain/p/signer" -) - -func NewWalletFactory( - ctx *snow.Context, - cfg *config.Config, - state state.State, -) *WalletFactory { - return &WalletFactory{ - ctx: ctx, - cfg: cfg, - state: state, - } -} - -type WalletFactory struct { - ctx *snow.Context - cfg *config.Config - state state.State -} - -func (w *WalletFactory) NewWallet(keys ...*secp256k1.PrivateKey) (builder.Builder, signer.Signer) { - var ( - kc = secp256k1fx.NewKeychain(keys...) - addrs = kc.Addresses() - backend = newBackend(addrs, w.state, w.ctx.SharedMemory) - context = newContext(w.ctx, w.cfg, w.state.GetTimestamp()) - ) - - return builder.New(addrs, context, backend), signer.New(kc, backend) -} From 0a8acdeb1b72f25117843a668fdbcef89e4a7416 Mon Sep 17 00:00:00 2001 From: marun Date: Wed, 28 Aug 2024 06:02:39 -0700 Subject: [PATCH 52/69] [ci] Configure buf-setup-action for check_generated_protobuf job with token (#3341) --- .github/workflows/ci.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 07edd1b0443a..a7c6145e2a61 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -165,6 +165,8 @@ jobs: - uses: actions/checkout@v4 - uses: ./.github/actions/setup-go-for-project - uses: bufbuild/buf-setup-action@v1.31.0 + with: + github_token: ${{ github.token }} - shell: bash run: scripts/protobuf_codegen.sh - shell: bash From 82bf033c3fb495d9441b752e4f168b3dc58513c8 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Wed, 28 Aug 2024 16:40:37 -0400 Subject: [PATCH 53/69] Add P-chain dynamic fees execution (#3251) --- vms/platformvm/block/builder/builder.go | 209 ++++++++++++++---- vms/platformvm/block/executor/verifier.go | 36 +++ .../block/executor/verifier_test.go | 142 ++++++++++++ vms/platformvm/service_test.go | 28 +-- vms/platformvm/state/chain_time_helpers.go | 16 +- .../state/chain_time_helpers_test.go | 64 ++++++ vms/platformvm/txs/executor/state_changes.go | 18 +- .../txs/executor/state_changes_test.go | 100 +++++++++ vms/platformvm/txs/txstest/context.go | 40 ++-- vms/platformvm/txs/txstest/wallet.go | 2 +- vms/platformvm/vm_test.go | 7 +- wallet/chain/p/builder/context.go | 50 ----- wallet/chain/p/context.go | 84 +++++++ wallet/subnet/primary/api.go | 3 +- 14 files changed, 674 insertions(+), 125 deletions(-) create mode 100644 vms/platformvm/state/chain_time_helpers_test.go create mode 100644 vms/platformvm/txs/executor/state_changes_test.go create mode 100644 wallet/chain/p/context.go diff --git a/vms/platformvm/block/builder/builder.go b/vms/platformvm/block/builder/builder.go index 6cecad86184f..35ad20adc16c 100644 --- a/vms/platformvm/block/builder/builder.go +++ b/vms/platformvm/block/builder/builder.go @@ -19,10 +19,12 @@ import ( "github.com/ava-labs/avalanchego/utils/set" "github.com/ava-labs/avalanchego/utils/timer/mockable" "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool" blockexecutor "github.com/ava-labs/avalanchego/vms/platformvm/block/executor" @@ -244,14 +246,30 @@ func (b *builder) PackAllBlockTxs() ([]*txs.Tx, error) { return nil, fmt.Errorf("%w: %s", errMissingPreferredState, preferredID) } - return packBlockTxs( + timestamp, _, err := state.NextBlockTime(preferredState, b.txExecutorBackend.Clk) + if err != nil { + return nil, fmt.Errorf("could not calculate next staker change time: %w", err) + } + + if !b.txExecutorBackend.Config.UpgradeConfig.IsEtnaActivated(timestamp) { + return packDurangoBlockTxs( + preferredID, + preferredState, + b.Mempool, + b.txExecutorBackend, + b.blkManager, + timestamp, + math.MaxInt, + ) + } + return packEtnaBlockTxs( preferredID, preferredState, b.Mempool, b.txExecutorBackend, b.blkManager, - b.txExecutorBackend.Clk.Time(), - math.MaxInt, + timestamp, + math.MaxUint64, ) } @@ -264,15 +282,31 @@ func buildBlock( forceAdvanceTime bool, parentState state.Chain, ) (block.Block, error) { - blockTxs, err := packBlockTxs( - parentID, - parentState, - builder.Mempool, - builder.txExecutorBackend, - builder.blkManager, - timestamp, - targetBlockSize, + var ( + blockTxs []*txs.Tx + err error ) + if builder.txExecutorBackend.Config.UpgradeConfig.IsEtnaActivated(timestamp) { + blockTxs, err = packEtnaBlockTxs( + parentID, + parentState, + builder.Mempool, + builder.txExecutorBackend, + builder.blkManager, + timestamp, + 0, // minCapacity is 0 as we want to honor the capacity in state. + ) + } else { + blockTxs, err = packDurangoBlockTxs( + parentID, + parentState, + builder.Mempool, + builder.txExecutorBackend, + builder.blkManager, + timestamp, + targetBlockSize, + ) + } if err != nil { return nil, fmt.Errorf("failed to pack block txs: %w", err) } @@ -314,7 +348,7 @@ func buildBlock( ) } -func packBlockTxs( +func packDurangoBlockTxs( parentID ids.ID, parentState state.Chain, mempool mempool.Mempool, @@ -346,55 +380,154 @@ func packBlockTxs( if txSize > remainingSize { break } - mempool.Remove(tx) - - // Invariant: [tx] has already been syntactically verified. - txDiff, err := state.NewDiffOn(stateDiff) + shouldAdd, err := executeTx( + parentID, + stateDiff, + mempool, + backend, + manager, + &inputs, + feeCalculator, + tx, + ) if err != nil { return nil, err } + if !shouldAdd { + continue + } + + remainingSize -= txSize + blockTxs = append(blockTxs, tx) + } + + return blockTxs, nil +} + +func packEtnaBlockTxs( + parentID ids.ID, + parentState state.Chain, + mempool mempool.Mempool, + backend *txexecutor.Backend, + manager blockexecutor.Manager, + timestamp time.Time, + minCapacity gas.Gas, +) ([]*txs.Tx, error) { + stateDiff, err := state.NewDiffOn(parentState) + if err != nil { + return nil, err + } + + if _, err := txexecutor.AdvanceTimeTo(backend, stateDiff, timestamp); err != nil { + return nil, err + } + + feeState := stateDiff.GetFeeState() + capacity := max(feeState.Capacity, minCapacity) - executor := &txexecutor.StandardTxExecutor{ - Backend: backend, - State: txDiff, - FeeCalculator: feeCalculator, - Tx: tx, + var ( + blockTxs []*txs.Tx + inputs set.Set[ids.ID] + blockComplexity gas.Dimensions + feeCalculator = state.PickFeeCalculator(backend.Config, stateDiff) + ) + for { + tx, exists := mempool.Peek() + if !exists { + break } - err = tx.Unsigned.Visit(executor) + txComplexity, err := fee.TxComplexity(tx.Unsigned) if err != nil { - txID := tx.ID() - mempool.MarkDropped(txID, err) - continue + return nil, err } - - if inputs.Overlaps(executor.Inputs) { - txID := tx.ID() - mempool.MarkDropped(txID, blockexecutor.ErrConflictingBlockTxs) - continue + newBlockComplexity, err := blockComplexity.Add(&txComplexity) + if err != nil { + return nil, err } - err = manager.VerifyUniqueInputs(parentID, executor.Inputs) + newBlockGas, err := newBlockComplexity.ToGas(backend.Config.DynamicFeeConfig.Weights) if err != nil { - txID := tx.ID() - mempool.MarkDropped(txID, err) - continue + return nil, err + } + if newBlockGas > capacity { + break } - inputs.Union(executor.Inputs) - txDiff.AddTx(tx, status.Committed) - err = txDiff.Apply(stateDiff) + shouldAdd, err := executeTx( + parentID, + stateDiff, + mempool, + backend, + manager, + &inputs, + feeCalculator, + tx, + ) if err != nil { return nil, err } + if !shouldAdd { + continue + } - remainingSize -= txSize + blockComplexity = newBlockComplexity blockTxs = append(blockTxs, tx) } return blockTxs, nil } +func executeTx( + parentID ids.ID, + stateDiff state.Diff, + mempool mempool.Mempool, + backend *txexecutor.Backend, + manager blockexecutor.Manager, + inputs *set.Set[ids.ID], + feeCalculator fee.Calculator, + tx *txs.Tx, +) (bool, error) { + mempool.Remove(tx) + + // Invariant: [tx] has already been syntactically verified. + + txDiff, err := state.NewDiffOn(stateDiff) + if err != nil { + return false, err + } + + executor := &txexecutor.StandardTxExecutor{ + Backend: backend, + State: txDiff, + FeeCalculator: feeCalculator, + Tx: tx, + } + + err = tx.Unsigned.Visit(executor) + if err != nil { + txID := tx.ID() + mempool.MarkDropped(txID, err) + return false, nil + } + + if inputs.Overlaps(executor.Inputs) { + txID := tx.ID() + mempool.MarkDropped(txID, blockexecutor.ErrConflictingBlockTxs) + return false, nil + } + err = manager.VerifyUniqueInputs(parentID, executor.Inputs) + if err != nil { + txID := tx.ID() + mempool.MarkDropped(txID, err) + return false, nil + } + inputs.Union(executor.Inputs) + + txDiff.AddTx(tx, status.Committed) + return true, txDiff.Apply(stateDiff) +} + // getNextStakerToReward returns the next staker txID to remove from the staking // set with a RewardValidatorTx rather than an AdvanceTimeTx. [chainTimestamp] // is the timestamp of the chain at the time this validator would be getting diff --git a/vms/platformvm/block/executor/verifier.go b/vms/platformvm/block/executor/verifier.go index e238a35c100e..532dc4d4b6f6 100644 --- a/vms/platformvm/block/executor/verifier.go +++ b/vms/platformvm/block/executor/verifier.go @@ -10,6 +10,7 @@ import ( "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/utils/set" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/status" @@ -460,6 +461,41 @@ func (v *verifier) processStandardTxs(txs []*txs.Tx, feeCalculator fee.Calculato func(), error, ) { + // Complexity is limited first to avoid processing too large of a block. + if timestamp := state.GetTimestamp(); v.txExecutorBackend.Config.UpgradeConfig.IsEtnaActivated(timestamp) { + var blockComplexity gas.Dimensions + for _, tx := range txs { + txComplexity, err := fee.TxComplexity(tx.Unsigned) + if err != nil { + txID := tx.ID() + v.MarkDropped(txID, err) + return nil, nil, nil, err + } + + blockComplexity, err = blockComplexity.Add(&txComplexity) + if err != nil { + return nil, nil, nil, err + } + } + + blockGas, err := blockComplexity.ToGas(v.txExecutorBackend.Config.DynamicFeeConfig.Weights) + if err != nil { + return nil, nil, nil, err + } + + // If this block exceeds the available capacity, ConsumeGas will return + // an error. + feeState := state.GetFeeState() + feeState, err = feeState.ConsumeGas(blockGas) + if err != nil { + return nil, nil, nil, err + } + + // Updating the fee state prior to executing the transactions is fine + // because the fee calculator was already created. + state.SetFeeState(feeState) + } + var ( onAcceptFunc func() inputs set.Set[ids.ID] diff --git a/vms/platformvm/block/executor/verifier_test.go b/vms/platformvm/block/executor/verifier_test.go index d2b131a3f2a3..6508d4c88624 100644 --- a/vms/platformvm/block/executor/verifier_test.go +++ b/vms/platformvm/block/executor/verifier_test.go @@ -8,30 +8,88 @@ import ( "testing" "time" + "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/chains/atomic" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/genesis" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/upgrade/upgradetest" + "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" "github.com/ava-labs/avalanchego/utils/timer/mockable" + "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/platformvm/block" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool" "github.com/ava-labs/avalanchego/vms/platformvm/txs/mempool/mempoolmock" "github.com/ava-labs/avalanchego/vms/platformvm/txs/txsmock" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" + "github.com/ava-labs/avalanchego/vms/platformvm/utxo" + "github.com/ava-labs/avalanchego/vms/secp256k1fx" ) +func newTestVerifier(t testing.TB, s state.State) *verifier { + require := require.New(t) + + mempool, err := mempool.New("", prometheus.NewRegistry(), nil) + require.NoError(err) + + var ( + upgrades = upgradetest.GetConfig(upgradetest.Latest) + ctx = snowtest.Context(t, constants.PlatformChainID) + clock = &mockable.Clock{} + fx = &secp256k1fx.Fx{} + ) + require.NoError(fx.InitializeVM(&secp256k1fx.TestVM{ + Clk: *clock, + Log: logging.NoLog{}, + })) + + return &verifier{ + backend: &backend{ + Mempool: mempool, + lastAccepted: s.GetLastAccepted(), + blkIDToState: make(map[ids.ID]*blockState), + state: s, + ctx: ctx, + }, + txExecutorBackend: &executor.Backend{ + Config: &config.Config{ + CreateAssetTxFee: genesis.LocalParams.CreateAssetTxFee, + StaticFeeConfig: genesis.LocalParams.StaticFeeConfig, + DynamicFeeConfig: genesis.LocalParams.DynamicFeeConfig, + SybilProtectionEnabled: true, + UpgradeConfig: upgrades, + }, + Ctx: ctx, + Clk: clock, + Fx: fx, + FlowChecker: utxo.NewVerifier( + ctx, + clock, + fx, + ), + Bootstrapped: utils.NewAtomic(true), + }, + } +} + func TestVerifierVisitProposalBlock(t *testing.T) { require := require.New(t) ctrl := gomock.NewController(t) @@ -1042,3 +1100,87 @@ func TestVerifierVisitBanffAbortBlockUnexpectedParentState(t *testing.T) { err = verifier.BanffAbortBlock(blk) require.ErrorIs(err, state.ErrMissingParentState) } + +func TestBlockExecutionWithComplexity(t *testing.T) { + s := statetest.New(t, statetest.Config{}) + verifier := newTestVerifier(t, s) + wallet := txstest.NewWallet( + t, + verifier.ctx, + verifier.txExecutorBackend.Config, + s, + secp256k1fx.NewKeychain(genesis.EWOQKey), + nil, // subnetIDs + nil, // chainIDs + ) + + baseTx0, err := wallet.IssueBaseTx([]*avax.TransferableOutput{}) + require.NoError(t, err) + baseTx1, err := wallet.IssueBaseTx([]*avax.TransferableOutput{}) + require.NoError(t, err) + + blockComplexity, err := fee.TxComplexity(baseTx0.Unsigned, baseTx1.Unsigned) + require.NoError(t, err) + blockGas, err := blockComplexity.ToGas(verifier.txExecutorBackend.Config.DynamicFeeConfig.Weights) + require.NoError(t, err) + + tests := []struct { + name string + timestamp time.Time + expectedErr error + expectedFeeState gas.State + }{ + { + name: "no capacity", + timestamp: genesistest.DefaultValidatorStartTime, + expectedErr: gas.ErrInsufficientCapacity, + }, + { + name: "updates fee state", + timestamp: genesistest.DefaultValidatorStartTime.Add(10 * time.Second), + expectedFeeState: gas.State{ + Capacity: gas.Gas(0).AddPerSecond(verifier.txExecutorBackend.Config.DynamicFeeConfig.MaxPerSecond, 10) - blockGas, + Excess: blockGas, + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + // Clear the state to prevent prior tests from impacting this test. + clear(verifier.blkIDToState) + + verifier.txExecutorBackend.Clk.Set(test.timestamp) + timestamp, _, err := state.NextBlockTime(s, verifier.txExecutorBackend.Clk) + require.NoError(err) + + lastAcceptedID := s.GetLastAccepted() + lastAccepted, err := s.GetStatelessBlock(lastAcceptedID) + require.NoError(err) + + blk, err := block.NewBanffStandardBlock( + timestamp, + lastAcceptedID, + lastAccepted.Height()+1, + []*txs.Tx{ + baseTx0, + baseTx1, + }, + ) + require.NoError(err) + + blkID := blk.ID() + err = blk.Visit(verifier) + require.ErrorIs(err, test.expectedErr) + if err != nil { + require.NotContains(verifier.blkIDToState, blkID) + return + } + + require.Contains(verifier.blkIDToState, blkID) + onAcceptState := verifier.blkIDToState[blkID].onAcceptState + require.Equal(test.expectedFeeState, onAcceptState.GetFeeState()) + }) + } +} diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index 24edafbeca83..c896066142e6 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -78,8 +78,8 @@ var ( } ) -func defaultService(t *testing.T) (*Service, *mutableSharedMemory) { - vm, _, mutableSharedMemory := defaultVM(t, upgradetest.Latest) +func defaultService(t *testing.T, fork upgradetest.Fork) (*Service, *mutableSharedMemory) { + vm, _, mutableSharedMemory := defaultVM(t, fork) return &Service{ vm: vm, addrManager: avax.NewAddressManager(vm.ctx), @@ -92,7 +92,7 @@ func defaultService(t *testing.T) (*Service, *mutableSharedMemory) { func TestExportKey(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) service.vm.ctx.Lock.Lock() ks := keystore.New(logging.NoLog{}, memdb.New()) @@ -122,7 +122,7 @@ func TestExportKey(t *testing.T) { // Test issuing a tx and accepted func TestGetTxStatus(t *testing.T) { require := require.New(t) - service, mutableSharedMemory := defaultService(t) + service, mutableSharedMemory := defaultService(t, upgradetest.Latest) service.vm.ctx.Lock.Lock() recipientKey, err := secp256k1.NewPrivateKey() @@ -304,7 +304,7 @@ func TestGetTx(t *testing.T) { ) t.Run(testName, func(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) service.vm.ctx.Lock.Lock() tx := test.createTx(t, service) @@ -366,10 +366,10 @@ func TestGetTx(t *testing.T) { func TestGetBalance(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Durango) feeCalculator := state.PickFeeCalculator(&service.vm.Config, service.vm.state) - createSubnetFee, err := feeCalculator.CalculateFee(&txs.CreateSubnetTx{}) + createSubnetFee, err := feeCalculator.CalculateFee(testSubnet1.Unsigned) require.NoError(err) // Ensure GetStake is correct for each of the genesis validators @@ -405,7 +405,7 @@ func TestGetBalance(t *testing.T) { func TestGetStake(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) // Ensure GetStake is correct for each of the genesis validators genesis := genesistest.New(t, genesistest.Config{}) @@ -605,7 +605,7 @@ func TestGetStake(t *testing.T) { func TestGetCurrentValidators(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) genesis := genesistest.New(t, genesistest.Config{}) @@ -741,7 +741,7 @@ func TestGetCurrentValidators(t *testing.T) { func TestGetTimestamp(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) reply := GetTimestampReply{} require.NoError(service.GetTimestamp(nil, nil, &reply)) @@ -777,7 +777,7 @@ func TestGetBlock(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) service.vm.ctx.Lock.Lock() service.vm.Config.CreateAssetTxFee = 100 * defaultTxFee @@ -1066,7 +1066,7 @@ func TestServiceGetBlockByHeight(t *testing.T) { func TestServiceGetSubnets(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) testSubnet1ID := testSubnet1.ID() @@ -1138,7 +1138,7 @@ func TestGetFeeConfig(t *testing.T) { t.Run(test.name, func(t *testing.T) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) service.vm.Config.UpgradeConfig.EtnaTime = test.etnaTime var reply gas.Config @@ -1152,7 +1152,7 @@ func FuzzGetFeeState(f *testing.F) { f.Fuzz(func(t *testing.T, capacity, excess uint64) { require := require.New(t) - service, _ := defaultService(t) + service, _ := defaultService(t, upgradetest.Latest) var ( expectedState = gas.State{ diff --git a/vms/platformvm/state/chain_time_helpers.go b/vms/platformvm/state/chain_time_helpers.go index 7b5dd6ebe10b..8b861f69a265 100644 --- a/vms/platformvm/state/chain_time_helpers.go +++ b/vms/platformvm/state/chain_time_helpers.go @@ -9,6 +9,7 @@ import ( "github.com/ava-labs/avalanchego/database" "github.com/ava-labs/avalanchego/utils/timer/mockable" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/config" "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) @@ -77,7 +78,20 @@ func GetNextStakerChangeTime(state Chain) (time.Time, error) { // PickFeeCalculator does not modify [state]. func PickFeeCalculator(cfg *config.Config, state Chain) fee.Calculator { timestamp := state.GetTimestamp() - return NewStaticFeeCalculator(cfg, timestamp) + if !cfg.UpgradeConfig.IsEtnaActivated(timestamp) { + return NewStaticFeeCalculator(cfg, timestamp) + } + + feeState := state.GetFeeState() + gasPrice := gas.CalculatePrice( + cfg.DynamicFeeConfig.MinPrice, + feeState.Excess, + cfg.DynamicFeeConfig.ExcessConversionConstant, + ) + return fee.NewDynamicCalculator( + cfg.DynamicFeeConfig.Weights, + gasPrice, + ) } // NewStaticFeeCalculator creates a static fee calculator, with the config set diff --git a/vms/platformvm/state/chain_time_helpers_test.go b/vms/platformvm/state/chain_time_helpers_test.go new file mode 100644 index 000000000000..3a6304aaeea5 --- /dev/null +++ b/vms/platformvm/state/chain_time_helpers_test.go @@ -0,0 +1,64 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package state + +import ( + "testing" + + "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/database/memdb" + "github.com/ava-labs/avalanchego/genesis" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" + "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" +) + +func TestPickFeeCalculator(t *testing.T) { + var ( + createAssetTxFee = genesis.LocalParams.CreateAssetTxFee + staticFeeConfig = genesis.LocalParams.StaticFeeConfig + dynamicFeeConfig = genesis.LocalParams.DynamicFeeConfig + ) + + apricotPhase2StaticFeeConfig := staticFeeConfig + apricotPhase2StaticFeeConfig.CreateSubnetTxFee = createAssetTxFee + apricotPhase2StaticFeeConfig.CreateBlockchainTxFee = createAssetTxFee + + tests := []struct { + fork upgradetest.Fork + expected fee.Calculator + }{ + { + fork: upgradetest.ApricotPhase2, + expected: fee.NewStaticCalculator(apricotPhase2StaticFeeConfig), + }, + { + fork: upgradetest.ApricotPhase3, + expected: fee.NewStaticCalculator(staticFeeConfig), + }, + { + fork: upgradetest.Etna, + expected: fee.NewDynamicCalculator( + dynamicFeeConfig.Weights, + dynamicFeeConfig.MinPrice, + ), + }, + } + for _, test := range tests { + t.Run(test.fork.String(), func(t *testing.T) { + var ( + config = &config.Config{ + CreateAssetTxFee: createAssetTxFee, + StaticFeeConfig: staticFeeConfig, + DynamicFeeConfig: dynamicFeeConfig, + UpgradeConfig: upgradetest.GetConfig(test.fork), + } + s = newTestState(t, memdb.New()) + ) + actual := PickFeeCalculator(config, s) + require.Equal(t, test.expected, actual) + }) + } +} diff --git a/vms/platformvm/txs/executor/state_changes.go b/vms/platformvm/txs/executor/state_changes.go index 3086358304a3..244be246f8a0 100644 --- a/vms/platformvm/txs/executor/state_changes.go +++ b/vms/platformvm/txs/executor/state_changes.go @@ -165,12 +165,22 @@ func AdvanceTimeTo( changed = true } - if err := changes.Apply(parentState); err != nil { - return false, err + if backend.Config.UpgradeConfig.IsEtnaActivated(newChainTime) { + previousChainTime := changes.GetTimestamp() + duration := uint64(newChainTime.Sub(previousChainTime) / time.Second) + + feeState := changes.GetFeeState() + feeState = feeState.AdvanceTime( + backend.Config.DynamicFeeConfig.MaxCapacity, + backend.Config.DynamicFeeConfig.MaxPerSecond, + backend.Config.DynamicFeeConfig.TargetPerSecond, + duration, + ) + changes.SetFeeState(feeState) } - parentState.SetTimestamp(newChainTime) - return changed, nil + changes.SetTimestamp(newChainTime) + return changed, changes.Apply(parentState) } func GetRewardsCalculator( diff --git a/vms/platformvm/txs/executor/state_changes_test.go b/vms/platformvm/txs/executor/state_changes_test.go new file mode 100644 index 000000000000..5588f4b7da73 --- /dev/null +++ b/vms/platformvm/txs/executor/state_changes_test.go @@ -0,0 +1,100 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package executor + +import ( + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/upgrade/upgradetest" + "github.com/ava-labs/avalanchego/vms/components/gas" + "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" +) + +func TestAdvanceTimeTo_UpdatesFeeState(t *testing.T) { + const ( + secondsToAdvance = 3 + durationToAdvance = secondsToAdvance * time.Second + ) + + feeConfig := gas.Config{ + MaxCapacity: 1000, + MaxPerSecond: 100, + TargetPerSecond: 50, + } + + tests := []struct { + name string + fork upgradetest.Fork + initialState gas.State + expectedState gas.State + }{ + { + name: "Pre-Etna", + fork: upgradetest.Durango, + initialState: gas.State{}, + expectedState: gas.State{}, // Pre-Etna, fee state should not change + }, + { + name: "Etna with no usage", + initialState: gas.State{ + Capacity: feeConfig.MaxCapacity, + Excess: 0, + }, + expectedState: gas.State{ + Capacity: feeConfig.MaxCapacity, + Excess: 0, + }, + }, + { + name: "Etna with usage", + fork: upgradetest.Etna, + initialState: gas.State{ + Capacity: 1, + Excess: 10_000, + }, + expectedState: gas.State{ + Capacity: min(gas.Gas(1).AddPerSecond(feeConfig.MaxPerSecond, secondsToAdvance), feeConfig.MaxCapacity), + Excess: gas.Gas(10_000).SubPerSecond(feeConfig.TargetPerSecond, secondsToAdvance), + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + var ( + require = require.New(t) + + s = statetest.New(t, statetest.Config{}) + nextTime = s.GetTimestamp().Add(durationToAdvance) + ) + + // Ensure the invariant that [nextTime <= nextStakerChangeTime] on + // AdvanceTimeTo is maintained. + nextStakerChangeTime, err := state.GetNextStakerChangeTime(s) + require.NoError(err) + require.False(nextTime.After(nextStakerChangeTime)) + + s.SetFeeState(test.initialState) + + validatorsModified, err := AdvanceTimeTo( + &Backend{ + Config: &config.Config{ + DynamicFeeConfig: feeConfig, + UpgradeConfig: upgradetest.GetConfig(test.fork), + }, + }, + s, + nextTime, + ) + require.NoError(err) + require.False(validatorsModified) + require.Equal(test.expectedState, s.GetFeeState()) + require.Equal(nextTime, s.GetTimestamp()) + }) + } +} diff --git a/vms/platformvm/txs/txstest/context.go b/vms/platformvm/txs/txstest/context.go index 5f453429c226..4fcc0f790ec8 100644 --- a/vms/platformvm/txs/txstest/context.go +++ b/vms/platformvm/txs/txstest/context.go @@ -4,27 +4,39 @@ package txstest import ( - "time" - "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/config" + "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/wallet/chain/p/builder" ) func newContext( ctx *snow.Context, - cfg *config.Config, - timestamp time.Time, + config *config.Config, + state state.State, ) *builder.Context { - feeConfig := cfg.StaticFeeConfig - if !cfg.UpgradeConfig.IsApricotPhase3Activated(timestamp) { - feeConfig.CreateSubnetTxFee = cfg.CreateAssetTxFee - feeConfig.CreateBlockchainTxFee = cfg.CreateAssetTxFee - } - - return &builder.Context{ - NetworkID: ctx.NetworkID, - AVAXAssetID: ctx.AVAXAssetID, - StaticFeeConfig: feeConfig, + var ( + timestamp = state.GetTimestamp() + builderContext = &builder.Context{ + NetworkID: ctx.NetworkID, + AVAXAssetID: ctx.AVAXAssetID, + } + ) + switch { + case config.UpgradeConfig.IsEtnaActivated(timestamp): + builderContext.ComplexityWeights = config.DynamicFeeConfig.Weights + builderContext.GasPrice = gas.CalculatePrice( + config.DynamicFeeConfig.MinPrice, + state.GetFeeState().Excess, + config.DynamicFeeConfig.ExcessConversionConstant, + ) + case config.UpgradeConfig.IsApricotPhase3Activated(timestamp): + builderContext.StaticFeeConfig = config.StaticFeeConfig + default: + builderContext.StaticFeeConfig = config.StaticFeeConfig + builderContext.StaticFeeConfig.CreateSubnetTxFee = config.CreateAssetTxFee + builderContext.StaticFeeConfig.CreateBlockchainTxFee = config.CreateAssetTxFee } + return builderContext } diff --git a/vms/platformvm/txs/txstest/wallet.go b/vms/platformvm/txs/txstest/wallet.go index 8f16b40719b3..0a040eed7d82 100644 --- a/vms/platformvm/txs/txstest/wallet.go +++ b/vms/platformvm/txs/txstest/wallet.go @@ -81,7 +81,7 @@ func NewWallet( owners[subnetID] = owner } - builderContext := newContext(ctx, config, state.GetTimestamp()) + builderContext := newContext(ctx, config, state) backend := wallet.NewBackend( builderContext, common.NewChainUTXOs(constants.PlatformChainID, utxos), diff --git a/vms/platformvm/vm_test.go b/vms/platformvm/vm_test.go index d11141c923aa..ab31ba76402e 100644 --- a/vms/platformvm/vm_test.go +++ b/vms/platformvm/vm_test.go @@ -184,6 +184,9 @@ func defaultVM(t *testing.T, f upgradetest.Fork) (*VM, database.Database, *mutab // align chain time and local clock vm.state.SetTimestamp(vm.clock.Time()) + vm.state.SetFeeState(gas.State{ + Capacity: defaultDynamicFeeConfig.MaxCapacity, + }) require.NoError(vm.SetState(context.Background(), snow.NormalOp)) @@ -245,7 +248,7 @@ func newWallet(t testing.TB, vm *VM, c walletConfig) wallet.Wallet { // Ensure genesis state is parsed from bytes and stored correctly func TestGenesis(t *testing.T) { require := require.New(t) - vm, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Durango) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() @@ -2034,7 +2037,7 @@ func TestTransferSubnetOwnershipTx(t *testing.T) { func TestBaseTx(t *testing.T) { require := require.New(t) - vm, _, _ := defaultVM(t, upgradetest.Latest) + vm, _, _ := defaultVM(t, upgradetest.Durango) vm.ctx.Lock.Lock() defer vm.ctx.Lock.Unlock() diff --git a/wallet/chain/p/builder/context.go b/wallet/chain/p/builder/context.go index 2ddf168ad228..bb871a9f2944 100644 --- a/wallet/chain/p/builder/context.go +++ b/wallet/chain/p/builder/context.go @@ -4,14 +4,10 @@ package builder import ( - "context" - - "github.com/ava-labs/avalanchego/api/info" "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/logging" - "github.com/ava-labs/avalanchego/vms/avm" "github.com/ava-labs/avalanchego/vms/components/gas" "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" ) @@ -26,52 +22,6 @@ type Context struct { GasPrice gas.Price } -func NewContextFromURI(ctx context.Context, uri string) (*Context, error) { - infoClient := info.NewClient(uri) - xChainClient := avm.NewClient(uri, "X") - return NewContextFromClients(ctx, infoClient, xChainClient) -} - -func NewContextFromClients( - ctx context.Context, - infoClient info.Client, - xChainClient avm.Client, -) (*Context, error) { - networkID, err := infoClient.GetNetworkID(ctx) - if err != nil { - return nil, err - } - - asset, err := xChainClient.GetAssetDescription(ctx, "AVAX") - if err != nil { - return nil, err - } - - txFees, err := infoClient.GetTxFee(ctx) - if err != nil { - return nil, err - } - - return &Context{ - NetworkID: networkID, - AVAXAssetID: asset.AssetID, - StaticFeeConfig: fee.StaticConfig{ - TxFee: uint64(txFees.TxFee), - CreateSubnetTxFee: uint64(txFees.CreateSubnetTxFee), - TransformSubnetTxFee: uint64(txFees.TransformSubnetTxFee), - CreateBlockchainTxFee: uint64(txFees.CreateBlockchainTxFee), - AddPrimaryNetworkValidatorFee: uint64(txFees.AddPrimaryNetworkValidatorFee), - AddPrimaryNetworkDelegatorFee: uint64(txFees.AddPrimaryNetworkDelegatorFee), - AddSubnetValidatorFee: uint64(txFees.AddSubnetValidatorFee), - AddSubnetDelegatorFee: uint64(txFees.AddSubnetDelegatorFee), - }, - - // TODO: Populate these fields once they are exposed by the API - ComplexityWeights: gas.Dimensions{}, - GasPrice: 0, - }, nil -} - func NewSnowContext(networkID uint32, avaxAssetID ids.ID) (*snow.Context, error) { lookup := ids.NewAliaser() return &snow.Context{ diff --git a/wallet/chain/p/context.go b/wallet/chain/p/context.go new file mode 100644 index 000000000000..a8685e4ee0d3 --- /dev/null +++ b/wallet/chain/p/context.go @@ -0,0 +1,84 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package p + +import ( + "context" + + "github.com/ava-labs/avalanchego/api/info" + "github.com/ava-labs/avalanchego/vms/avm" + "github.com/ava-labs/avalanchego/vms/platformvm" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/wallet/chain/p/builder" +) + +// gasPriceMultiplier increases the gas price to support multiple transactions +// to be issued. +// +// TODO: Handle this better. Either here or in the mempool. +const gasPriceMultiplier = 2 + +func NewContextFromURI(ctx context.Context, uri string) (*builder.Context, error) { + infoClient := info.NewClient(uri) + xChainClient := avm.NewClient(uri, "X") + pChainClient := platformvm.NewClient(uri) + return NewContextFromClients(ctx, infoClient, xChainClient, pChainClient) +} + +func NewContextFromClients( + ctx context.Context, + infoClient info.Client, + xChainClient avm.Client, + pChainClient platformvm.Client, +) (*builder.Context, error) { + networkID, err := infoClient.GetNetworkID(ctx) + if err != nil { + return nil, err + } + + asset, err := xChainClient.GetAssetDescription(ctx, "AVAX") + if err != nil { + return nil, err + } + + dynamicFeeConfig, err := pChainClient.GetFeeConfig(ctx) + if err != nil { + return nil, err + } + + // TODO: After Etna is activated, assume the gas price is always non-zero. + if dynamicFeeConfig.MinPrice != 0 { + _, gasPrice, _, err := pChainClient.GetFeeState(ctx) + if err != nil { + return nil, err + } + + return &builder.Context{ + NetworkID: networkID, + AVAXAssetID: asset.AssetID, + ComplexityWeights: dynamicFeeConfig.Weights, + GasPrice: gasPriceMultiplier * gasPrice, + }, nil + } + + staticFeeConfig, err := infoClient.GetTxFee(ctx) + if err != nil { + return nil, err + } + + return &builder.Context{ + NetworkID: networkID, + AVAXAssetID: asset.AssetID, + StaticFeeConfig: fee.StaticConfig{ + TxFee: uint64(staticFeeConfig.TxFee), + CreateSubnetTxFee: uint64(staticFeeConfig.CreateSubnetTxFee), + TransformSubnetTxFee: uint64(staticFeeConfig.TransformSubnetTxFee), + CreateBlockchainTxFee: uint64(staticFeeConfig.CreateBlockchainTxFee), + AddPrimaryNetworkValidatorFee: uint64(staticFeeConfig.AddPrimaryNetworkValidatorFee), + AddPrimaryNetworkDelegatorFee: uint64(staticFeeConfig.AddPrimaryNetworkDelegatorFee), + AddSubnetValidatorFee: uint64(staticFeeConfig.AddSubnetValidatorFee), + AddSubnetDelegatorFee: uint64(staticFeeConfig.AddSubnetDelegatorFee), + }, + }, nil +} diff --git a/wallet/subnet/primary/api.go b/wallet/subnet/primary/api.go index 2aedc5c476c9..d9f9e5e0624a 100644 --- a/wallet/subnet/primary/api.go +++ b/wallet/subnet/primary/api.go @@ -21,6 +21,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/wallet/chain/c" + "github.com/ava-labs/avalanchego/wallet/chain/p" "github.com/ava-labs/avalanchego/wallet/chain/x" pbuilder "github.com/ava-labs/avalanchego/wallet/chain/p/builder" @@ -79,7 +80,7 @@ func FetchState( xClient := avm.NewClient(uri, "X") cClient := evm.NewCChainClient(uri) - pCTX, err := pbuilder.NewContextFromClients(ctx, infoClient, xClient) + pCTX, err := p.NewContextFromClients(ctx, infoClient, xClient, pClient) if err != nil { return nil, err } From f81b68dc3f6e02526a096786f9f243b688e8c5f6 Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Thu, 29 Aug 2024 21:38:29 +0300 Subject: [PATCH 54/69] Include disconnected validators in health message (#3344) Signed-off-by: Ceyhun Onur Co-authored-by: Darioush Jalali Co-authored-by: Stephen Buttolph --- snow/engine/common/tracker/peers.go | 33 ++++++++++++++++++++++++++ snow/networking/handler/health.go | 16 +++++++++++-- snow/networking/handler/health_test.go | 18 +++++++------- 3 files changed, 56 insertions(+), 11 deletions(-) diff --git a/snow/engine/common/tracker/peers.go b/snow/engine/common/tracker/peers.go index 543933df43c2..37bf7b10f026 100644 --- a/snow/engine/common/tracker/peers.go +++ b/snow/engine/common/tracker/peers.go @@ -9,6 +9,7 @@ import ( "sync" "github.com/prometheus/client_golang/prometheus" + "golang.org/x/exp/maps" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow/validators" @@ -34,6 +35,12 @@ type Peers interface { // SampleValidator returns a randomly selected connected validator. If there // are no currently connected validators then it will return false. SampleValidator() (ids.NodeID, bool) + // GetValidators returns the set of all validators + // known to this peer manager + GetValidators() set.Set[ids.NodeID] + // ConnectedValidators returns the set of all validators + // that are currently connected + ConnectedValidators() set.Set[ids.NodeID] } type lockedPeers struct { @@ -105,6 +112,20 @@ func (p *lockedPeers) SampleValidator() (ids.NodeID, bool) { return p.peers.SampleValidator() } +func (p *lockedPeers) GetValidators() set.Set[ids.NodeID] { + p.lock.RLock() + defer p.lock.RUnlock() + + return p.peers.GetValidators() +} + +func (p *lockedPeers) ConnectedValidators() set.Set[ids.NodeID] { + p.lock.RLock() + defer p.lock.RUnlock() + + return p.peers.ConnectedValidators() +} + type meteredPeers struct { Peers @@ -250,3 +271,15 @@ func (p *peerData) ConnectedPercent() float64 { func (p *peerData) SampleValidator() (ids.NodeID, bool) { return p.connectedValidators.Peek() } + +func (p *peerData) GetValidators() set.Set[ids.NodeID] { + return set.Of(maps.Keys(p.validators)...) +} + +func (p *peerData) ConnectedValidators() set.Set[ids.NodeID] { + // The set is copied to avoid future changes from being reflected in the + // returned set. + copied := set.NewSet[ids.NodeID](len(p.connectedValidators)) + copied.Union(p.connectedValidators) + return copied +} diff --git a/snow/networking/handler/health.go b/snow/networking/handler/health.go index 3f4af4299d1c..0dbcb844fb95 100644 --- a/snow/networking/handler/health.go +++ b/snow/networking/handler/health.go @@ -7,6 +7,9 @@ import ( "context" "errors" "fmt" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/utils/set" ) var ErrNotConnectedEnoughStake = errors.New("not connected to enough stake") @@ -39,8 +42,9 @@ func (h *handler) HealthCheck(ctx context.Context) (interface{}, error) { func (h *handler) networkHealthCheck() (interface{}, error) { percentConnected := h.peerTracker.ConnectedPercent() - details := map[string]float64{ - "percentConnected": percentConnected, + details := map[string]interface{}{ + "percentConnected": percentConnected, + "disconnectedValidators": h.getDisconnectedValidators(), } var err error @@ -56,3 +60,11 @@ func (h *handler) networkHealthCheck() (interface{}, error) { return details, err } + +func (h *handler) getDisconnectedValidators() set.Set[ids.NodeID] { + vdrs := h.peerTracker.GetValidators() + connectedVdrs := h.peerTracker.ConnectedValidators() + // vdrs - connectedVdrs is equal to the disconnectedVdrs + vdrs.Difference(connectedVdrs) + return vdrs +} diff --git a/snow/networking/handler/health_test.go b/snow/networking/handler/health_test.go index f37b5f551a6d..4e27a786dc1b 100644 --- a/snow/networking/handler/health_test.go +++ b/snow/networking/handler/health_test.go @@ -136,8 +136,8 @@ func TestHealthCheckSubnet(t *testing.T) { require.NoError(vdrs.AddStaker(ctx.SubnetID, vdrID, nil, ids.Empty, 100)) } - - for index, nodeID := range vdrIDs.List() { + vdrIDsList := vdrIDs.List() + for index, nodeID := range vdrIDsList { require.NoError(peerTracker.Connected(context.Background(), nodeID, nil)) details, err := handlerIntf.HealthCheck(context.Background()) @@ -152,13 +152,13 @@ func TestHealthCheckSubnet(t *testing.T) { detailsMap, ok := details.(map[string]interface{}) require.True(ok) - networkingMap, ok := detailsMap["networking"] - require.True(ok) - networkingDetails, ok := networkingMap.(map[string]float64) - require.True(ok) - percentConnected, ok := networkingDetails["percentConnected"] - require.True(ok) - require.Equal(expectedPercentConnected, percentConnected) + require.Equal( + map[string]interface{}{ + "percentConnected": expectedPercentConnected, + "disconnectedValidators": set.Of(vdrIDsList[index+1:]...), + }, + detailsMap["networking"], + ) } }) } From e8c257f4d10dea1e8b2ccd9df0bcc17af48dbb00 Mon Sep 17 00:00:00 2001 From: yacovm Date: Thu, 29 Aug 2024 23:43:19 +0200 Subject: [PATCH 55/69] Print type of message sent in the verbose log (#3348) Signed-off-by: Yacov Manevich Signed-off-by: yacovm Co-authored-by: Stephen Buttolph --- network/peer/peer.go | 1 + 1 file changed, 1 insertion(+) diff --git a/network/peer/peer.go b/network/peer/peer.go index c424c1fbdccd..fb4b3904167a 100644 --- a/network/peer/peer.go +++ b/network/peer/peer.go @@ -594,6 +594,7 @@ func (p *peer) writeMessages() { func (p *peer) writeMessage(writer io.Writer, msg message.OutboundMessage) { msgBytes := msg.Bytes() p.Log.Verbo("sending message", + zap.Stringer("op", msg.Op()), zap.Stringer("nodeID", p.id), zap.Binary("messageBytes", msgBytes), ) From 9b03425729c00c6a1f38730a227f4b91ae586635 Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Mon, 2 Sep 2024 23:10:20 +0300 Subject: [PATCH 56/69] Remove local chain config from e2e test (#3293) Signed-off-by: Ceyhun Onur Signed-off-by: Ceyhun Onur Co-authored-by: Stephen Buttolph Co-authored-by: Darioush Jalali --- go.mod | 2 +- go.sum | 4 ++-- scripts/tests.upgrade.sh | 4 ++-- tests/fixture/tmpnet/genesis.go | 8 +++++--- tests/upgrade/upgrade_test.go | 34 ++++++++++++++++----------------- 5 files changed, 26 insertions(+), 26 deletions(-) diff --git a/go.mod b/go.mod index f847fee1dd8f..30476015824e 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/DataDog/zstd v1.5.2 github.com/NYTimes/gziphandler v1.1.1 github.com/antithesishq/antithesis-sdk-go v0.3.8 - github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240813194342-7635a96aa180 + github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240815193440-a96bc921e732 github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95 github.com/btcsuite/btcd/btcutil v1.1.3 github.com/cockroachdb/pebble v0.0.0-20230928194634-aa077af62593 diff --git a/go.sum b/go.sum index 5881b9005f47..8b4a35ca4d07 100644 --- a/go.sum +++ b/go.sum @@ -62,8 +62,8 @@ github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax github.com/antithesishq/antithesis-sdk-go v0.3.8 h1:OvGoHxIcOXFJLyn9IJQ5DzByZ3YVAWNBc394ObzDRb8= github.com/antithesishq/antithesis-sdk-go v0.3.8/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= -github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240813194342-7635a96aa180 h1:6aIHp7wbyGVYdhHVQUbG7BEcbCMEQ5SYopPPJyipyvk= -github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240813194342-7635a96aa180/go.mod h1:/wNBVq7J7wlC2Kbov7kk6LV5xZvau7VF9zwTVOeyAjY= +github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240815193440-a96bc921e732 h1:wlhGJbmb7s3bU2QWtxKjscGjfHknQiq+cVhhUjONsB8= +github.com/ava-labs/coreth v0.13.8-fixed-genesis-upgrade.0.20240815193440-a96bc921e732/go.mod h1:RkQLaQ961Xe/sUb3ycn4Qi18vPPuEetTqDf2eDcquAs= github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95 h1:dOVbtdnZL++pENdTCNZ1nu41eYDQkTML4sWebDnnq8c= github.com/ava-labs/ledger-avalanche/go v0.0.0-20240610153809-9c955cc90a95/go.mod h1:pJxaT9bUgeRNVmNRgtCHb7sFDIRKy7CzTQVi8gGNT6g= github.com/aymerick/raymond v2.0.3-0.20180322193309-b565731e1464+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= diff --git a/scripts/tests.upgrade.sh b/scripts/tests.upgrade.sh index 8cc158d87d49..5ca8a0f1a24d 100755 --- a/scripts/tests.upgrade.sh +++ b/scripts/tests.upgrade.sh @@ -16,8 +16,8 @@ fi # local network, this flag must be updated to the last compatible # version with the latest code. # -# v1.11.0 activates Durango. -DEFAULT_VERSION="1.11.0" +# v1.11.3 fixes a regression in Coreth genesis for custom networks. +DEFAULT_VERSION="1.11.3" VERSION="${1:-${DEFAULT_VERSION}}" if [[ -z "${VERSION}" ]]; then diff --git a/tests/fixture/tmpnet/genesis.go b/tests/fixture/tmpnet/genesis.go index aa308be6ee71..c914c9b94e9b 100644 --- a/tests/fixture/tmpnet/genesis.go +++ b/tests/fixture/tmpnet/genesis.go @@ -147,11 +147,13 @@ func NewTestGenesis( ) } + chainID := big.NewInt(int64(networkID)) // Define C-Chain genesis cChainGenesis := &core.Genesis{ - Config: params.AvalancheLocalChainConfig, - Difficulty: big.NewInt(0), // Difficulty is a mandatory field - Timestamp: uint64(upgrade.InitiallyActiveTime.Unix()), // This time enables Avalanche upgrades by default + // TODO: remove this after Etna and set only the chainID + Config: params.GetChainConfig(upgrade.Default, chainID), // upgrade will be again set by VM according to the snow.Context + Difficulty: big.NewInt(0), // Difficulty is a mandatory field + Timestamp: uint64(upgrade.InitiallyActiveTime.Unix()), // This time enables Avalanche upgrades by default GasLimit: defaultGasLimit, Alloc: cChainBalances, } diff --git a/tests/upgrade/upgrade_test.go b/tests/upgrade/upgrade_test.go index de8f292a1d1a..48bcc8b57c9d 100644 --- a/tests/upgrade/upgrade_test.go +++ b/tests/upgrade/upgrade_test.go @@ -4,18 +4,19 @@ package upgrade import ( + "encoding/base64" "encoding/json" "flag" "fmt" "testing" - "github.com/ava-labs/coreth/core" "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/config" "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" - "github.com/ava-labs/avalanchego/upgrade" + "github.com/ava-labs/avalanchego/upgrade/upgradetest" ) func TestUpgrade(t *testing.T) { @@ -49,23 +50,20 @@ var _ = ginkgo.Describe("[Upgrade]", func() { ginkgo.It("can upgrade versions", func() { network := tmpnet.NewDefaultNetwork("avalanchego-upgrade") - { - // Get the default genesis so we can modify it - genesis, err := network.DefaultGenesis() - require.NoError(err) - network.Genesis = genesis - // Etna enables Cancun which modifies the outcome of the C-Chain genesis - // This is because of new header fields that modify the genesis block hash. - // This code can be removed once the Etna upgrade is activated. - cChainGenesis := new(core.Genesis) - cChainGenesisStr := network.Genesis.CChainGenesis - require.NoError(json.Unmarshal([]byte(cChainGenesisStr), cChainGenesis)) - unscheduledActivationTime := uint64(upgrade.UnscheduledActivationTime.Unix()) - cChainGenesis.Config.EtnaTime = &unscheduledActivationTime - cChainGenesisBytes, err := json.Marshal(cChainGenesis) - require.NoError(err) - network.Genesis.CChainGenesis = string(cChainGenesisBytes) + // Get the default genesis so we can modify it + genesis, err := network.DefaultGenesis() + require.NoError(err) + network.Genesis = genesis + + // Configure network upgrade flag + latestUnscheduled := upgradetest.GetConfig(upgradetest.Latest - 1) + upgradeJSON, err := json.Marshal(latestUnscheduled) + require.NoError(err) + upgradeBase64 := base64.StdEncoding.EncodeToString(upgradeJSON) + if network.DefaultFlags == nil { + network.DefaultFlags = tmpnet.FlagsMap{} } + network.DefaultFlags[config.UpgradeFileContentKey] = upgradeBase64 e2e.StartNetwork(tc, network, avalancheGoExecPath, "" /* pluginDir */, 0 /* shutdownDelay */, false /* reuseNetwork */) From 9cbcc7c2d3f0a05bb61b067de9cecdb32fe9d078 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 3 Sep 2024 10:51:53 -0400 Subject: [PATCH 57/69] Separate codec registries by upgrade (#3353) --- vms/platformvm/block/codec.go | 27 +++++++++++++++++---------- vms/platformvm/txs/codec.go | 31 ++++++++++++++++++------------- 2 files changed, 35 insertions(+), 23 deletions(-) diff --git a/vms/platformvm/block/codec.go b/vms/platformvm/block/codec.go index dbb446161fb5..56b3590dcdc4 100644 --- a/vms/platformvm/block/codec.go +++ b/vms/platformvm/block/codec.go @@ -32,10 +32,9 @@ func init() { errs := wrappers.Errs{} for _, c := range []linearcodec.Codec{c, gc} { errs.Add( - RegisterApricotBlockTypes(c), - txs.RegisterUnsignedTxsTypes(c), - RegisterBanffBlockTypes(c), - txs.RegisterDurangoUnsignedTxsTypes(c), + RegisterApricotTypes(c), + RegisterBanffTypes(c), + RegisterDurangoTypes(c), ) } @@ -50,25 +49,33 @@ func init() { } } -// RegisterApricotBlockTypes allows registering relevant type of blocks package -// in the right sequence. Following repackaging of platformvm package, a few -// subpackage-level codecs were introduced, each handling serialization of -// specific types. -func RegisterApricotBlockTypes(targetCodec codec.Registry) error { +// RegisterApricotTypes registers the type information for blocks that were +// valid during the Apricot series of upgrades. +func RegisterApricotTypes(targetCodec linearcodec.Codec) error { return errors.Join( targetCodec.RegisterType(&ApricotProposalBlock{}), targetCodec.RegisterType(&ApricotAbortBlock{}), targetCodec.RegisterType(&ApricotCommitBlock{}), targetCodec.RegisterType(&ApricotStandardBlock{}), targetCodec.RegisterType(&ApricotAtomicBlock{}), + txs.RegisterApricotTypes(targetCodec), ) } -func RegisterBanffBlockTypes(targetCodec codec.Registry) error { +// RegisterBanffTypes registers the type information for blocks that were valid +// during the Banff series of upgrades. +func RegisterBanffTypes(targetCodec linearcodec.Codec) error { return errors.Join( + txs.RegisterBanffTypes(targetCodec), targetCodec.RegisterType(&BanffProposalBlock{}), targetCodec.RegisterType(&BanffAbortBlock{}), targetCodec.RegisterType(&BanffCommitBlock{}), targetCodec.RegisterType(&BanffStandardBlock{}), ) } + +// RegisterDurangoTypes registers the type information for blocks that were +// valid during the Durango series of upgrades. +func RegisterDurangoTypes(targetCodec linearcodec.Codec) error { + return txs.RegisterDurangoTypes(targetCodec) +} diff --git a/vms/platformvm/txs/codec.go b/vms/platformvm/txs/codec.go index 8fa09606897f..33c1b563392b 100644 --- a/vms/platformvm/txs/codec.go +++ b/vms/platformvm/txs/codec.go @@ -38,11 +38,14 @@ func init() { // we skip positions for the blocks. c.SkipRegistrations(5) - errs.Add(RegisterUnsignedTxsTypes(c)) + errs.Add( + RegisterApricotTypes(c), + RegisterBanffTypes(c), + ) c.SkipRegistrations(4) - errs.Add(RegisterDurangoUnsignedTxsTypes(c)) + errs.Add(RegisterDurangoTypes(c)) } Codec = codec.NewDefaultManager() @@ -56,14 +59,9 @@ func init() { } } -// RegisterUnsignedTxsTypes allows registering relevant type of unsigned package -// in the right sequence. Following repackaging of platformvm package, a few -// subpackage-level codecs were introduced, each handling serialization of -// specific types. -// -// RegisterUnsignedTxsTypes is made exportable so to guarantee that other codecs -// are coherent with components one. -func RegisterUnsignedTxsTypes(targetCodec linearcodec.Codec) error { +// RegisterApricotTypes registers the type information for transactions that +// were valid during the Apricot series of upgrades. +func RegisterApricotTypes(targetCodec linearcodec.Codec) error { errs := wrappers.Errs{} // The secp256k1fx is registered here because this is the same place it is @@ -90,8 +88,14 @@ func RegisterUnsignedTxsTypes(targetCodec linearcodec.Codec) error { targetCodec.RegisterType(&stakeable.LockIn{}), targetCodec.RegisterType(&stakeable.LockOut{}), + ) + return errs.Err +} - // Banff additions: +// RegisterBanffTypes registers the type information for transactions that were +// valid during the Banff series of upgrades. +func RegisterBanffTypes(targetCodec linearcodec.Codec) error { + return errors.Join( targetCodec.RegisterType(&RemoveSubnetValidatorTx{}), targetCodec.RegisterType(&TransformSubnetTx{}), targetCodec.RegisterType(&AddPermissionlessValidatorTx{}), @@ -100,10 +104,11 @@ func RegisterUnsignedTxsTypes(targetCodec linearcodec.Codec) error { targetCodec.RegisterType(&signer.Empty{}), targetCodec.RegisterType(&signer.ProofOfPossession{}), ) - return errs.Err } -func RegisterDurangoUnsignedTxsTypes(targetCodec linearcodec.Codec) error { +// RegisterDurangoTypes registers the type information for transactions that +// were valid during the Durango series of upgrades. +func RegisterDurangoTypes(targetCodec linearcodec.Codec) error { return errors.Join( targetCodec.RegisterType(&TransferSubnetOwnershipTx{}), targetCodec.RegisterType(&BaseTx{}), From 833b3a0c8dbe7df87f901ce4dcd988659fad1f13 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 3 Sep 2024 11:06:32 -0400 Subject: [PATCH 58/69] Support unmarshalling of json byte slices (#3354) --- vms/avm/service_test.go | 16 +++++----- vms/platformvm/service_test.go | 4 +++ vms/types/blob_data.go | 23 ++++++++++++++ vms/types/blob_data_test.go | 56 ++++++++++++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 8 deletions(-) create mode 100644 vms/types/blob_data_test.go diff --git a/vms/avm/service_test.go b/vms/avm/service_test.go index 6f44e469a75e..c6e20c6ecb51 100644 --- a/vms/avm/service_test.go +++ b/vms/avm/service_test.go @@ -660,7 +660,7 @@ func TestServiceGetTxJSON_ExportTx(t *testing.T) { } } ], - "memo": "0x", + "memo": null, "destinationChain": "2mcwQKiD8VEspmMJpL1dc7okQQ5dDVAWeCBZ7FWBFAbxpv3t7w", "exportedOutputs": [ { @@ -800,7 +800,7 @@ func TestServiceGetTxJSON_CreateAssetTx(t *testing.T) { } } ], - "memo": "0x", + "memo": null, "name": "Team Rocket", "symbol": "TR", "denomination": 0, @@ -972,7 +972,7 @@ func TestServiceGetTxJSON_OperationTxWithNftxMintOp(t *testing.T) { } } ], - "memo": "0x", + "memo": null, "operations": [ { "assetID": %[4]q, @@ -1117,7 +1117,7 @@ func TestServiceGetTxJSON_OperationTxWithMultipleNftxMintOp(t *testing.T) { } } ], - "memo": "0x", + "memo": null, "operations": [ { "assetID": %[4]q, @@ -1292,7 +1292,7 @@ func TestServiceGetTxJSON_OperationTxWithSecpMintOp(t *testing.T) { } } ], - "memo": "0x", + "memo": null, "operations": [ { "assetID": %[4]q, @@ -1439,7 +1439,7 @@ func TestServiceGetTxJSON_OperationTxWithMultipleSecpMintOp(t *testing.T) { } } ], - "memo": "0x", + "memo": null, "operations": [ { "assetID": %[4]q, @@ -1617,7 +1617,7 @@ func TestServiceGetTxJSON_OperationTxWithPropertyFxMintOp(t *testing.T) { } } ], - "memo": "0x", + "memo": null, "operations": [ { "assetID": %[4]q, @@ -1759,7 +1759,7 @@ func TestServiceGetTxJSON_OperationTxWithPropertyFxMintOpMultiple(t *testing.T) } } ], - "memo": "0x", + "memo": null, "operations": [ { "assetID": %[4]q, diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index c896066142e6..7b3252c140e3 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -234,6 +234,7 @@ func TestGetTx(t *testing.T) { constants.AVMID, []ids.ID{}, "chain name", + common.WithMemo([]byte{}), ) require.NoError(t, err) return tx @@ -266,6 +267,7 @@ func TestGetTx(t *testing.T) { rewardsOwner, rewardsOwner, 0, + common.WithMemo([]byte{}), ) require.NoError(t, err) return tx @@ -289,6 +291,7 @@ func TestGetTx(t *testing.T) { }, }, }}, + common.WithMemo([]byte{}), ) require.NoError(t, err) return tx @@ -792,6 +795,7 @@ func TestGetBlock(t *testing.T) { constants.AVMID, []ids.ID{}, "chain name", + common.WithMemo([]byte{}), ) require.NoError(err) diff --git a/vms/types/blob_data.go b/vms/types/blob_data.go index cee4fe7ba4d8..155d6a29d7e0 100644 --- a/vms/types/blob_data.go +++ b/vms/types/blob_data.go @@ -9,13 +9,36 @@ import ( "github.com/ava-labs/avalanchego/utils/formatting" ) +const nullStr = "null" + // JSONByteSlice represents [[]byte] that is json marshalled to hex type JSONByteSlice []byte func (b JSONByteSlice) MarshalJSON() ([]byte, error) { + if b == nil { + return []byte(nullStr), nil + } + hexData, err := formatting.Encode(formatting.HexNC, b) if err != nil { return nil, err } return json.Marshal(hexData) } + +func (b *JSONByteSlice) UnmarshalJSON(jsonBytes []byte) error { + if string(jsonBytes) == nullStr { + return nil + } + + var hexData string + if err := json.Unmarshal(jsonBytes, &hexData); err != nil { + return err + } + v, err := formatting.Decode(formatting.HexNC, hexData) + if err != nil { + return err + } + *b = v + return nil +} diff --git a/vms/types/blob_data_test.go b/vms/types/blob_data_test.go new file mode 100644 index 000000000000..82c692a9468e --- /dev/null +++ b/vms/types/blob_data_test.go @@ -0,0 +1,56 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package types + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestJSON(t *testing.T) { + tests := []struct { + name string + value JSONByteSlice + expectedJSON string + }{ + { + name: "nil", + value: nil, + expectedJSON: nullStr, + }, + { + name: "empty", + value: []byte{}, + expectedJSON: `"0x"`, + }, + { + name: "not empty", + value: []byte{0, 1, 2, 3}, + expectedJSON: `"0x00010203"`, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + jsonBytes, err := json.Marshal(test.value) + require.NoError(err) + require.Equal(test.expectedJSON, string(jsonBytes)) + + var unmarshaled JSONByteSlice + require.NoError(json.Unmarshal(jsonBytes, &unmarshaled)) + require.Equal(test.value, unmarshaled) + }) + } +} + +func TestUnmarshalJSONNullKeepsInitialValue(t *testing.T) { + require := require.New(t) + + unmarshaled := JSONByteSlice{1, 2, 3} + require.NoError(json.Unmarshal([]byte(nullStr), &unmarshaled)) + require.Equal(JSONByteSlice{1, 2, 3}, unmarshaled) +} From 17ece5d6410d36b8a1ee8a31d7e8abfc7dca0bb9 Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 3 Sep 2024 14:10:26 -0400 Subject: [PATCH 59/69] Add explicit p-chain current validator check in AddValidator (#3355) --- vms/platformvm/block/builder/builder_test.go | 8 +-- vms/platformvm/block/executor/helpers_test.go | 2 +- .../block/executor/proposal_block_test.go | 24 +++---- .../block/executor/standard_block_test.go | 8 +-- vms/platformvm/service_test.go | 2 +- vms/platformvm/state/diff.go | 16 +++-- vms/platformvm/state/diff_test.go | 4 +- vms/platformvm/state/mock_chain.go | 12 ++-- vms/platformvm/state/mock_diff.go | 12 ++-- vms/platformvm/state/mock_state.go | 12 ++-- vms/platformvm/state/stakers.go | 17 ++++- vms/platformvm/state/stakers_test.go | 4 +- vms/platformvm/state/state.go | 10 ++- vms/platformvm/state/state_test.go | 18 ++--- .../txs/executor/advance_time_test.go | 10 +-- .../txs/executor/proposal_tx_executor.go | 8 ++- .../txs/executor/proposal_tx_executor_test.go | 12 ++-- .../txs/executor/reward_validator_test.go | 8 +-- .../txs/executor/standard_tx_executor.go | 8 ++- .../txs/executor/standard_tx_executor_test.go | 14 ++-- vms/platformvm/txs/executor/state_changes.go | 8 ++- .../validators/manager_benchmark_test.go | 12 ++-- vms/platformvm/vm_regression_test.go | 69 +++++++++++++++++++ 23 files changed, 207 insertions(+), 91 deletions(-) diff --git a/vms/platformvm/block/builder/builder_test.go b/vms/platformvm/block/builder/builder_test.go index e691c6f6ce2e..1a056fb4b905 100644 --- a/vms/platformvm/block/builder/builder_test.go +++ b/vms/platformvm/block/builder/builder_test.go @@ -221,10 +221,10 @@ func TestBuildBlockAdvanceTime(t *testing.T) { ) // Add a staker to [env.state] - env.state.PutCurrentValidator(&state.Staker{ + require.NoError(env.state.PutCurrentValidator(&state.Staker{ NextTime: nextTime, Priority: txs.PrimaryNetworkValidatorCurrentPriority, - }) + })) // Advance wall clock to [nextTime] env.backend.Clk.Set(nextTime) @@ -278,10 +278,10 @@ func TestBuildBlockForceAdvanceTime(t *testing.T) { ) // Add a staker to [env.state] - env.state.PutCurrentValidator(&state.Staker{ + require.NoError(env.state.PutCurrentValidator(&state.Staker{ NextTime: nextTime, Priority: txs.PrimaryNetworkValidatorCurrentPriority, - }) + })) // Advance wall clock to [nextTime] + [txexecutor.SyncBound] env.backend.Clk.Set(nextTime.Add(txexecutor.SyncBound)) diff --git a/vms/platformvm/block/executor/helpers_test.go b/vms/platformvm/block/executor/helpers_test.go index f066b1fc13c7..b11e4714c885 100644 --- a/vms/platformvm/block/executor/helpers_test.go +++ b/vms/platformvm/block/executor/helpers_test.go @@ -378,7 +378,7 @@ func addPendingValidator( ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(addValidatorTx, status.Committed) env.state.SetHeight(1) require.NoError(env.state.Commit()) diff --git a/vms/platformvm/block/executor/proposal_block_test.go b/vms/platformvm/block/executor/proposal_block_test.go index 397802cf0faa..a1c5151044d5 100644 --- a/vms/platformvm/block/executor/proposal_block_test.go +++ b/vms/platformvm/block/executor/proposal_block_test.go @@ -543,7 +543,7 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) require.NoError(env.state.Commit()) } @@ -572,7 +572,7 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(subnetStaker) + require.NoError(env.state.PutPendingValidator(subnetStaker)) env.state.AddTx(tx, status.Committed) require.NoError(env.state.Commit()) } @@ -611,7 +611,7 @@ func TestBanffProposalBlockUpdateStakers(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker0) + require.NoError(env.state.PutCurrentValidator(staker0)) env.state.AddTx(addStaker0, status.Committed) require.NoError(env.state.Commit()) @@ -714,7 +714,7 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) require.NoError(env.state.Commit()) @@ -741,7 +741,7 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) require.NoError(env.state.Commit()) @@ -782,7 +782,7 @@ func TestBanffProposalBlockRemoveSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(addStaker0, status.Committed) require.NoError(env.state.Commit()) @@ -867,7 +867,7 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) require.NoError(env.state.Commit()) @@ -904,7 +904,7 @@ func TestBanffProposalBlockTrackedSubnet(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(addStaker0, status.Committed) require.NoError(env.state.Commit()) @@ -996,7 +996,7 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(addStaker0, status.Committed) require.NoError(env.state.Commit()) @@ -1085,7 +1085,7 @@ func TestBanffProposalBlockDelegatorStakerWeight(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(addStaker0, status.Committed) require.NoError(env.state.Commit()) @@ -1181,7 +1181,7 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(addStaker0, status.Committed) require.NoError(env.state.Commit()) @@ -1270,7 +1270,7 @@ func TestBanffProposalBlockDelegatorStakers(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(addStaker0, status.Committed) require.NoError(env.state.Commit()) diff --git a/vms/platformvm/block/executor/standard_block_test.go b/vms/platformvm/block/executor/standard_block_test.go index 15cc43cdad93..7c31ccb7f253 100644 --- a/vms/platformvm/block/executor/standard_block_test.go +++ b/vms/platformvm/block/executor/standard_block_test.go @@ -534,7 +534,7 @@ func TestBanffStandardBlockUpdateStakers(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) } env.state.SetHeight( /*dummyHeight*/ 1) @@ -631,7 +631,7 @@ func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) require.NoError(env.state.Commit()) @@ -658,7 +658,7 @@ func TestBanffStandardBlockRemoveSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) require.NoError(env.state.Commit()) @@ -733,7 +733,7 @@ func TestBanffStandardBlockTrackedSubnet(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) require.NoError(env.state.Commit()) diff --git a/vms/platformvm/service_test.go b/vms/platformvm/service_test.go index 7b3252c140e3..9454de534558 100644 --- a/vms/platformvm/service_test.go +++ b/vms/platformvm/service_test.go @@ -582,7 +582,7 @@ func TestGetStake(t *testing.T) { ) require.NoError(err) - service.vm.state.PutPendingValidator(staker) + require.NoError(service.vm.state.PutPendingValidator(staker)) service.vm.state.AddTx(tx, status.Committed) require.NoError(service.vm.state.Commit()) diff --git a/vms/platformvm/state/diff.go b/vms/platformvm/state/diff.go index 66477823673a..16f7edf4435b 100644 --- a/vms/platformvm/state/diff.go +++ b/vms/platformvm/state/diff.go @@ -180,8 +180,8 @@ func (d *diff) GetDelegateeReward(subnetID ids.ID, nodeID ids.NodeID) (uint64, e return parentState.GetDelegateeReward(subnetID, nodeID) } -func (d *diff) PutCurrentValidator(staker *Staker) { - d.currentStakerDiffs.PutValidator(staker) +func (d *diff) PutCurrentValidator(staker *Staker) error { + return d.currentStakerDiffs.PutValidator(staker) } func (d *diff) DeleteCurrentValidator(staker *Staker) { @@ -243,8 +243,8 @@ func (d *diff) GetPendingValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, } } -func (d *diff) PutPendingValidator(staker *Staker) { - d.pendingStakerDiffs.PutValidator(staker) +func (d *diff) PutPendingValidator(staker *Staker) error { + return d.pendingStakerDiffs.PutValidator(staker) } func (d *diff) DeletePendingValidator(staker *Staker) { @@ -444,7 +444,9 @@ func (d *diff) Apply(baseState Chain) error { for _, validatorDiff := range subnetValidatorDiffs { switch validatorDiff.validatorStatus { case added: - baseState.PutCurrentValidator(validatorDiff.validator) + if err := baseState.PutCurrentValidator(validatorDiff.validator); err != nil { + return err + } case deleted: baseState.DeleteCurrentValidator(validatorDiff.validator) } @@ -471,7 +473,9 @@ func (d *diff) Apply(baseState Chain) error { for _, validatorDiff := range subnetValidatorDiffs { switch validatorDiff.validatorStatus { case added: - baseState.PutPendingValidator(validatorDiff.validator) + if err := baseState.PutPendingValidator(validatorDiff.validator); err != nil { + return err + } case deleted: baseState.DeletePendingValidator(validatorDiff.validator) } diff --git a/vms/platformvm/state/diff_test.go b/vms/platformvm/state/diff_test.go index 82525e087593..56ff3bc8ac8b 100644 --- a/vms/platformvm/state/diff_test.go +++ b/vms/platformvm/state/diff_test.go @@ -111,7 +111,7 @@ func TestDiffCurrentValidator(t *testing.T) { SubnetID: ids.GenerateTestID(), NodeID: ids.GenerateTestNodeID(), } - d.PutCurrentValidator(currentValidator) + require.NoError(d.PutCurrentValidator(currentValidator)) // Assert that we get the current validator back gotCurrentValidator, err := d.GetCurrentValidator(currentValidator.SubnetID, currentValidator.NodeID) @@ -145,7 +145,7 @@ func TestDiffPendingValidator(t *testing.T) { SubnetID: ids.GenerateTestID(), NodeID: ids.GenerateTestNodeID(), } - d.PutPendingValidator(pendingValidator) + require.NoError(d.PutPendingValidator(pendingValidator)) // Assert that we get the pending validator back gotPendingValidator, err := d.GetPendingValidator(pendingValidator.SubnetID, pendingValidator.NodeID) diff --git a/vms/platformvm/state/mock_chain.go b/vms/platformvm/state/mock_chain.go index 13adc2d2cc86..727847a7c07f 100644 --- a/vms/platformvm/state/mock_chain.go +++ b/vms/platformvm/state/mock_chain.go @@ -416,9 +416,11 @@ func (mr *MockChainMockRecorder) PutCurrentDelegator(staker any) *gomock.Call { } // PutCurrentValidator mocks base method. -func (m *MockChain) PutCurrentValidator(staker *Staker) { +func (m *MockChain) PutCurrentValidator(staker *Staker) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentValidator", staker) + ret := m.ctrl.Call(m, "PutCurrentValidator", staker) + ret0, _ := ret[0].(error) + return ret0 } // PutCurrentValidator indicates an expected call of PutCurrentValidator. @@ -440,9 +442,11 @@ func (mr *MockChainMockRecorder) PutPendingDelegator(staker any) *gomock.Call { } // PutPendingValidator mocks base method. -func (m *MockChain) PutPendingValidator(staker *Staker) { +func (m *MockChain) PutPendingValidator(staker *Staker) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingValidator", staker) + ret := m.ctrl.Call(m, "PutPendingValidator", staker) + ret0, _ := ret[0].(error) + return ret0 } // PutPendingValidator indicates an expected call of PutPendingValidator. diff --git a/vms/platformvm/state/mock_diff.go b/vms/platformvm/state/mock_diff.go index 8bfd09c44d9c..ccf6619b5b24 100644 --- a/vms/platformvm/state/mock_diff.go +++ b/vms/platformvm/state/mock_diff.go @@ -430,9 +430,11 @@ func (mr *MockDiffMockRecorder) PutCurrentDelegator(staker any) *gomock.Call { } // PutCurrentValidator mocks base method. -func (m *MockDiff) PutCurrentValidator(staker *Staker) { +func (m *MockDiff) PutCurrentValidator(staker *Staker) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentValidator", staker) + ret := m.ctrl.Call(m, "PutCurrentValidator", staker) + ret0, _ := ret[0].(error) + return ret0 } // PutCurrentValidator indicates an expected call of PutCurrentValidator. @@ -454,9 +456,11 @@ func (mr *MockDiffMockRecorder) PutPendingDelegator(staker any) *gomock.Call { } // PutPendingValidator mocks base method. -func (m *MockDiff) PutPendingValidator(staker *Staker) { +func (m *MockDiff) PutPendingValidator(staker *Staker) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingValidator", staker) + ret := m.ctrl.Call(m, "PutPendingValidator", staker) + ret0, _ := ret[0].(error) + return ret0 } // PutPendingValidator indicates an expected call of PutPendingValidator. diff --git a/vms/platformvm/state/mock_state.go b/vms/platformvm/state/mock_state.go index 9bc07c2333fe..527db5cf8a53 100644 --- a/vms/platformvm/state/mock_state.go +++ b/vms/platformvm/state/mock_state.go @@ -651,9 +651,11 @@ func (mr *MockStateMockRecorder) PutCurrentDelegator(staker any) *gomock.Call { } // PutCurrentValidator mocks base method. -func (m *MockState) PutCurrentValidator(staker *Staker) { +func (m *MockState) PutCurrentValidator(staker *Staker) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutCurrentValidator", staker) + ret := m.ctrl.Call(m, "PutCurrentValidator", staker) + ret0, _ := ret[0].(error) + return ret0 } // PutCurrentValidator indicates an expected call of PutCurrentValidator. @@ -675,9 +677,11 @@ func (mr *MockStateMockRecorder) PutPendingDelegator(staker any) *gomock.Call { } // PutPendingValidator mocks base method. -func (m *MockState) PutPendingValidator(staker *Staker) { +func (m *MockState) PutPendingValidator(staker *Staker) error { m.ctrl.T.Helper() - m.ctrl.Call(m, "PutPendingValidator", staker) + ret := m.ctrl.Call(m, "PutPendingValidator", staker) + ret0, _ := ret[0].(error) + return ret0 } // PutPendingValidator indicates an expected call of PutPendingValidator. diff --git a/vms/platformvm/state/stakers.go b/vms/platformvm/state/stakers.go index c39d84d48d02..658796855958 100644 --- a/vms/platformvm/state/stakers.go +++ b/vms/platformvm/state/stakers.go @@ -4,6 +4,8 @@ package state import ( + "errors" + "github.com/google/btree" "github.com/ava-labs/avalanchego/database" @@ -11,6 +13,8 @@ import ( "github.com/ava-labs/avalanchego/utils/iterator" ) +var ErrAddingStakerAfterDeletion = errors.New("attempted to add a staker after deleting it") + type Stakers interface { CurrentStakers PendingStakers @@ -26,7 +30,7 @@ type CurrentStakers interface { // staker set. // // Invariant: [staker] is not currently a CurrentValidator - PutCurrentValidator(staker *Staker) + PutCurrentValidator(staker *Staker) error // DeleteCurrentValidator removes the [staker] describing a validator from // the staker set. @@ -72,7 +76,7 @@ type PendingStakers interface { // PutPendingValidator adds the [staker] describing a validator to the // staker set. - PutPendingValidator(staker *Staker) + PutPendingValidator(staker *Staker) error // DeletePendingValidator removes the [staker] describing a validator from // the staker set. @@ -289,8 +293,14 @@ func (s *diffStakers) GetValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker, return nil, validatorDiff.validatorStatus } -func (s *diffStakers) PutValidator(staker *Staker) { +func (s *diffStakers) PutValidator(staker *Staker) error { validatorDiff := s.getOrCreateDiff(staker.SubnetID, staker.NodeID) + if validatorDiff.validatorStatus == deleted { + // Enforce the invariant that a validator cannot be added after being + // deleted. + return ErrAddingStakerAfterDeletion + } + validatorDiff.validatorStatus = added validatorDiff.validator = staker @@ -298,6 +308,7 @@ func (s *diffStakers) PutValidator(staker *Staker) { s.addedStakers = btree.NewG(defaultTreeDegree, (*Staker).Less) } s.addedStakers.ReplaceOrInsert(staker) + return nil } func (s *diffStakers) DeleteValidator(staker *Staker) { diff --git a/vms/platformvm/state/stakers_test.go b/vms/platformvm/state/stakers_test.go index e4ae2aa840c5..d536b2a719d8 100644 --- a/vms/platformvm/state/stakers_test.go +++ b/vms/platformvm/state/stakers_test.go @@ -162,7 +162,7 @@ func TestDiffStakersValidator(t *testing.T) { stakerIterator := v.GetStakerIterator(iterator.Empty[*Staker]{}) assertIteratorsEqual(t, iterator.FromSlice(delegator), stakerIterator) - v.PutValidator(staker) + require.NoError(v.PutValidator(staker)) returnedStaker, status := v.GetValidator(staker.SubnetID, staker.NodeID) require.Equal(added, status) @@ -203,7 +203,7 @@ func TestDiffStakersDelegator(t *testing.T) { v := diffStakers{} - v.PutValidator(staker) + require.NoError(t, v.PutValidator(staker)) delegatorIterator := v.GetDelegatorIterator(iterator.Empty[*Staker]{}, ids.GenerateTestID(), delegator.NodeID) assertIteratorsEqual(t, iterator.Empty[*Staker]{}, delegatorIterator) diff --git a/vms/platformvm/state/state.go b/vms/platformvm/state/state.go index 17a5e83bd28f..b5288df75140 100644 --- a/vms/platformvm/state/state.go +++ b/vms/platformvm/state/state.go @@ -682,8 +682,9 @@ func (s *state) GetCurrentValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker return s.currentStakers.GetValidator(subnetID, nodeID) } -func (s *state) PutCurrentValidator(staker *Staker) { +func (s *state) PutCurrentValidator(staker *Staker) error { s.currentStakers.PutValidator(staker) + return nil } func (s *state) DeleteCurrentValidator(staker *Staker) { @@ -710,8 +711,9 @@ func (s *state) GetPendingValidator(subnetID ids.ID, nodeID ids.NodeID) (*Staker return s.pendingStakers.GetValidator(subnetID, nodeID) } -func (s *state) PutPendingValidator(staker *Staker) { +func (s *state) PutPendingValidator(staker *Staker) error { s.pendingStakers.PutValidator(staker) + return nil } func (s *state) DeletePendingValidator(staker *Staker) { @@ -1287,7 +1289,9 @@ func (s *state) syncGenesis(genesisBlk block.Block, genesis *genesis.Genesis) er return err } - s.PutCurrentValidator(staker) + if err := s.PutCurrentValidator(staker); err != nil { + return err + } s.AddTx(vdrTx, status.Committed) s.SetCurrentSupply(constants.PrimaryNetworkID, newCurrentSupply) } diff --git a/vms/platformvm/state/state_test.go b/vms/platformvm/state/state_test.go index de2bab544c00..08b53eeb4fe8 100644 --- a/vms/platformvm/state/state_test.go +++ b/vms/platformvm/state/state_test.go @@ -148,7 +148,7 @@ func TestPersistStakers(t *testing.T) { ) r.NoError(err) - s.PutCurrentValidator(staker) + r.NoError(s.PutCurrentValidator(staker)) s.AddTx(addPermValTx, status.Committed) // this is currently needed to reload the staker r.NoError(s.Commit()) return staker @@ -243,7 +243,7 @@ func TestPersistStakers(t *testing.T) { ) r.NoError(err) - s.PutCurrentValidator(val) + r.NoError(s.PutCurrentValidator(val)) s.AddTx(addPermValTx, status.Committed) // this is currently needed to reload the staker r.NoError(s.Commit()) @@ -308,7 +308,7 @@ func TestPersistStakers(t *testing.T) { ) r.NoError(err) - s.PutPendingValidator(staker) + r.NoError(s.PutPendingValidator(staker)) s.AddTx(addPermValTx, status.Committed) // this is currently needed to reload the staker r.NoError(s.Commit()) return staker @@ -375,7 +375,7 @@ func TestPersistStakers(t *testing.T) { del, err := NewPendingStaker(addPermDelTx.ID(), utxDel) r.NoError(err) - s.PutPendingValidator(val) + r.NoError(s.PutPendingValidator(val)) s.AddTx(addPermValTx, status.Committed) // this is currently needed to reload the staker r.NoError(s.Commit()) @@ -428,7 +428,7 @@ func TestPersistStakers(t *testing.T) { ) r.NoError(err) - s.PutCurrentValidator(staker) + r.NoError(s.PutCurrentValidator(staker)) s.AddTx(addPermValTx, status.Committed) // this is currently needed to reload the staker r.NoError(s.Commit()) @@ -517,7 +517,7 @@ func TestPersistStakers(t *testing.T) { ) r.NoError(err) - s.PutCurrentValidator(val) + r.NoError(s.PutCurrentValidator(val)) s.AddTx(addPermValTx, status.Committed) // this is currently needed to reload the staker s.PutCurrentDelegator(del) @@ -582,7 +582,7 @@ func TestPersistStakers(t *testing.T) { ) r.NoError(err) - s.PutPendingValidator(staker) + r.NoError(s.PutPendingValidator(staker)) s.AddTx(addPermValTx, status.Committed) // this is currently needed to reload the staker r.NoError(s.Commit()) @@ -649,7 +649,7 @@ func TestPersistStakers(t *testing.T) { del, err := NewPendingStaker(addPermDelTx.ID(), utxDel) r.NoError(err) - s.PutPendingValidator(val) + r.NoError(s.PutPendingValidator(val)) s.AddTx(addPermValTx, status.Committed) // this is currently needed to reload the staker s.PutPendingDelegator(del) @@ -1099,7 +1099,7 @@ func TestStateAddRemoveValidator(t *testing.T) { for currentIndex, diff := range diffs { for _, added := range diff.addedValidators { added := added - state.PutCurrentValidator(&added) + require.NoError(state.PutCurrentValidator(&added)) } for _, added := range diff.addedDelegators { added := added diff --git a/vms/platformvm/txs/executor/advance_time_test.go b/vms/platformvm/txs/executor/advance_time_test.go index aadf84136615..c301b8bde8bb 100644 --- a/vms/platformvm/txs/executor/advance_time_test.go +++ b/vms/platformvm/txs/executor/advance_time_test.go @@ -408,7 +408,7 @@ func TestAdvanceTimeTxUpdateStakers(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) } env.state.SetHeight(dummyHeight) @@ -513,7 +513,7 @@ func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -541,7 +541,7 @@ func TestAdvanceTimeTxRemoveSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -625,7 +625,7 @@ func TestTrackedSubnet(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -962,7 +962,7 @@ func addPendingValidator( ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(addPendingValidatorTx, status.Committed) dummyHeight := uint64(1) env.state.SetHeight(dummyHeight) diff --git a/vms/platformvm/txs/executor/proposal_tx_executor.go b/vms/platformvm/txs/executor/proposal_tx_executor.go index d7b76d10c615..f5a995772a7c 100644 --- a/vms/platformvm/txs/executor/proposal_tx_executor.go +++ b/vms/platformvm/txs/executor/proposal_tx_executor.go @@ -138,7 +138,9 @@ func (e *ProposalTxExecutor) AddValidatorTx(tx *txs.AddValidatorTx) error { return err } - e.OnCommitState.PutPendingValidator(newStaker) + if err := e.OnCommitState.PutPendingValidator(newStaker); err != nil { + return err + } // Set up the state if this tx is aborted // Consume the UTXOs @@ -185,7 +187,9 @@ func (e *ProposalTxExecutor) AddSubnetValidatorTx(tx *txs.AddSubnetValidatorTx) return err } - e.OnCommitState.PutPendingValidator(newStaker) + if err := e.OnCommitState.PutPendingValidator(newStaker); err != nil { + return err + } // Set up the state if this tx is aborted // Consume the UTXOs diff --git a/vms/platformvm/txs/executor/proposal_tx_executor_test.go b/vms/platformvm/txs/executor/proposal_tx_executor_test.go index 70687a965836..eed2e6a6ddeb 100644 --- a/vms/platformvm/txs/executor/proposal_tx_executor_test.go +++ b/vms/platformvm/txs/executor/proposal_tx_executor_test.go @@ -65,7 +65,7 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -101,7 +101,7 @@ func TestProposalTxExecuteAddDelegator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -434,7 +434,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(addDSTx, status.Committed) dummyHeight := uint64(1) env.state.SetHeight(dummyHeight) @@ -622,7 +622,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(subnetTx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -779,7 +779,7 @@ func TestProposalTxExecuteAddSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -909,7 +909,7 @@ func TestProposalTxExecuteAddValidator(t *testing.T) { ) require.NoError(err) - env.state.PutPendingValidator(staker) + require.NoError(env.state.PutPendingValidator(staker)) env.state.AddTx(tx, status.Committed) dummyHeight := uint64(1) env.state.SetHeight(dummyHeight) diff --git a/vms/platformvm/txs/executor/reward_validator_test.go b/vms/platformvm/txs/executor/reward_validator_test.go index 55f210ebc95f..86fb83f994ed 100644 --- a/vms/platformvm/txs/executor/reward_validator_test.go +++ b/vms/platformvm/txs/executor/reward_validator_test.go @@ -300,7 +300,7 @@ func TestRewardDelegatorTxExecuteOnCommitPreDelegateeDeferral(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(vdrStaker) + require.NoError(env.state.PutCurrentValidator(vdrStaker)) env.state.AddTx(vdrTx, status.Committed) env.state.PutCurrentDelegator(delStaker) env.state.AddTx(delTx, status.Committed) @@ -433,7 +433,7 @@ func TestRewardDelegatorTxExecuteOnCommitPostDelegateeDeferral(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(vdrStaker) + require.NoError(env.state.PutCurrentValidator(vdrStaker)) env.state.AddTx(vdrTx, status.Committed) env.state.PutCurrentDelegator(delStaker) env.state.AddTx(delTx, status.Committed) @@ -660,7 +660,7 @@ func TestRewardDelegatorTxAndValidatorTxExecuteOnCommitPostDelegateeDeferral(t * ) require.NoError(err) - env.state.PutCurrentValidator(vdrStaker) + require.NoError(env.state.PutCurrentValidator(vdrStaker)) env.state.AddTx(vdrTx, status.Committed) env.state.PutCurrentDelegator(delStaker) env.state.AddTx(delTx, status.Committed) @@ -831,7 +831,7 @@ func TestRewardDelegatorTxExecuteOnAbort(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(vdrStaker) + require.NoError(env.state.PutCurrentValidator(vdrStaker)) env.state.AddTx(vdrTx, status.Committed) env.state.PutCurrentDelegator(delStaker) env.state.AddTx(delTx, status.Committed) diff --git a/vms/platformvm/txs/executor/standard_tx_executor.go b/vms/platformvm/txs/executor/standard_tx_executor.go index 1204b7d82502..16e520e0af6e 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor.go +++ b/vms/platformvm/txs/executor/standard_tx_executor.go @@ -671,11 +671,15 @@ func (e *StandardTxExecutor) putStaker(stakerTx txs.Staker) error { switch priority := staker.Priority; { case priority.IsCurrentValidator(): - e.State.PutCurrentValidator(staker) + if err := e.State.PutCurrentValidator(staker); err != nil { + return err + } case priority.IsCurrentDelegator(): e.State.PutCurrentDelegator(staker) case priority.IsPendingValidator(): - e.State.PutPendingValidator(staker) + if err := e.State.PutPendingValidator(staker); err != nil { + return err + } case priority.IsPendingDelegator(): e.State.PutPendingDelegator(staker) default: diff --git a/vms/platformvm/txs/executor/standard_tx_executor_test.go b/vms/platformvm/txs/executor/standard_tx_executor_test.go index 2b01148a7f76..459c96c08b92 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor_test.go +++ b/vms/platformvm/txs/executor/standard_tx_executor_test.go @@ -143,7 +143,7 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -178,7 +178,7 @@ func TestStandardTxExecutorAddDelegator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -497,7 +497,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(addDSTx, status.Committed) dummyHeight := uint64(1) env.state.SetHeight(dummyHeight) @@ -669,7 +669,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(subnetTx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -858,7 +858,7 @@ func TestApricotStandardTxExecutorAddSubnetValidator(t *testing.T) { ) require.NoError(err) - env.state.PutCurrentValidator(staker) + require.NoError(env.state.PutCurrentValidator(staker)) env.state.AddTx(tx, status.Committed) env.state.SetHeight(dummyHeight) require.NoError(env.state.Commit()) @@ -987,7 +987,7 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) - onAcceptState.PutCurrentValidator(staker) + require.NoError(onAcceptState.PutCurrentValidator(staker)) onAcceptState.AddTx(tx, status.Committed) feeCalculator := state.PickFeeCalculator(env.config, onAcceptState) @@ -1027,7 +1027,7 @@ func TestBanffStandardTxExecutorAddValidator(t *testing.T) { onAcceptState, err := state.NewDiff(lastAcceptedID, env) require.NoError(err) - onAcceptState.PutPendingValidator(staker) + require.NoError(onAcceptState.PutPendingValidator(staker)) onAcceptState.AddTx(tx, status.Committed) feeCalculator := state.PickFeeCalculator(env.config, onAcceptState) diff --git a/vms/platformvm/txs/executor/state_changes.go b/vms/platformvm/txs/executor/state_changes.go index 244be246f8a0..55f940fca509 100644 --- a/vms/platformvm/txs/executor/state_changes.go +++ b/vms/platformvm/txs/executor/state_changes.go @@ -97,7 +97,9 @@ func AdvanceTimeTo( stakerToAdd.Priority = txs.PendingToCurrentPriorities[stakerToRemove.Priority] if stakerToRemove.Priority == txs.SubnetPermissionedValidatorPendingPriority { - changes.PutCurrentValidator(&stakerToAdd) + if err := changes.PutCurrentValidator(&stakerToAdd); err != nil { + return false, err + } changes.DeletePendingValidator(stakerToRemove) changed = true continue @@ -126,7 +128,9 @@ func AdvanceTimeTo( switch stakerToRemove.Priority { case txs.PrimaryNetworkValidatorPendingPriority, txs.SubnetPermissionlessValidatorPendingPriority: - changes.PutCurrentValidator(&stakerToAdd) + if err := changes.PutCurrentValidator(&stakerToAdd); err != nil { + return false, err + } changes.DeletePendingValidator(stakerToRemove) case txs.PrimaryNetworkDelegatorApricotPendingPriority, txs.PrimaryNetworkDelegatorBanffPendingPriority, txs.SubnetPermissionlessDelegatorPendingPriority: diff --git a/vms/platformvm/validators/manager_benchmark_test.go b/vms/platformvm/validators/manager_benchmark_test.go index 98227e09913d..0b2222f45f1a 100644 --- a/vms/platformvm/validators/manager_benchmark_test.go +++ b/vms/platformvm/validators/manager_benchmark_test.go @@ -115,7 +115,7 @@ func addPrimaryValidator( } nodeID := ids.GenerateTestNodeID() - s.PutCurrentValidator(&state.Staker{ + if err := s.PutCurrentValidator(&state.Staker{ TxID: ids.GenerateTestID(), NodeID: nodeID, PublicKey: bls.PublicFromSecretKey(sk), @@ -126,7 +126,9 @@ func addPrimaryValidator( PotentialReward: 0, NextTime: endTime, Priority: txs.PrimaryNetworkValidatorCurrentPriority, - }) + }); err != nil { + return ids.EmptyNodeID, err + } blk, err := block.NewBanffStandardBlock(startTime, ids.GenerateTestID(), height, nil) if err != nil { @@ -146,7 +148,7 @@ func addSubnetValidator( nodeID ids.NodeID, height uint64, ) error { - s.PutCurrentValidator(&state.Staker{ + if err := s.PutCurrentValidator(&state.Staker{ TxID: ids.GenerateTestID(), NodeID: nodeID, SubnetID: subnetID, @@ -156,7 +158,9 @@ func addSubnetValidator( PotentialReward: 0, NextTime: endTime, Priority: txs.SubnetPermissionlessValidatorCurrentPriority, - }) + }); err != nil { + return err + } blk, err := block.NewBanffStandardBlock(startTime, ids.GenerateTestID(), height, nil) if err != nil { diff --git a/vms/platformvm/vm_regression_test.go b/vms/platformvm/vm_regression_test.go index 811dc2dfb91a..608ebaa956fc 100644 --- a/vms/platformvm/vm_regression_test.go +++ b/vms/platformvm/vm_regression_test.go @@ -39,6 +39,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/genesis/genesistest" "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" + "github.com/ava-labs/avalanchego/vms/platformvm/state" "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/platformvm/txs/executor" @@ -1366,6 +1367,74 @@ func TestRemovePermissionedValidatorDuringPendingToCurrentTransitionTracked(t *t require.NoError(buildAndAcceptStandardBlock(vm)) } +func TestAddValidatorDuringRemoval(t *testing.T) { + require := require.New(t) + + vm, _, _ := defaultVM(t, upgradetest.Durango) + vm.ctx.Lock.Lock() + defer vm.ctx.Lock.Unlock() + + var ( + nodeID = genesistest.DefaultNodeIDs[0] + subnetID = testSubnet1.ID() + wallet = newWallet(t, vm, walletConfig{ + subnetIDs: []ids.ID{subnetID}, + }) + + duration = defaultMinStakingDuration + firstEndTime = latestForkTime.Add(duration) + ) + + firstAddSubnetValidatorTx, err := wallet.IssueAddSubnetValidatorTx(&txs.SubnetValidator{ + Validator: txs.Validator{ + NodeID: nodeID, + End: uint64(firstEndTime.Unix()), + Wght: 1, + }, + Subnet: subnetID, + }) + require.NoError(err) + + vm.ctx.Lock.Unlock() + require.NoError(vm.issueTxFromRPC(firstAddSubnetValidatorTx)) + vm.ctx.Lock.Lock() + + // Accept firstAddSubnetValidatorTx + require.NoError(buildAndAcceptStandardBlock(vm)) + + // Verify that the validator was added + _, err = vm.state.GetCurrentValidator(subnetID, nodeID) + require.NoError(err) + + secondEndTime := firstEndTime.Add(duration) + secondSubnetValidatorTx, err := wallet.IssueAddSubnetValidatorTx(&txs.SubnetValidator{ + Validator: txs.Validator{ + NodeID: nodeID, + End: uint64(secondEndTime.Unix()), + Wght: 1, + }, + Subnet: subnetID, + }) + require.NoError(err) + + vm.clock.Set(firstEndTime) + vm.ctx.Lock.Unlock() + err = vm.issueTxFromRPC(secondSubnetValidatorTx) + vm.ctx.Lock.Lock() + require.ErrorIs(err, state.ErrAddingStakerAfterDeletion) + + // Remove the first subnet validator + require.NoError(buildAndAcceptStandardBlock(vm)) + + // Verify that the validator does not exist + _, err = vm.state.GetCurrentValidator(subnetID, nodeID) + require.ErrorIs(err, database.ErrNotFound) + + // Verify that the invalid transaction was not executed + _, _, err = vm.state.GetTx(secondSubnetValidatorTx.ID()) + require.ErrorIs(err, database.ErrNotFound) +} + // GetValidatorSet must return the BLS keys for a given validator correctly when // queried at a previous height, even in case it has currently expired func TestSubnetValidatorBLSKeyDiffAfterExpiry(t *testing.T) { From d3c09eb19d6e8c85a4757f17cd5da7e713c2baba Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Tue, 3 Sep 2024 19:34:12 -0400 Subject: [PATCH 60/69] Update versions for v1.11.11 (#3347) --- RELEASES.md | 158 +++++++++++++++++++++++++++++++++++++ proto/README.md | 2 +- version/compatibility.json | 3 + version/constants.go | 4 +- 4 files changed, 164 insertions(+), 3 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index be6a7cef9548..16b371b67a12 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,5 +1,163 @@ # Release Notes +## [v1.11.11](https://github.com/ava-labs/avalanchego/releases/tag/v1.11.11) + +This version is backwards compatible to [v1.11.0](https://github.com/ava-labs/avalanchego/releases/tag/v1.11.0). It is optional, but encouraged. + +The plugin version is updated to `37` all plugins must update to be compatible. + +### APIs + +- Updated JSON marshalling of the `Memo` field to follow best practices +- Added `info.upgrades` +- Added `platform.getFeeConfig` +- Added `platform.getFeeState` +- Deprecated subnet uptimes + - `info.uptimes` with non-primary network subnetIDs is deprecated + - `info.peers` `observedSubnetUptimes` is deprecated + - `platform.getCurrentValidators` `uptime` and `connected` are deprecated for non-primary network subnetIDs. + - `avalanche_network_node_subnet_uptime_weighted_average` metric is deprecated + - `avalanche_network_node_subnet_uptime_rewarding_stake` metric is deprecated +- Added `avalanche_network_tracked_peers` metric +- Added `avalanche_network_tracked_subnets` metric +- Removed `avalanche_network_tracked_ips` metric +- Added disconnected validators to the health check result + + +### Configs + +- Added upgrade config + - `--upgrade-file` + - `--upgrade-file-content` +- Added dynamic fees config + - `--dynamic-fees-bandwidth-weight` + - `--dynamic-fees-read-weight` + - `--dynamic-fees-write-weight` + - `--dynamic-fees-compute-weight` + - `--dynamic-fees-max-gas-capacity` + - `--dynamic-fees-max-gas-per-second` + - `--dynamic-fees-target-gas-per-second` + - `--dynamic-fees-min-gas-price` + - `--dynamic-fees-excess-conversion-constant` + +### Fixes + +- Fixed panic when tracing is enabled +- Removed duplicate block signature verifications during bootstrapping +- Fixed racy timer clearing in message throttling + +### What's Changed + +- [ci] Remove defunct network outage sim workflow by @marun in https://github.com/ava-labs/avalanchego/pull/3234 +- chore: allow test-only imports in `*test` and `/tests/**` packages by @ARR4N in https://github.com/ava-labs/avalanchego/pull/3229 +- Add benchmarks for add and sub fee dimensions by @abi87 in https://github.com/ava-labs/avalanchego/pull/3222 +- Remove deadcode by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3086 +- Parallelize BatchedParseBlock by @yacovm in https://github.com/ava-labs/avalanchego/pull/3227 +- [ci] Lint on non-test code importing packages from /tests by @marun in https://github.com/ava-labs/avalanchego/pull/3214 +- Merge unlocked stake outputs by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3231 +- ACP 118 reference implementation by @cam-schultz in https://github.com/ava-labs/avalanchego/pull/3218 +- Storage OpenBSD/adJ by @vtamara in https://github.com/ava-labs/avalanchego/pull/2809 +- Remove unused error from fee calculator creation by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3245 +- Rename Transitive snowman to Engine snowman by @yacovm in https://github.com/ava-labs/avalanchego/pull/3244 +- Simplify static fee calculations by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3240 +- Remove targetBlockSize arg by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3249 +- Add dynamic fees config by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3250 +- Remove unused Samplers by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3219 +- Inline `verifier` struct creation by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3252 +- Add fee.State to P-chain state by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3248 +- Fix comparison comment in snowflake algorithms by @yacovm in https://github.com/ava-labs/avalanchego/pull/3256 +- Add network upgrade config by @aaronbuchwald in https://github.com/ava-labs/avalanchego/pull/3207 +- [vms/platformvm] Add `VerifyWithContext` to `Block`s by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3236 +- [ci] Switch to v2 of docker compose plugin by @marun in https://github.com/ava-labs/avalanchego/pull/3259 +- Minimize signature verification when bootstrapping by @yacovm in https://github.com/ava-labs/avalanchego/pull/3255 +- [vms/platformvm] Add tracking of a Subnet manager by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3126 +- Remove trackedSubnet check for explicitly named peers in network.Send() by @iansuvak in https://github.com/ava-labs/avalanchego/pull/3258 +- refactor: introduce `*test` packages in lieu of `//go:build test` by @ARR4N in https://github.com/ava-labs/avalanchego/pull/3238 +- [e2e] Enhance post-test bootstrap checks by @marun in https://github.com/ava-labs/avalanchego/pull/3253 +- [e2e] Abstract usage of ginkgo with a new test context by @marun in https://github.com/ava-labs/avalanchego/pull/3254 +- Update code owners by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3262 +- [antithesis] Refactor image build for reuse by other repos by @marun in https://github.com/ava-labs/avalanchego/pull/3198 +- Expose upgrade config in the info API by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3266 +- [antithesis] Ensure references to pushed images are qualified by @marun in https://github.com/ava-labs/avalanchego/pull/3264 +- Fix spelling by @nnsW3 in https://github.com/ava-labs/avalanchego/pull/3267 +- refactor: rename `*test.Test*` identifiers by @ARR4N in https://github.com/ava-labs/avalanchego/pull/3260 +- Separate e2e tests by etna activation by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3268 +- Implement P-chain ACP-103 complexity calculations by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3209 +- Implement dynamic fee calculator by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3211 +- [tmpnet] Add Network.GetNetworkID() to get ID of a running network by @marun in https://github.com/ava-labs/avalanchego/pull/3269 +- Disable `TransformSubnetTx` post-Etna by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3152 +- [tmpnet] Fail node health check if node is not running by @marun in https://github.com/ava-labs/avalanchego/pull/3274 +- [tmpnet] Enable network restart to simplify iteration by @marun in https://github.com/ava-labs/avalanchego/pull/3272 +- Add StoppedTimer helper by @marun in https://github.com/ava-labs/avalanchego/pull/3280 +- Fix race in timer stoppage by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3281 +- [tmpnet] Add check for vm binaries to network and node start by @marun in https://github.com/ava-labs/avalanchego/pull/3273 +- Refactor P-chain Builder by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3282 +- chore: fix some comments by @drawdrop in https://github.com/ava-labs/avalanchego/pull/3289 +- Update write path of tmpnet subnet config by @aaronbuchwald in https://github.com/ava-labs/avalanchego/pull/3290 +- add network upgrades to chain ctx by @ceyonur in https://github.com/ava-labs/avalanchego/pull/3283 +- Implement dynamic fee builder by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3232 +- bump coreth past upgrade schedule refactor by @darioush in https://github.com/ava-labs/avalanchego/pull/3278 +- Remove cross-chain requests by @darioush in https://github.com/ava-labs/avalanchego/pull/3277 +- wallet: obtain subnet owners by using P-Chain's getSubnet API call by @felipemadero in https://github.com/ava-labs/avalanchego/pull/3247 +- [antithesis] Add tmpnet support to workloads to simplify development by @marun in https://github.com/ava-labs/avalanchego/pull/3215 +- Refactor e2e tests for P-chain tests by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3295 +- Fix e2e tests to support dynamic fees by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3296 +- Improve error message of dynamic fee calculations by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3297 +- Reduce dynamic fees variability to ease testing by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3298 +- deprecate uptime apis by @ceyonur in https://github.com/ava-labs/avalanchego/pull/3226 +- [antithesis] Fix broken flag handling and improve image testing by @marun in https://github.com/ava-labs/avalanchego/pull/3299 +- Add P-chain fee APIs by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3286 +- [tmpnet] Add support for checking rpcchainvm version compatibility by @marun in https://github.com/ava-labs/avalanchego/pull/3276 +- Rename gas price calculation function by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3302 +- Remove duplicate fork definitions by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3304 +- Restrict `Owner` usage after a Subnet manager is set by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3147 +- SoV networking support by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/2951 +- [antithesis] Enable custom plugin dir for subnet-evm by @marun in https://github.com/ava-labs/avalanchego/pull/3305 +- Refactor state tests to always use initialized state by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3310 +- Remove mock for `Versions` interface by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3312 +- Allow P-chain wallet to be used by the platformvm by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3314 +- Remove crosschain leftovers by @ceyonur in https://github.com/ava-labs/avalanchego/pull/3309 +- Rename race condition image tags by @cam-schultz in https://github.com/ava-labs/avalanchego/pull/3311 +- Add .String() to Fork testing utility by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3315 +- [antithesis] Update schedule to make room for subnet-evm by @marun in https://github.com/ava-labs/avalanchego/pull/3317 +- [tmpnet] Update monitoring urls from *-experimental to *-poc by @marun in https://github.com/ava-labs/avalanchego/pull/3306 +- Add statetest to replace common test state initialization by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3319 +- Rename `components/fee` pkg to `components/gas` by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3321 +- Remove mocks for `Staker` and `ScheduledStaker` by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3322 +- Move most mocks to sub-dirs by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3323 +- [e2e] Simplify pre-funded key usage by @marun in https://github.com/ava-labs/avalanchego/pull/3011 +- Move iterator implementations to `utils` pkg by @dhrubabasu in https://github.com/ava-labs/avalanchego/pull/3320 +- Remove duplicate genesis creations in P-chain unit tests by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3318 +- Simplify P-Chain transaction creation in unit tests by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3327 +- [tmpnet] Ensure nodes are stopped in the event of bootstrap failure by @marun in https://github.com/ava-labs/avalanchego/pull/3332 +- Add tx complexity helper by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3334 +- Fixed segfault when --tracing-enabled is set by @blenessy in https://github.com/ava-labs/avalanchego/pull/3330 +- chore: remove deprecated `validatorstest.TestState` by @ARR4N in https://github.com/ava-labs/avalanchego/pull/3301 +- Enforce network config not including `PrimaryNetworkID` in `trackedSubnets` by @iansuvak in https://github.com/ava-labs/avalanchego/pull/3336 +- Use wallet in `platformvm/block` tests by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3328 +- [ci] Stop using setup-go-v3 by @marun in https://github.com/ava-labs/avalanchego/pull/3339 +- Use wallet in `platformvm/txs` tests by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3333 +- [ci] Configure buf-setup-action for check_generated_protobuf job with token by @marun in https://github.com/ava-labs/avalanchego/pull/3341 +- Add P-chain dynamic fees execution by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3251 +- Include disconnected validators in health message by @ceyonur in https://github.com/ava-labs/avalanchego/pull/3344 +- Print type of message sent in the verbose log by @yacovm in https://github.com/ava-labs/avalanchego/pull/3348 +- Remove local chain config from e2e test by @ceyonur in https://github.com/ava-labs/avalanchego/pull/3293 +- Separate codec registries by upgrade by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3353 +- Support unmarshalling of json byte slices by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3354 +- Add explicit p-chain current validator check in AddValidator by @StephenButtolph in https://github.com/ava-labs/avalanchego/pull/3355 + +### New Contributors + +- @yacovm made their first contribution in https://github.com/ava-labs/avalanchego/pull/3227 +- @cam-schultz made their first contribution in https://github.com/ava-labs/avalanchego/pull/3218 +- @vtamara made their first contribution in https://github.com/ava-labs/avalanchego/pull/2809 +- @iansuvak made their first contribution in https://github.com/ava-labs/avalanchego/pull/3258 +- @nnsW3 made their first contribution in https://github.com/ava-labs/avalanchego/pull/3267 +- @drawdrop made their first contribution in https://github.com/ava-labs/avalanchego/pull/3289 +- @blenessy made their first contribution in https://github.com/ava-labs/avalanchego/pull/3330 + +**Full Changelog**: https://github.com/ava-labs/avalanchego/compare/v1.11.10...v1.11.11 + ## [v1.11.10](https://github.com/ava-labs/avalanchego/releases/tag/v1.11.10) This version is backwards compatible to [v1.11.0](https://github.com/ava-labs/avalanchego/releases/tag/v1.11.0). It is optional, but encouraged. diff --git a/proto/README.md b/proto/README.md index 5bbf1b3fc7ee..ece9fd7ac2f2 100644 --- a/proto/README.md +++ b/proto/README.md @@ -1,6 +1,6 @@ # Avalanche gRPC -Now Serving: **Protocol Version 36** +Now Serving: **Protocol Version 37** Protobuf files are hosted at [https://buf.build/ava-labs/avalanche](https://buf.build/ava-labs/avalanche) and diff --git a/version/compatibility.json b/version/compatibility.json index dba18fd78582..d9be9f2d0953 100644 --- a/version/compatibility.json +++ b/version/compatibility.json @@ -1,4 +1,7 @@ { + "37": [ + "v1.11.11" + ], "36": [ "v1.11.10" ], diff --git a/version/constants.go b/version/constants.go index a2ef3ced40c4..032aad715818 100644 --- a/version/constants.go +++ b/version/constants.go @@ -15,7 +15,7 @@ const ( // RPCChainVMProtocol should be bumped anytime changes are made which // require the plugin vm to upgrade to latest avalanchego release to be // compatible. - RPCChainVMProtocol uint = 36 + RPCChainVMProtocol uint = 37 ) // These are globals that describe network upgrades and node versions @@ -23,7 +23,7 @@ var ( Current = &Semantic{ Major: 1, Minor: 11, - Patch: 10, + Patch: 11, } CurrentApp = &Application{ Name: Client, From ccf261275796ef4319ab6591397e8c219c9a42a7 Mon Sep 17 00:00:00 2001 From: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> Date: Wed, 4 Sep 2024 00:46:04 -0400 Subject: [PATCH 61/69] Implement `ConvertSubnetTx` (#3217) Signed-off-by: Dhruba Basu <7675102+dhrubabasu@users.noreply.github.com> Co-authored-by: Stephen Buttolph --- tests/e2e/p/permissionless_layer_one.go | 101 ++++ vms/platformvm/block/codec.go | 7 + vms/platformvm/client.go | 5 + vms/platformvm/metrics/tx_metrics.go | 7 + vms/platformvm/service.go | 18 +- vms/platformvm/txs/codec.go | 13 +- vms/platformvm/txs/convert_subnet_tx.go | 64 ++ vms/platformvm/txs/convert_subnet_tx_test.go | 565 ++++++++++++++++++ .../txs/convert_subnet_tx_test_complex.json | 81 +++ .../txs/convert_subnet_tx_test_simple.json | 28 + .../txs/executor/atomic_tx_executor.go | 4 + .../txs/executor/proposal_tx_executor.go | 4 + .../txs/executor/standard_tx_executor.go | 52 ++ .../txs/executor/standard_tx_executor_test.go | 215 +++++++ vms/platformvm/txs/fee/calculator_test.go | 12 + vms/platformvm/txs/fee/complexity.go | 30 + vms/platformvm/txs/fee/static_calculator.go | 4 + vms/platformvm/txs/visitor.go | 1 + wallet/chain/p/builder/builder.go | 75 +++ .../chain/p/builder/builder_with_options.go | 14 + wallet/chain/p/builder_test.go | 40 ++ wallet/chain/p/signer/visitor.go | 13 + wallet/chain/p/wallet/backend_visitor.go | 4 + wallet/chain/p/wallet/wallet.go | 26 + wallet/chain/p/wallet/with_options.go | 14 + 25 files changed, 1395 insertions(+), 2 deletions(-) create mode 100644 tests/e2e/p/permissionless_layer_one.go create mode 100644 vms/platformvm/txs/convert_subnet_tx.go create mode 100644 vms/platformvm/txs/convert_subnet_tx_test.go create mode 100644 vms/platformvm/txs/convert_subnet_tx_test_complex.json create mode 100644 vms/platformvm/txs/convert_subnet_tx_test_simple.json diff --git a/tests/e2e/p/permissionless_layer_one.go b/tests/e2e/p/permissionless_layer_one.go new file mode 100644 index 000000000000..0420be83d0da --- /dev/null +++ b/tests/e2e/p/permissionless_layer_one.go @@ -0,0 +1,101 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package p + +import ( + "time" + + "github.com/stretchr/testify/require" + + "github.com/ava-labs/avalanchego/api/info" + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/tests/fixture/e2e" + "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/vms/platformvm" + "github.com/ava-labs/avalanchego/vms/secp256k1fx" + + ginkgo "github.com/onsi/ginkgo/v2" +) + +var _ = e2e.DescribePChain("[Permissionless L1]", func() { + tc := e2e.NewTestContext() + require := require.New(tc) + + ginkgo.It("creates a Permissionless L1", func() { + env := e2e.GetEnv(tc) + nodeURI := env.GetRandomNodeURI() + infoClient := info.NewClient(nodeURI.URI) + + tc.By("fetching upgrade config") + upgrades, err := infoClient.Upgrades(tc.DefaultContext()) + require.NoError(err) + + tc.By("verifying Etna is activated") + now := time.Now() + if !upgrades.IsEtnaActivated(now) { + ginkgo.Skip("Etna is not activated. Permissionless L1s are enabled post-Etna, skipping test.") + } + + keychain := env.NewKeychain() + baseWallet := e2e.NewWallet(tc, keychain, nodeURI) + + pWallet := baseWallet.P() + pClient := platformvm.NewClient(nodeURI.URI) + + owner := &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + keychain.Keys[0].Address(), + }, + } + + tc.By("issuing a CreateSubnetTx") + subnetTx, err := pWallet.IssueCreateSubnetTx( + owner, + tc.WithDefaultContext(), + ) + require.NoError(err) + + tc.By("verifying a Permissioned Subnet was successfully created") + subnetID := subnetTx.ID() + require.NotEqual(subnetID, constants.PrimaryNetworkID) + + res, err := pClient.GetSubnet(tc.DefaultContext(), subnetID) + require.NoError(err) + + require.Equal(platformvm.GetSubnetClientResponse{ + IsPermissioned: true, + ControlKeys: []ids.ShortID{ + keychain.Keys[0].Address(), + }, + Threshold: 1, + }, res) + + chainID := ids.GenerateTestID() + address := []byte{'a', 'd', 'd', 'r', 'e', 's', 's'} + + tc.By("issuing a ConvertSubnetTx") + _, err = pWallet.IssueConvertSubnetTx( + subnetID, + chainID, + address, + tc.WithDefaultContext(), + ) + require.NoError(err) + + tc.By("verifying the Permissioned Subnet was converted to a Permissionless L1") + res, err = pClient.GetSubnet(tc.DefaultContext(), subnetID) + require.NoError(err) + + require.Equal(platformvm.GetSubnetClientResponse{ + IsPermissioned: false, + ControlKeys: []ids.ShortID{ + keychain.Keys[0].Address(), + }, + Threshold: 1, + ManagerChainID: chainID, + ManagerAddress: address, + }, res) + }) +}) diff --git a/vms/platformvm/block/codec.go b/vms/platformvm/block/codec.go index 56b3590dcdc4..bb23ea2b00ae 100644 --- a/vms/platformvm/block/codec.go +++ b/vms/platformvm/block/codec.go @@ -35,6 +35,7 @@ func init() { RegisterApricotTypes(c), RegisterBanffTypes(c), RegisterDurangoTypes(c), + RegisterEtnaTypes(c), ) } @@ -79,3 +80,9 @@ func RegisterBanffTypes(targetCodec linearcodec.Codec) error { func RegisterDurangoTypes(targetCodec linearcodec.Codec) error { return txs.RegisterDurangoTypes(targetCodec) } + +// RegisterEtnaTypes registers the type information for blocks that were valid +// during the Etna series of upgrades. +func RegisterEtnaTypes(targetCodec linearcodec.Codec) error { + return txs.RegisterEtnaTypes(targetCodec) +} diff --git a/vms/platformvm/client.go b/vms/platformvm/client.go index e5338fbae3f8..54554f37d92b 100644 --- a/vms/platformvm/client.go +++ b/vms/platformvm/client.go @@ -235,6 +235,9 @@ type GetSubnetClientResponse struct { Locktime uint64 // subnet transformation tx ID for a permissionless subnet SubnetTransformationTxID ids.ID + // subnet manager information for a permissionless L1 + ManagerChainID ids.ID + ManagerAddress []byte } func (c *client) GetSubnet(ctx context.Context, subnetID ids.ID, options ...rpc.Option) (GetSubnetClientResponse, error) { @@ -256,6 +259,8 @@ func (c *client) GetSubnet(ctx context.Context, subnetID ids.ID, options ...rpc. Threshold: uint32(res.Threshold), Locktime: uint64(res.Locktime), SubnetTransformationTxID: res.SubnetTransformationTxID, + ManagerChainID: res.ManagerChainID, + ManagerAddress: res.ManagerAddress, }, nil } diff --git a/vms/platformvm/metrics/tx_metrics.go b/vms/platformvm/metrics/tx_metrics.go index 02f45f011624..fd6c63494f7c 100644 --- a/vms/platformvm/metrics/tx_metrics.go +++ b/vms/platformvm/metrics/tx_metrics.go @@ -132,6 +132,13 @@ func (m *txMetrics) TransferSubnetOwnershipTx(*txs.TransferSubnetOwnershipTx) er return nil } +func (m *txMetrics) ConvertSubnetTx(*txs.ConvertSubnetTx) error { + m.numTxs.With(prometheus.Labels{ + txLabel: "convert_subnet", + }).Inc() + return nil +} + func (m *txMetrics) BaseTx(*txs.BaseTx) error { m.numTxs.With(prometheus.Labels{ txLabel: "base", diff --git a/vms/platformvm/service.go b/vms/platformvm/service.go index 411919ecaa8d..fd753de47c32 100644 --- a/vms/platformvm/service.go +++ b/vms/platformvm/service.go @@ -38,6 +38,7 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/vms/types" avajson "github.com/ava-labs/avalanchego/utils/json" safemath "github.com/ava-labs/avalanchego/utils/math" @@ -436,8 +437,11 @@ type GetSubnetResponse struct { ControlKeys []string `json:"controlKeys"` Threshold avajson.Uint32 `json:"threshold"` Locktime avajson.Uint64 `json:"locktime"` - // subnet transformation tx ID for a permissionless subnet + // subnet transformation tx ID for an elastic subnet SubnetTransformationTxID ids.ID `json:"subnetTransformationTxID"` + // subnet manager information for a permissionless L1 + ManagerChainID ids.ID `json:"managerChainID"` + ManagerAddress types.JSONByteSlice `json:"managerAddress"` } func (s *Service) GetSubnet(_ *http.Request, args *GetSubnetArgs, response *GetSubnetResponse) error { @@ -486,6 +490,18 @@ func (s *Service) GetSubnet(_ *http.Request, args *GetSubnetArgs, response *GetS return err } + switch chainID, addr, err := s.vm.state.GetSubnetManager(args.SubnetID); err { + case nil: + response.IsPermissioned = false + response.ManagerChainID = chainID + response.ManagerAddress = addr + case database.ErrNotFound: + response.ManagerChainID = ids.Empty + response.ManagerAddress = []byte(nil) + default: + return err + } + return nil } diff --git a/vms/platformvm/txs/codec.go b/vms/platformvm/txs/codec.go index 33c1b563392b..123da91b8dea 100644 --- a/vms/platformvm/txs/codec.go +++ b/vms/platformvm/txs/codec.go @@ -45,7 +45,10 @@ func init() { c.SkipRegistrations(4) - errs.Add(RegisterDurangoTypes(c)) + errs.Add( + RegisterDurangoTypes(c), + RegisterEtnaTypes(c), + ) } Codec = codec.NewDefaultManager() @@ -114,3 +117,11 @@ func RegisterDurangoTypes(targetCodec linearcodec.Codec) error { targetCodec.RegisterType(&BaseTx{}), ) } + +// RegisterEtnaTypes registers the type information for transactions that +// were valid during the Etna series of upgrades. +func RegisterEtnaTypes(targetCodec linearcodec.Codec) error { + return errors.Join( + targetCodec.RegisterType(&ConvertSubnetTx{}), + ) +} diff --git a/vms/platformvm/txs/convert_subnet_tx.go b/vms/platformvm/txs/convert_subnet_tx.go new file mode 100644 index 000000000000..3fa4193faf3c --- /dev/null +++ b/vms/platformvm/txs/convert_subnet_tx.go @@ -0,0 +1,64 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package txs + +import ( + "errors" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/vms/components/verify" + "github.com/ava-labs/avalanchego/vms/types" +) + +const MaxSubnetAddressLength = 4096 + +var ( + _ UnsignedTx = (*TransferSubnetOwnershipTx)(nil) + + ErrConvertPermissionlessSubnet = errors.New("cannot convert a permissionless subnet") + ErrAddressTooLong = errors.New("address is too long") +) + +type ConvertSubnetTx struct { + // Metadata, inputs and outputs + BaseTx `serialize:"true"` + // ID of the Subnet to transform + Subnet ids.ID `serialize:"true" json:"subnetID"` + // Chain where the Subnet manager lives + ChainID ids.ID `serialize:"true" json:"chainID"` + // Address of the Subnet manager + Address types.JSONByteSlice `serialize:"true" json:"address"` + // Authorizes this conversion + SubnetAuth verify.Verifiable `serialize:"true" json:"subnetAuthorization"` +} + +func (tx *ConvertSubnetTx) SyntacticVerify(ctx *snow.Context) error { + switch { + case tx == nil: + return ErrNilTx + case tx.SyntacticallyVerified: + // already passed syntactic verification + return nil + case tx.Subnet == constants.PrimaryNetworkID: + return ErrConvertPermissionlessSubnet + case len(tx.Address) > MaxSubnetAddressLength: + return ErrAddressTooLong + } + + if err := tx.BaseTx.SyntacticVerify(ctx); err != nil { + return err + } + if err := tx.SubnetAuth.Verify(); err != nil { + return err + } + + tx.SyntacticallyVerified = true + return nil +} + +func (tx *ConvertSubnetTx) Visit(visitor Visitor) error { + return visitor.ConvertSubnetTx(tx) +} diff --git a/vms/platformvm/txs/convert_subnet_tx_test.go b/vms/platformvm/txs/convert_subnet_tx_test.go new file mode 100644 index 000000000000..42a392f0181e --- /dev/null +++ b/vms/platformvm/txs/convert_subnet_tx_test.go @@ -0,0 +1,565 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package txs + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + _ "embed" + + "github.com/ava-labs/avalanchego/ids" + "github.com/ava-labs/avalanchego/snow/snowtest" + "github.com/ava-labs/avalanchego/utils/constants" + "github.com/ava-labs/avalanchego/utils/units" + "github.com/ava-labs/avalanchego/vms/components/avax" + "github.com/ava-labs/avalanchego/vms/platformvm/stakeable" + "github.com/ava-labs/avalanchego/vms/secp256k1fx" + "github.com/ava-labs/avalanchego/vms/types" +) + +var ( + //go:embed convert_subnet_tx_test_simple.json + convertSubnetTxSimpleJSON []byte + //go:embed convert_subnet_tx_test_complex.json + convertSubnetTxComplexJSON []byte +) + +func TestConvertSubnetTxSerialization(t *testing.T) { + var ( + addr = ids.ShortID{ + 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, + 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, + 0x44, 0x55, 0x66, 0x77, + } + avaxAssetID = ids.ID{ + 0x21, 0xe6, 0x73, 0x17, 0xcb, 0xc4, 0xbe, 0x2a, + 0xeb, 0x00, 0x67, 0x7a, 0xd6, 0x46, 0x27, 0x78, + 0xa8, 0xf5, 0x22, 0x74, 0xb9, 0xd6, 0x05, 0xdf, + 0x25, 0x91, 0xb2, 0x30, 0x27, 0xa8, 0x7d, 0xff, + } + customAssetID = ids.ID{ + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + } + txID = ids.ID{ + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + } + subnetID = ids.ID{ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, + } + managerChainID = ids.ID{ + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + } + managerAddress = []byte{ + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xde, 0xad, + } + ) + + tests := []struct { + name string + tx *ConvertSubnetTx + expectedBytes []byte + expectedJSON []byte + }{ + { + name: "simple", + tx: &ConvertSubnetTx{ + BaseTx: BaseTx{ + BaseTx: avax.BaseTx{ + NetworkID: constants.UnitTestID, + BlockchainID: constants.PlatformChainID, + Outs: []*avax.TransferableOutput{}, + Ins: []*avax.TransferableInput{ + { + UTXOID: avax.UTXOID{ + TxID: txID, + OutputIndex: 1, + }, + Asset: avax.Asset{ + ID: avaxAssetID, + }, + In: &secp256k1fx.TransferInput{ + Amt: units.MilliAvax, + Input: secp256k1fx.Input{ + SigIndices: []uint32{5}, + }, + }, + }, + }, + Memo: types.JSONByteSlice{}, + }, + }, + Subnet: subnetID, + ChainID: managerChainID, + Address: managerAddress, + SubnetAuth: &secp256k1fx.Input{ + SigIndices: []uint32{3}, + }, + }, + expectedBytes: []byte{ + // Codec version + 0x00, 0x00, + // ConvertSubnetTx Type ID + 0x00, 0x00, 0x00, 0x23, + // Network ID + 0x00, 0x00, 0x00, 0x0a, + // P-chain blockchain ID + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Number of outputs + 0x00, 0x00, 0x00, 0x00, + // Number of inputs + 0x00, 0x00, 0x00, 0x01, + // Inputs[0] + // TxID + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + // Tx output index + 0x00, 0x00, 0x00, 0x01, + // AVAX assetID + 0x21, 0xe6, 0x73, 0x17, 0xcb, 0xc4, 0xbe, 0x2a, + 0xeb, 0x00, 0x67, 0x7a, 0xd6, 0x46, 0x27, 0x78, + 0xa8, 0xf5, 0x22, 0x74, 0xb9, 0xd6, 0x05, 0xdf, + 0x25, 0x91, 0xb2, 0x30, 0x27, 0xa8, 0x7d, 0xff, + // secp256k1fx transfer input type ID + 0x00, 0x00, 0x00, 0x05, + // input amount = 1 MilliAvax + 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x42, 0x40, + // number of signatures needed in input + 0x00, 0x00, 0x00, 0x01, + // index of signer + 0x00, 0x00, 0x00, 0x05, + // length of memo + 0x00, 0x00, 0x00, 0x00, + // subnetID to modify + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, + // chainID of the manager + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + // length of the manager address + 0x00, 0x00, 0x00, 0x14, + // address of the manager + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xde, 0xad, + // secp256k1fx authorization type ID + 0x00, 0x00, 0x00, 0x0a, + // number of signatures needed in authorization + 0x00, 0x00, 0x00, 0x01, + // index of signer + 0x00, 0x00, 0x00, 0x03, + }, + expectedJSON: convertSubnetTxSimpleJSON, + }, + { + name: "complex", + tx: &ConvertSubnetTx{ + BaseTx: BaseTx{ + BaseTx: avax.BaseTx{ + NetworkID: constants.UnitTestID, + BlockchainID: constants.PlatformChainID, + Outs: []*avax.TransferableOutput{ + { + Asset: avax.Asset{ + ID: avaxAssetID, + }, + Out: &stakeable.LockOut{ + Locktime: 87654321, + TransferableOut: &secp256k1fx.TransferOutput{ + Amt: 1, + OutputOwners: secp256k1fx.OutputOwners{ + Locktime: 12345678, + Threshold: 0, + Addrs: []ids.ShortID{}, + }, + }, + }, + }, + { + Asset: avax.Asset{ + ID: customAssetID, + }, + Out: &stakeable.LockOut{ + Locktime: 876543210, + TransferableOut: &secp256k1fx.TransferOutput{ + Amt: 0xffffffffffffffff, + OutputOwners: secp256k1fx.OutputOwners{ + Locktime: 0, + Threshold: 1, + Addrs: []ids.ShortID{ + addr, + }, + }, + }, + }, + }, + }, + Ins: []*avax.TransferableInput{ + { + UTXOID: avax.UTXOID{ + TxID: txID, + OutputIndex: 1, + }, + Asset: avax.Asset{ + ID: avaxAssetID, + }, + In: &secp256k1fx.TransferInput{ + Amt: units.Avax, + Input: secp256k1fx.Input{ + SigIndices: []uint32{2, 5}, + }, + }, + }, + { + UTXOID: avax.UTXOID{ + TxID: txID, + OutputIndex: 2, + }, + Asset: avax.Asset{ + ID: customAssetID, + }, + In: &stakeable.LockIn{ + Locktime: 876543210, + TransferableIn: &secp256k1fx.TransferInput{ + Amt: 0xefffffffffffffff, + Input: secp256k1fx.Input{ + SigIndices: []uint32{0}, + }, + }, + }, + }, + { + UTXOID: avax.UTXOID{ + TxID: txID, + OutputIndex: 3, + }, + Asset: avax.Asset{ + ID: customAssetID, + }, + In: &secp256k1fx.TransferInput{ + Amt: 0x1000000000000000, + Input: secp256k1fx.Input{ + SigIndices: []uint32{}, + }, + }, + }, + }, + Memo: types.JSONByteSlice("😅\nwell that's\x01\x23\x45!"), + }, + }, + Subnet: subnetID, + ChainID: managerChainID, + Address: managerAddress, + SubnetAuth: &secp256k1fx.Input{ + SigIndices: []uint32{}, + }, + }, + expectedBytes: []byte{ + // Codec version + 0x00, 0x00, + // ConvertSubnetTx Type ID + 0x00, 0x00, 0x00, 0x23, + // Network ID + 0x00, 0x00, 0x00, 0x0a, + // P-chain blockchain ID + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // Number of outputs + 0x00, 0x00, 0x00, 0x02, + // Outputs[0] + // AVAX assetID + 0x21, 0xe6, 0x73, 0x17, 0xcb, 0xc4, 0xbe, 0x2a, + 0xeb, 0x00, 0x67, 0x7a, 0xd6, 0x46, 0x27, 0x78, + 0xa8, 0xf5, 0x22, 0x74, 0xb9, 0xd6, 0x05, 0xdf, + 0x25, 0x91, 0xb2, 0x30, 0x27, 0xa8, 0x7d, 0xff, + // Stakeable locked output type ID + 0x00, 0x00, 0x00, 0x16, + // Locktime + 0x00, 0x00, 0x00, 0x00, 0x05, 0x39, 0x7f, 0xb1, + // secp256k1fx transfer output type ID + 0x00, 0x00, 0x00, 0x07, + // amount + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + // secp256k1fx output locktime + 0x00, 0x00, 0x00, 0x00, 0x00, 0xbc, 0x61, 0x4e, + // threshold + 0x00, 0x00, 0x00, 0x00, + // number of addresses + 0x00, 0x00, 0x00, 0x00, + // Outputs[1] + // custom asset ID + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + // Stakeable locked output type ID + 0x00, 0x00, 0x00, 0x16, + // Locktime + 0x00, 0x00, 0x00, 0x00, 0x34, 0x3e, 0xfc, 0xea, + // secp256k1fx transfer output type ID + 0x00, 0x00, 0x00, 0x07, + // amount + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + // secp256k1fx output locktime + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // threshold + 0x00, 0x00, 0x00, 0x01, + // number of addresses + 0x00, 0x00, 0x00, 0x01, + // address[0] + 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, + 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, + 0x44, 0x55, 0x66, 0x77, + // number of inputs + 0x00, 0x00, 0x00, 0x03, + // inputs[0] + // TxID + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + // Tx output index + 0x00, 0x00, 0x00, 0x01, + // AVAX assetID + 0x21, 0xe6, 0x73, 0x17, 0xcb, 0xc4, 0xbe, 0x2a, + 0xeb, 0x00, 0x67, 0x7a, 0xd6, 0x46, 0x27, 0x78, + 0xa8, 0xf5, 0x22, 0x74, 0xb9, 0xd6, 0x05, 0xdf, + 0x25, 0x91, 0xb2, 0x30, 0x27, 0xa8, 0x7d, 0xff, + // secp256k1fx transfer input type ID + 0x00, 0x00, 0x00, 0x05, + // input amount = 1 Avax + 0x00, 0x00, 0x00, 0x00, 0x3b, 0x9a, 0xca, 0x00, + // number of signatures needed in input + 0x00, 0x00, 0x00, 0x02, + // index of first signer + 0x00, 0x00, 0x00, 0x02, + // index of second signer + 0x00, 0x00, 0x00, 0x05, + // inputs[1] + // TxID + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + // Tx output index + 0x00, 0x00, 0x00, 0x02, + // Custom asset ID + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + // Stakeable locked input type ID + 0x00, 0x00, 0x00, 0x15, + // Locktime + 0x00, 0x00, 0x00, 0x00, 0x34, 0x3e, 0xfc, 0xea, + // secp256k1fx transfer input type ID + 0x00, 0x00, 0x00, 0x05, + // input amount + 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + // number of signatures needed in input + 0x00, 0x00, 0x00, 0x01, + // index of signer + 0x00, 0x00, 0x00, 0x00, + // inputs[2] + // TxID + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + 0xff, 0xee, 0xdd, 0xcc, 0xbb, 0xaa, 0x99, 0x88, + // Tx output index + 0x00, 0x00, 0x00, 0x03, + // custom asset ID + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + 0x99, 0x77, 0x55, 0x77, 0x11, 0x33, 0x55, 0x31, + // secp256k1fx transfer input type ID + 0x00, 0x00, 0x00, 0x05, + // input amount + 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // number of signatures needed in input + 0x00, 0x00, 0x00, 0x00, + // length of memo + 0x00, 0x00, 0x00, 0x14, + // memo + 0xf0, 0x9f, 0x98, 0x85, 0x0a, 0x77, 0x65, 0x6c, + 0x6c, 0x20, 0x74, 0x68, 0x61, 0x74, 0x27, 0x73, + 0x01, 0x23, 0x45, 0x21, + // subnetID to modify + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, + // chainID of the manager + 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, + 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, + 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + // length of the manager address + 0x00, 0x00, 0x00, 0x14, + // address of the manager + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0xde, 0xad, + // secp256k1fx authorization type ID + 0x00, 0x00, 0x00, 0x0a, + // number of signatures needed in authorization + 0x00, 0x00, 0x00, 0x00, + }, + expectedJSON: convertSubnetTxComplexJSON, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + var unsignedTx UnsignedTx = test.tx + txBytes, err := Codec.Marshal(CodecVersion, &unsignedTx) + require.NoError(err) + require.Equal(test.expectedBytes, txBytes) + + ctx := snowtest.Context(t, constants.PlatformChainID) + test.tx.InitCtx(ctx) + + txJSON, err := json.MarshalIndent(test.tx, "", "\t") + require.NoError(err) + require.Equal( + // Normalize newlines for Windows + strings.ReplaceAll(string(test.expectedJSON), "\r\n", "\n"), + string(txJSON), + ) + }) + } +} + +func TestConvertSubnetTxSyntacticVerify(t *testing.T) { + var ( + ctx = snowtest.Context(t, ids.GenerateTestID()) + validBaseTx = BaseTx{ + BaseTx: avax.BaseTx{ + NetworkID: ctx.NetworkID, + BlockchainID: ctx.ChainID, + }, + } + validSubnetID = ids.GenerateTestID() + invalidAddress = make(types.JSONByteSlice, MaxSubnetAddressLength+1) + validSubnetAuth = &secp256k1fx.Input{} + invalidSubnetAuth = &secp256k1fx.Input{ + SigIndices: []uint32{1, 0}, + } + ) + + tests := []struct { + name string + tx *ConvertSubnetTx + expectedErr error + }{ + { + name: "nil tx", + tx: nil, + expectedErr: ErrNilTx, + }, + { + name: "already verified", + // The tx includes invalid data to verify that a cached result is + // returned. + tx: &ConvertSubnetTx{ + BaseTx: BaseTx{ + SyntacticallyVerified: true, + }, + Subnet: constants.PrimaryNetworkID, + Address: invalidAddress, + SubnetAuth: invalidSubnetAuth, + }, + expectedErr: nil, + }, + { + name: "invalid subnetID", + tx: &ConvertSubnetTx{ + BaseTx: validBaseTx, + Subnet: constants.PrimaryNetworkID, + SubnetAuth: validSubnetAuth, + }, + expectedErr: ErrConvertPermissionlessSubnet, + }, + { + name: "invalid address", + tx: &ConvertSubnetTx{ + BaseTx: validBaseTx, + Subnet: validSubnetID, + Address: invalidAddress, + SubnetAuth: validSubnetAuth, + }, + expectedErr: ErrAddressTooLong, + }, + { + name: "invalid BaseTx", + tx: &ConvertSubnetTx{ + BaseTx: BaseTx{}, + Subnet: validSubnetID, + SubnetAuth: validSubnetAuth, + }, + expectedErr: avax.ErrWrongNetworkID, + }, + { + name: "invalid subnetAuth", + tx: &ConvertSubnetTx{ + BaseTx: validBaseTx, + Subnet: validSubnetID, + SubnetAuth: invalidSubnetAuth, + }, + expectedErr: secp256k1fx.ErrInputIndicesNotSortedUnique, + }, + { + name: "passes verification", + tx: &ConvertSubnetTx{ + BaseTx: validBaseTx, + Subnet: validSubnetID, + SubnetAuth: validSubnetAuth, + }, + expectedErr: nil, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + err := test.tx.SyntacticVerify(ctx) + require.ErrorIs(err, test.expectedErr) + if test.expectedErr != nil { + return + } + require.True(test.tx.SyntacticallyVerified) + }) + } +} diff --git a/vms/platformvm/txs/convert_subnet_tx_test_complex.json b/vms/platformvm/txs/convert_subnet_tx_test_complex.json new file mode 100644 index 000000000000..b5178db2f9cb --- /dev/null +++ b/vms/platformvm/txs/convert_subnet_tx_test_complex.json @@ -0,0 +1,81 @@ +{ + "networkID": 10, + "blockchainID": "11111111111111111111111111111111LpoYY", + "outputs": [ + { + "assetID": "FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z", + "fxID": "spdxUxVJQbX85MGxMHbKw1sHxMnSqJ3QBzDyDYEP3h6TLuxqQ", + "output": { + "locktime": 87654321, + "output": { + "addresses": [], + "amount": 1, + "locktime": 12345678, + "threshold": 0 + } + } + }, + { + "assetID": "2Ab62uWwJw1T6VvmKD36ufsiuGZuX1pGykXAvPX1LtjTRHxwcc", + "fxID": "spdxUxVJQbX85MGxMHbKw1sHxMnSqJ3QBzDyDYEP3h6TLuxqQ", + "output": { + "locktime": 876543210, + "output": { + "addresses": [ + "P-testing1g32kvaugnx4tk3z4vemc3xd2hdz92enhgrdu9n" + ], + "amount": 18446744073709551615, + "locktime": 0, + "threshold": 1 + } + } + } + ], + "inputs": [ + { + "txID": "2wiU5PnFTjTmoAXGZutHAsPF36qGGyLHYHj9G1Aucfmb3JFFGN", + "outputIndex": 1, + "assetID": "FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z", + "fxID": "spdxUxVJQbX85MGxMHbKw1sHxMnSqJ3QBzDyDYEP3h6TLuxqQ", + "input": { + "amount": 1000000000, + "signatureIndices": [ + 2, + 5 + ] + } + }, + { + "txID": "2wiU5PnFTjTmoAXGZutHAsPF36qGGyLHYHj9G1Aucfmb3JFFGN", + "outputIndex": 2, + "assetID": "2Ab62uWwJw1T6VvmKD36ufsiuGZuX1pGykXAvPX1LtjTRHxwcc", + "fxID": "spdxUxVJQbX85MGxMHbKw1sHxMnSqJ3QBzDyDYEP3h6TLuxqQ", + "input": { + "locktime": 876543210, + "input": { + "amount": 17293822569102704639, + "signatureIndices": [ + 0 + ] + } + } + }, + { + "txID": "2wiU5PnFTjTmoAXGZutHAsPF36qGGyLHYHj9G1Aucfmb3JFFGN", + "outputIndex": 3, + "assetID": "2Ab62uWwJw1T6VvmKD36ufsiuGZuX1pGykXAvPX1LtjTRHxwcc", + "fxID": "spdxUxVJQbX85MGxMHbKw1sHxMnSqJ3QBzDyDYEP3h6TLuxqQ", + "input": { + "amount": 1152921504606846976, + "signatureIndices": [] + } + } + ], + "memo": "0xf09f98850a77656c6c2074686174277301234521", + "subnetID": "SkB92YpWm4UpburLz9tEKZw2i67H3FF6YkjaU4BkFUDTG9Xm", + "chainID": "NfebWJbJMmUpduqFCF8i1m5pstbVYLP1gGHbacrevXZMhpVMy", + "address": "0x000000000000000000000000000000000000dead", + "subnetAuthorization": { + "signatureIndices": [] + } +} \ No newline at end of file diff --git a/vms/platformvm/txs/convert_subnet_tx_test_simple.json b/vms/platformvm/txs/convert_subnet_tx_test_simple.json new file mode 100644 index 000000000000..8463a748141f --- /dev/null +++ b/vms/platformvm/txs/convert_subnet_tx_test_simple.json @@ -0,0 +1,28 @@ +{ + "networkID": 10, + "blockchainID": "11111111111111111111111111111111LpoYY", + "outputs": [], + "inputs": [ + { + "txID": "2wiU5PnFTjTmoAXGZutHAsPF36qGGyLHYHj9G1Aucfmb3JFFGN", + "outputIndex": 1, + "assetID": "FvwEAhmxKfeiG8SnEvq42hc6whRyY3EFYAvebMqDNDGCgxN5Z", + "fxID": "spdxUxVJQbX85MGxMHbKw1sHxMnSqJ3QBzDyDYEP3h6TLuxqQ", + "input": { + "amount": 1000000, + "signatureIndices": [ + 5 + ] + } + } + ], + "memo": "0x", + "subnetID": "SkB92YpWm4UpburLz9tEKZw2i67H3FF6YkjaU4BkFUDTG9Xm", + "chainID": "NfebWJbJMmUpduqFCF8i1m5pstbVYLP1gGHbacrevXZMhpVMy", + "address": "0x000000000000000000000000000000000000dead", + "subnetAuthorization": { + "signatureIndices": [ + 3 + ] + } +} \ No newline at end of file diff --git a/vms/platformvm/txs/executor/atomic_tx_executor.go b/vms/platformvm/txs/executor/atomic_tx_executor.go index f62abd21f818..190c5ec114c9 100644 --- a/vms/platformvm/txs/executor/atomic_tx_executor.go +++ b/vms/platformvm/txs/executor/atomic_tx_executor.go @@ -82,6 +82,10 @@ func (*AtomicTxExecutor) BaseTx(*txs.BaseTx) error { return ErrWrongTxType } +func (*AtomicTxExecutor) ConvertSubnetTx(*txs.ConvertSubnetTx) error { + return ErrWrongTxType +} + func (e *AtomicTxExecutor) ImportTx(tx *txs.ImportTx) error { return e.atomicTx(tx) } diff --git a/vms/platformvm/txs/executor/proposal_tx_executor.go b/vms/platformvm/txs/executor/proposal_tx_executor.go index f5a995772a7c..573d6199e2a3 100644 --- a/vms/platformvm/txs/executor/proposal_tx_executor.go +++ b/vms/platformvm/txs/executor/proposal_tx_executor.go @@ -100,6 +100,10 @@ func (*ProposalTxExecutor) BaseTx(*txs.BaseTx) error { return ErrWrongTxType } +func (*ProposalTxExecutor) ConvertSubnetTx(*txs.ConvertSubnetTx) error { + return ErrWrongTxType +} + func (e *ProposalTxExecutor) AddValidatorTx(tx *txs.AddValidatorTx) error { // AddValidatorTx is a proposal transaction until the Banff fork // activation. Following the activation, AddValidatorTxs must be issued into diff --git a/vms/platformvm/txs/executor/standard_tx_executor.go b/vms/platformvm/txs/executor/standard_tx_executor.go index 16e520e0af6e..d0a37f5ba82c 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor.go +++ b/vms/platformvm/txs/executor/standard_tx_executor.go @@ -28,6 +28,7 @@ var ( errEmptyNodeID = errors.New("validator nodeID cannot be empty") errMaxStakeDurationTooLarge = errors.New("max stake duration must be less than or equal to the global max stake duration") errMissingStartTimePreDurango = errors.New("staker transactions must have a StartTime pre-Durango") + errEtnaUpgradeNotActive = errors.New("attempting to use an Etna-upgrade feature prior to activation") errTransformSubnetTxPostEtna = errors.New("TransformSubnetTx is not permitted post-Etna") ) @@ -494,6 +495,57 @@ func (e *StandardTxExecutor) TransformSubnetTx(tx *txs.TransformSubnetTx) error return nil } +func (e *StandardTxExecutor) ConvertSubnetTx(tx *txs.ConvertSubnetTx) error { + var ( + currentTimestamp = e.State.GetTimestamp() + upgrades = e.Backend.Config.UpgradeConfig + ) + if !upgrades.IsEtnaActivated(currentTimestamp) { + return errEtnaUpgradeNotActive + } + + if err := e.Tx.SyntacticVerify(e.Ctx); err != nil { + return err + } + + if err := avax.VerifyMemoFieldLength(tx.Memo, true /*=isDurangoActive*/); err != nil { + return err + } + + baseTxCreds, err := verifyPoASubnetAuthorization(e.Backend, e.State, e.Tx, tx.Subnet, tx.SubnetAuth) + if err != nil { + return err + } + + // Verify the flowcheck + fee, err := e.FeeCalculator.CalculateFee(tx) + if err != nil { + return err + } + if err := e.Backend.FlowChecker.VerifySpend( + tx, + e.State, + tx.Ins, + tx.Outs, + baseTxCreds, + map[ids.ID]uint64{ + e.Ctx.AVAXAssetID: fee, + }, + ); err != nil { + return err + } + + txID := e.Tx.ID() + + // Consume the UTXOS + avax.Consume(e.State, tx.Ins) + // Produce the UTXOS + avax.Produce(e.State, txID, tx.Outs) + // Set the new Subnet manager in the database + e.State.SetSubnetManager(tx.Subnet, tx.ChainID, tx.Address) + return nil +} + func (e *StandardTxExecutor) AddPermissionlessValidatorTx(tx *txs.AddPermissionlessValidatorTx) error { if err := verifyAddPermissionlessValidatorTx( e.Backend, diff --git a/vms/platformvm/txs/executor/standard_tx_executor_test.go b/vms/platformvm/txs/executor/standard_tx_executor_test.go index 459c96c08b92..e11ad73ac5d9 100644 --- a/vms/platformvm/txs/executor/standard_tx_executor_test.go +++ b/vms/platformvm/txs/executor/standard_tx_executor_test.go @@ -14,14 +14,17 @@ import ( "go.uber.org/mock/gomock" "github.com/ava-labs/avalanchego/database" + "github.com/ava-labs/avalanchego/genesis" "github.com/ava-labs/avalanchego/ids" "github.com/ava-labs/avalanchego/snow" + "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/upgrade/upgradetest" "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/crypto/secp256k1" "github.com/ava-labs/avalanchego/utils/hashing" + "github.com/ava-labs/avalanchego/utils/logging" "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" @@ -31,8 +34,12 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/state" + "github.com/ava-labs/avalanchego/vms/platformvm/state/statetest" "github.com/ava-labs/avalanchego/vms/platformvm/status" "github.com/ava-labs/avalanchego/vms/platformvm/txs" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/fee" + "github.com/ava-labs/avalanchego/vms/platformvm/txs/txstest" + "github.com/ava-labs/avalanchego/vms/platformvm/utxo" "github.com/ava-labs/avalanchego/vms/platformvm/utxo/utxomock" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" @@ -2358,3 +2365,211 @@ func TestStandardExecutorTransformSubnetTx(t *testing.T) { }) } } + +func TestStandardExecutorConvertSubnetTx(t *testing.T) { + var ( + fx = &secp256k1fx.Fx{} + vm = &secp256k1fx.TestVM{ + Log: logging.NoLog{}, + } + ) + require.NoError(t, fx.InitializeVM(vm)) + + var ( + ctx = snowtest.Context(t, constants.PlatformChainID) + defaultConfig = &config.Config{ + DynamicFeeConfig: genesis.LocalParams.DynamicFeeConfig, + UpgradeConfig: upgradetest.GetConfig(upgradetest.Latest), + } + baseState = statetest.New(t, statetest.Config{ + Upgrades: defaultConfig.UpgradeConfig, + }) + wallet = txstest.NewWallet( + t, + ctx, + defaultConfig, + baseState, + secp256k1fx.NewKeychain(genesistest.DefaultFundedKeys...), + nil, // subnetIDs + nil, // chainIDs + ) + flowChecker = utxo.NewVerifier( + ctx, + &vm.Clk, + fx, + ) + ) + + // Create the subnet + createSubnetTx, err := wallet.IssueCreateSubnetTx( + &secp256k1fx.OutputOwners{}, + ) + require.NoError(t, err) + + diff, err := state.NewDiffOn(baseState) + require.NoError(t, err) + + require.NoError(t, createSubnetTx.Unsigned.Visit(&StandardTxExecutor{ + Backend: &Backend{ + Config: defaultConfig, + Bootstrapped: utils.NewAtomic(true), + Fx: fx, + FlowChecker: flowChecker, + Ctx: ctx, + }, + FeeCalculator: state.PickFeeCalculator(defaultConfig, baseState), + Tx: createSubnetTx, + State: diff, + })) + require.NoError(t, diff.Apply(baseState)) + require.NoError(t, baseState.Commit()) + + subnetID := createSubnetTx.ID() + tests := []struct { + name string + builderOptions []common.Option + updateExecutor func(executor *StandardTxExecutor) + expectedErr error + }{ + { + name: "invalid prior to E-Upgrade", + updateExecutor: func(e *StandardTxExecutor) { + e.Backend.Config = &config.Config{ + UpgradeConfig: upgradetest.GetConfig(upgradetest.Durango), + } + }, + expectedErr: errEtnaUpgradeNotActive, + }, + { + name: "tx fails syntactic verification", + updateExecutor: func(e *StandardTxExecutor) { + e.Backend.Ctx = snowtest.Context(t, ids.GenerateTestID()) + }, + expectedErr: avax.ErrWrongChainID, + }, + { + name: "invalid memo length", + builderOptions: []common.Option{ + common.WithMemo([]byte("memo!")), + }, + expectedErr: avax.ErrMemoTooLarge, + }, + { + name: "fail subnet authorization", + updateExecutor: func(e *StandardTxExecutor) { + e.State.SetSubnetOwner(subnetID, &secp256k1fx.OutputOwners{ + Threshold: 1, + Addrs: []ids.ShortID{ + ids.GenerateTestShortID(), + }, + }) + }, + expectedErr: errUnauthorizedSubnetModification, + }, + { + name: "invalid if subnet is transformed", + updateExecutor: func(e *StandardTxExecutor) { + e.State.AddSubnetTransformation(&txs.Tx{Unsigned: &txs.TransformSubnetTx{ + Subnet: subnetID, + }}) + }, + expectedErr: errIsImmutable, + }, + { + name: "invalid if subnet is converted", + updateExecutor: func(e *StandardTxExecutor) { + e.State.SetSubnetManager(subnetID, ids.GenerateTestID(), nil) + }, + expectedErr: errIsImmutable, + }, + { + name: "invalid fee calculation", + updateExecutor: func(e *StandardTxExecutor) { + e.FeeCalculator = fee.NewStaticCalculator(e.Config.StaticFeeConfig) + }, + expectedErr: fee.ErrUnsupportedTx, + }, + { + name: "insufficient fee", + updateExecutor: func(e *StandardTxExecutor) { + e.FeeCalculator = fee.NewDynamicCalculator( + e.Config.DynamicFeeConfig.Weights, + 100*genesis.LocalParams.DynamicFeeConfig.MinPrice, + ) + }, + expectedErr: utxo.ErrInsufficientUnlockedFunds, + }, + { + name: "valid tx", + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + require := require.New(t) + + // Create the ConvertSubnetTx + var ( + wallet = txstest.NewWallet( + t, + ctx, + defaultConfig, + baseState, + secp256k1fx.NewKeychain(genesistest.DefaultFundedKeys...), + []ids.ID{subnetID}, + nil, // chainIDs + ) + chainID = ids.GenerateTestID() + address = utils.RandomBytes(32) + ) + convertSubnetTx, err := wallet.IssueConvertSubnetTx( + subnetID, + chainID, + address, + test.builderOptions..., + ) + require.NoError(err) + + diff, err := state.NewDiffOn(baseState) + require.NoError(err) + + executor := &StandardTxExecutor{ + Backend: &Backend{ + Config: defaultConfig, + Bootstrapped: utils.NewAtomic(true), + Fx: fx, + FlowChecker: flowChecker, + Ctx: ctx, + }, + FeeCalculator: state.PickFeeCalculator(defaultConfig, baseState), + Tx: convertSubnetTx, + State: diff, + } + if test.updateExecutor != nil { + test.updateExecutor(executor) + } + + err = convertSubnetTx.Unsigned.Visit(executor) + require.ErrorIs(err, test.expectedErr) + if err != nil { + return + } + + for utxoID := range convertSubnetTx.InputIDs() { + _, err := diff.GetUTXO(utxoID) + require.ErrorIs(err, database.ErrNotFound) + } + + for _, expectedUTXO := range convertSubnetTx.UTXOs() { + utxoID := expectedUTXO.InputID() + utxo, err := diff.GetUTXO(utxoID) + require.NoError(err) + require.Equal(expectedUTXO, utxo) + } + + stateChainID, stateAddress, err := diff.GetSubnetManager(subnetID) + require.NoError(err) + require.Equal(chainID, stateChainID) + require.Equal(address, stateAddress) + }) + } +} diff --git a/vms/platformvm/txs/fee/calculator_test.go b/vms/platformvm/txs/fee/calculator_test.go index 843f20d13e9d..172f927e9796 100644 --- a/vms/platformvm/txs/fee/calculator_test.go +++ b/vms/platformvm/txs/fee/calculator_test.go @@ -219,5 +219,17 @@ var ( }, expectedDynamicFee: 173_600, }, + { + name: "ConvertSubnetTx", + tx: "00000000002300015b380000000000000000000000000000000000000000000000000000000000000000000000012a16b813b6a4a64d8e9b3f11460b782fcc319364bc038915af56834b72043ce80000000700470de4d97cdcc00000000000000000000000010000000180fa21568b6a2ef338a773ba18bfc0cb493af926000000018d65db2676f4733a7d263ad14606ddbc2f1996bb2998358f4b6f1e01297d1da5000000002a16b813b6a4a64d8e9b3f11460b782fcc319364bc038915af56834b72043ce80000000500470de4d98c1f000000000100000000000000008d65db2676f4733a7d263ad14606ddbc2f1996bb2998358f4b6f1e01297d1da55fa29ed4356903dac2364713c60f57d8472c7dda4a5e08d88a88ad8ea71aed6000000007616464726573730000000a0000000100000000000000020000000900000001c990ecf3f39646c4c90cb1f5cc2a9a98c33df1a9a41a084e7f3e7b2afe10fd853068a20ad4ddf83c087b6311ab0fdab339ca529f57cda3329ca31b142987c223000000000900000001c990ecf3f39646c4c90cb1f5cc2a9a98c33df1a9a41a084e7f3e7b2afe10fd853068a20ad4ddf83c087b6311ab0fdab339ca529f57cda3329ca31b142987c22300", + expectedStaticFeeErr: ErrUnsupportedTx, + expectedComplexity: gas.Dimensions{ + gas.Bandwidth: 459, // The length of the tx in bytes + gas.DBRead: IntrinsicConvertSubnetTxComplexities[gas.DBRead] + intrinsicInputDBRead, + gas.DBWrite: IntrinsicConvertSubnetTxComplexities[gas.DBWrite] + intrinsicInputDBWrite + intrinsicOutputDBWrite, + gas.Compute: 0, // TODO: implement + }, + expectedDynamicFee: 175_900, + }, } ) diff --git a/vms/platformvm/txs/fee/complexity.go b/vms/platformvm/txs/fee/complexity.go index adae002e0009..02942e09b76f 100644 --- a/vms/platformvm/txs/fee/complexity.go +++ b/vms/platformvm/txs/fee/complexity.go @@ -175,6 +175,17 @@ var ( gas.DBWrite: 1, gas.Compute: 0, } + IntrinsicConvertSubnetTxComplexities = gas.Dimensions{ + gas.Bandwidth: IntrinsicBaseTxComplexities[gas.Bandwidth] + + ids.IDLen + // subnetID + ids.IDLen + // chainID + wrappers.IntLen + // address length + wrappers.IntLen + // subnetAuth typeID + wrappers.IntLen, // subnetAuthCredential typeID + gas.DBRead: 1, + gas.DBWrite: 1, + gas.Compute: 0, + } errUnsupportedOutput = errors.New("unsupported output type") errUnsupportedInput = errors.New("unsupported input type") @@ -594,6 +605,25 @@ func (c *complexityVisitor) TransferSubnetOwnershipTx(tx *txs.TransferSubnetOwne return err } +func (c *complexityVisitor) ConvertSubnetTx(tx *txs.ConvertSubnetTx) error { + baseTxComplexity, err := baseTxComplexity(&tx.BaseTx) + if err != nil { + return err + } + authComplexity, err := AuthComplexity(tx.SubnetAuth) + if err != nil { + return err + } + c.output, err = IntrinsicConvertSubnetTxComplexities.Add( + &baseTxComplexity, + &authComplexity, + &gas.Dimensions{ + gas.Bandwidth: uint64(len(tx.Address)), + }, + ) + return err +} + func baseTxComplexity(tx *txs.BaseTx) (gas.Dimensions, error) { outputsComplexity, err := OutputComplexity(tx.Outs...) if err != nil { diff --git a/vms/platformvm/txs/fee/static_calculator.go b/vms/platformvm/txs/fee/static_calculator.go index 9b79e573db70..888ccba8621c 100644 --- a/vms/platformvm/txs/fee/static_calculator.go +++ b/vms/platformvm/txs/fee/static_calculator.go @@ -47,6 +47,10 @@ func (*staticVisitor) RewardValidatorTx(*txs.RewardValidatorTx) error { return ErrUnsupportedTx } +func (*staticVisitor) ConvertSubnetTx(*txs.ConvertSubnetTx) error { + return ErrUnsupportedTx +} + func (c *staticVisitor) AddValidatorTx(*txs.AddValidatorTx) error { c.fee = c.config.AddPrimaryNetworkValidatorFee return nil diff --git a/vms/platformvm/txs/visitor.go b/vms/platformvm/txs/visitor.go index b3fc55af4cf3..142a6115d7af 100644 --- a/vms/platformvm/txs/visitor.go +++ b/vms/platformvm/txs/visitor.go @@ -19,5 +19,6 @@ type Visitor interface { AddPermissionlessValidatorTx(*AddPermissionlessValidatorTx) error AddPermissionlessDelegatorTx(*AddPermissionlessDelegatorTx) error TransferSubnetOwnershipTx(*TransferSubnetOwnershipTx) error + ConvertSubnetTx(*ConvertSubnetTx) error BaseTx(*BaseTx) error } diff --git a/wallet/chain/p/builder/builder.go b/wallet/chain/p/builder/builder.go index b665617e0e16..5a0b063280fd 100644 --- a/wallet/chain/p/builder/builder.go +++ b/wallet/chain/p/builder/builder.go @@ -150,6 +150,18 @@ type Builder interface { options ...common.Option, ) (*txs.TransferSubnetOwnershipTx, error) + // NewConvertSubnetTx converts the subnet to a Permissionless L1. + // + // - [subnetID] specifies the subnet to be converted + // - [chainID] specifies which chain the manager is deployed on + // - [address] specifies the address of the manager + NewConvertSubnetTx( + subnetID ids.ID, + chainID ids.ID, + address []byte, + options ...common.Option, + ) (*txs.ConvertSubnetTx, error) + // NewImportTx creates an import transaction that attempts to consume all // the available UTXOs and import the funds to [to]. // @@ -766,6 +778,69 @@ func (b *builder) NewTransferSubnetOwnershipTx( return tx, b.initCtx(tx) } +func (b *builder) NewConvertSubnetTx( + subnetID ids.ID, + chainID ids.ID, + address []byte, + options ...common.Option, +) (*txs.ConvertSubnetTx, error) { + toBurn := map[ids.ID]uint64{} + toStake := map[ids.ID]uint64{} + + ops := common.NewOptions(options) + subnetAuth, err := b.authorizeSubnet(subnetID, ops) + if err != nil { + return nil, err + } + + memo := ops.Memo() + additionalBytes, err := math.Add(uint64(len(memo)), uint64(len(address))) + if err != nil { + return nil, err + } + bytesComplexity := gas.Dimensions{ + gas.Bandwidth: additionalBytes, + } + authComplexity, err := fee.AuthComplexity(subnetAuth) + if err != nil { + return nil, err + } + complexity, err := fee.IntrinsicConvertSubnetTxComplexities.Add( + &bytesComplexity, + &authComplexity, + ) + if err != nil { + return nil, err + } + + inputs, outputs, _, err := b.spend( + toBurn, + toStake, + 0, + complexity, + nil, + ops, + ) + if err != nil { + return nil, err + } + + tx := &txs.ConvertSubnetTx{ + BaseTx: txs.BaseTx{BaseTx: avax.BaseTx{ + NetworkID: b.context.NetworkID, + BlockchainID: constants.PlatformChainID, + Ins: inputs, + Outs: outputs, + Memo: memo, + }}, + Subnet: subnetID, + ChainID: chainID, + Address: address, + SubnetAuth: subnetAuth, + } + return tx, b.initCtx(tx) +} + func (b *builder) NewImportTx( sourceChainID ids.ID, to *secp256k1fx.OutputOwners, diff --git a/wallet/chain/p/builder/builder_with_options.go b/wallet/chain/p/builder/builder_with_options.go index d831e0c76daa..4a473cf50bac 100644 --- a/wallet/chain/p/builder/builder_with_options.go +++ b/wallet/chain/p/builder/builder_with_options.go @@ -155,6 +155,20 @@ func (b *builderWithOptions) NewTransferSubnetOwnershipTx( ) } +func (b *builderWithOptions) NewConvertSubnetTx( + subnetID ids.ID, + chainID ids.ID, + address []byte, + options ...common.Option, +) (*txs.ConvertSubnetTx, error) { + return b.builder.NewConvertSubnetTx( + subnetID, + chainID, + address, + common.UnionOptions(b.options, options)..., + ) +} + func (b *builderWithOptions) NewImportTx( sourceChainID ids.ID, to *secp256k1fx.OutputOwners, diff --git a/wallet/chain/p/builder_test.go b/wallet/chain/p/builder_test.go index e2a970b909cc..54892dfb32c7 100644 --- a/wallet/chain/p/builder_test.go +++ b/wallet/chain/p/builder_test.go @@ -666,6 +666,46 @@ func TestAddPermissionlessDelegatorTx(t *testing.T) { } } +func TestConvertSubnetTx(t *testing.T) { + var ( + chainID = ids.GenerateTestID() + address = utils.RandomBytes(32) + ) + for _, e := range testEnvironmentPostEtna { + t.Run(e.name, func(t *testing.T) { + var ( + require = require.New(t) + chainUTXOs = utxotest.NewDeterministicChainUTXOs(t, map[ids.ID][]*avax.UTXO{ + constants.PlatformChainID: utxos, + }) + backend = wallet.NewBackend(e.context, chainUTXOs, subnetOwners) + builder = builder.New(set.Of(utxoAddr, subnetAuthAddr), e.context, backend) + ) + + utx, err := builder.NewConvertSubnetTx( + subnetID, + chainID, + address, + common.WithMemo(e.memo), + ) + require.NoError(err) + require.Equal(subnetID, utx.Subnet) + require.Equal(chainID, utx.ChainID) + require.Equal(types.JSONByteSlice(address), utx.Address) + require.Equal(types.JSONByteSlice(e.memo), utx.Memo) + requireFeeIsCorrect( + require, + e.feeCalculator, + utx, + &utx.BaseTx.BaseTx, + nil, + nil, + nil, + ) + }) + } +} + func makeTestUTXOs(utxosKey *secp256k1.PrivateKey) []*avax.UTXO { // Note: we avoid ids.GenerateTestNodeID here to make sure that UTXO IDs // won't change run by run. This simplifies checking what utxos are included diff --git a/wallet/chain/p/signer/visitor.go b/wallet/chain/p/signer/visitor.go index 5dd4abe2b7d2..38d501c908b0 100644 --- a/wallet/chain/p/signer/visitor.go +++ b/wallet/chain/p/signer/visitor.go @@ -156,6 +156,19 @@ func (s *visitor) TransferSubnetOwnershipTx(tx *txs.TransferSubnetOwnershipTx) e return sign(s.tx, true, txSigners) } +func (s *visitor) ConvertSubnetTx(tx *txs.ConvertSubnetTx) error { + txSigners, err := s.getSigners(constants.PlatformChainID, tx.Ins) + if err != nil { + return err + } + subnetAuthSigners, err := s.getSubnetSigners(tx.Subnet, tx.SubnetAuth) + if err != nil { + return err + } + txSigners = append(txSigners, subnetAuthSigners) + return sign(s.tx, true, txSigners) +} + func (s *visitor) TransformSubnetTx(tx *txs.TransformSubnetTx) error { txSigners, err := s.getSigners(constants.PlatformChainID, tx.Ins) if err != nil { diff --git a/wallet/chain/p/wallet/backend_visitor.go b/wallet/chain/p/wallet/backend_visitor.go index 61dc3e231da7..8e44ee3b5e2d 100644 --- a/wallet/chain/p/wallet/backend_visitor.go +++ b/wallet/chain/p/wallet/backend_visitor.go @@ -70,6 +70,10 @@ func (b *backendVisitor) TransferSubnetOwnershipTx(tx *txs.TransferSubnetOwnersh return b.baseTx(&tx.BaseTx) } +func (b *backendVisitor) ConvertSubnetTx(tx *txs.ConvertSubnetTx) error { + return b.baseTx(&tx.BaseTx) +} + func (b *backendVisitor) BaseTx(tx *txs.BaseTx) error { return b.baseTx(tx) } diff --git a/wallet/chain/p/wallet/wallet.go b/wallet/chain/p/wallet/wallet.go index d7414f1b3e28..4e2886d41e88 100644 --- a/wallet/chain/p/wallet/wallet.go +++ b/wallet/chain/p/wallet/wallet.go @@ -135,6 +135,19 @@ type Wallet interface { options ...common.Option, ) (*txs.Tx, error) + // IssueConvertSubnetTx creates, signs, and issues a transaction that + // converts the subnet to a Permissionless L1. + // + // - [subnetID] specifies the subnet to be converted + // - [chainID] specifies which chain the manager is deployed on + // - [address] specifies the address of the manager + IssueConvertSubnetTx( + subnetID ids.ID, + chainID ids.ID, + address []byte, + options ...common.Option, + ) (*txs.Tx, error) + // IssueImportTx creates, signs, and issues an import transaction that // attempts to consume all the available UTXOs and import the funds to [to]. // @@ -375,6 +388,19 @@ func (w *wallet) IssueTransferSubnetOwnershipTx( return w.IssueUnsignedTx(utx, options...) } +func (w *wallet) IssueConvertSubnetTx( + subnetID ids.ID, + chainID ids.ID, + address []byte, + options ...common.Option, +) (*txs.Tx, error) { + utx, err := w.builder.NewConvertSubnetTx(subnetID, chainID, address, options...) + if err != nil { + return nil, err + } + return w.IssueUnsignedTx(utx, options...) +} + func (w *wallet) IssueImportTx( sourceChainID ids.ID, to *secp256k1fx.OutputOwners, diff --git a/wallet/chain/p/wallet/with_options.go b/wallet/chain/p/wallet/with_options.go index 64b22050a953..7082764aa18d 100644 --- a/wallet/chain/p/wallet/with_options.go +++ b/wallet/chain/p/wallet/with_options.go @@ -143,6 +143,20 @@ func (w *withOptions) IssueTransferSubnetOwnershipTx( ) } +func (w *withOptions) IssueConvertSubnetTx( + subnetID ids.ID, + chainID ids.ID, + address []byte, + options ...common.Option, +) (*txs.Tx, error) { + return w.wallet.IssueConvertSubnetTx( + subnetID, + chainID, + address, + common.UnionOptions(w.options, options)..., + ) +} + func (w *withOptions) IssueImportTx( sourceChainID ids.ID, to *secp256k1fx.OutputOwners, From ca0228a961cbec97b505db53acf78dec5ee87bf0 Mon Sep 17 00:00:00 2001 From: marun Date: Wed, 4 Sep 2024 07:14:46 -0700 Subject: [PATCH 62/69] [e2e] Emit a duration-scoped grafana link for each test (#3340) Signed-off-by: marun Co-authored-by: Stephen Buttolph --- tests/e2e/c/dynamic_fees.go | 7 ++++ tests/fixture/e2e/env.go | 3 ++ tests/fixture/e2e/flags.go | 9 +++-- tests/fixture/e2e/metrics_link.go | 55 +++++++++++++++++++++++++++++++ tests/fixture/tmpnet/network.go | 22 ++++++++++++- 5 files changed, 92 insertions(+), 4 deletions(-) create mode 100644 tests/fixture/e2e/metrics_link.go diff --git a/tests/e2e/c/dynamic_fees.go b/tests/e2e/c/dynamic_fees.go index 6b554087a996..409d41056e1f 100644 --- a/tests/e2e/c/dynamic_fees.go +++ b/tests/e2e/c/dynamic_fees.go @@ -39,6 +39,13 @@ var _ = e2e.DescribeCChain("[Dynamic Fees]", func() { privateNetwork := tmpnet.NewDefaultNetwork("avalanchego-e2e-dynamic-fees") e2e.GetEnv(tc).StartPrivateNetwork(privateNetwork) + // Avoid emitting a spec-scoped metrics link for the shared + // network since the link emitted by the start of the private + // network is more relevant. + // + // TODO(marun) Make this implicit to the start of a private network + e2e.EmitMetricsLink = false + tc.By("allocating a pre-funded key") key := privateNetwork.PreFundedKeys[0] ethAddress := evm.GetEthAddress(key) diff --git a/tests/fixture/e2e/env.go b/tests/fixture/e2e/env.go index a8b10c19c9fa..f39961dfb522 100644 --- a/tests/fixture/e2e/env.go +++ b/tests/fixture/e2e/env.go @@ -58,6 +58,9 @@ type TestEnvironment struct { // Retrieve the test environment configured with the provided test context. func GetEnv(tc tests.TestContext) *TestEnvironment { + if env == nil { + return nil + } return &TestEnvironment{ NetworkDir: env.NetworkDir, URIs: env.URIs, diff --git a/tests/fixture/e2e/flags.go b/tests/fixture/e2e/flags.go index 05d698ce6262..f87132b0c974 100644 --- a/tests/fixture/e2e/flags.go +++ b/tests/fixture/e2e/flags.go @@ -12,6 +12,10 @@ import ( "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" ) +// Ensure that this value takes into account the scrape_interval +// defined in scripts/run_prometheus.sh. +const networkShutdownDelay = 12 * time.Second + type FlagVars struct { avalancheGoExecPath string pluginDir string @@ -52,9 +56,8 @@ func (v *FlagVars) RestartNetwork() bool { func (v *FlagVars) NetworkShutdownDelay() time.Duration { if v.delayNetworkShutdown { - // Only return a non-zero value if the delay is enabled. Make sure this value takes - // into account the scrape_interval defined in scripts/run_prometheus.sh. - return 12 * time.Second + // Only return a non-zero value if the delay is enabled. + return networkShutdownDelay } return 0 } diff --git a/tests/fixture/e2e/metrics_link.go b/tests/fixture/e2e/metrics_link.go new file mode 100644 index 000000000000..97ccd7e7d3d9 --- /dev/null +++ b/tests/fixture/e2e/metrics_link.go @@ -0,0 +1,55 @@ +// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. +// See the file LICENSE for licensing terms. + +package e2e + +import ( + "strconv" + "time" + + "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" + + ginkgo "github.com/onsi/ginkgo/v2" +) + +// The ginkgo event handlers defined in this file will be automatically +// applied to all ginkgo suites importing this package. + +// Whether a spec-scoped metrics link should be emitted after the current +// spec finishes executing. +var EmitMetricsLink bool + +// This event handler ensures that by default a spec-scoped metrics link +// will be emitted at the end of spec execution. If the test uses a +// private network, it can disable this behavior by setting +// EmitMetricsLink to false. +// +// TODO(marun) Make this conditional on metrics collection being enabled +var _ = ginkgo.BeforeEach(func() { + EmitMetricsLink = true +}) + +// This event handler attempts to emit a metrics link scoped to the duration +// of the current spec. +// +// TODO(marun) Make this conditional on metrics collection being enabled +var _ = ginkgo.AfterEach(func() { + tc := NewTestContext() + env := GetEnv(tc) + if env == nil || !EmitMetricsLink { + return + } + + specReport := ginkgo.CurrentSpecReport() + startTime := specReport.StartTime.UnixMilli() + // Extend the end time by the shutdown delay (a proxy for the metrics + // scrape interval) to maximize the chances of the specified duration + // including all metrics relevant to the current spec. + endTime := time.Now().Add(networkShutdownDelay).UnixMilli() + metricsLink := tmpnet.MetricsLinkForNetwork( + env.GetNetwork().UUID, + strconv.FormatInt(startTime, 10), + strconv.FormatInt(endTime, 10), + ) + tc.Outf("Test Metrics: %s\n", metricsLink) +}) diff --git a/tests/fixture/tmpnet/network.go b/tests/fixture/tmpnet/network.go index 3eec5cdf7a06..96798b063b3b 100644 --- a/tests/fixture/tmpnet/network.go +++ b/tests/fixture/tmpnet/network.go @@ -373,7 +373,9 @@ func (n *Network) StartNodes(ctx context.Context, w io.Writer, nodesToStart ...* return err } // Provide a link to the main dashboard filtered by the uuid and showing results from now till whenever the link is viewed - if _, err := fmt.Fprintf(w, "\nMetrics: https://grafana-poc.avax-dev.network/d/kBQpRdWnk/avalanche-main-dashboard?&var-filter=network_uuid%%7C%%3D%%7C%s&var-filter=is_ephemeral_node%%7C%%3D%%7Cfalse&from=%d&to=now\n", n.UUID, startTime.UnixMilli()); err != nil { + startTimeStr := strconv.FormatInt(startTime.UnixMilli(), 10) + metricsURL := MetricsLinkForNetwork(n.UUID, startTimeStr, "") + if _, err := fmt.Fprintf(w, "\nMetrics: %s\n", metricsURL); err != nil { return err } @@ -1009,3 +1011,21 @@ func getRPCVersion(command string, versionArgs ...string) (uint64, error) { return version.RPCChainVM, nil } + +// MetricsLinkForNetwork returns a link to the default metrics dashboard for the network +// with the given UUID. The start and end times are accepted as strings to support the +// use of Grafana's time range syntax (e.g. `now`, `now-1h`). +func MetricsLinkForNetwork(networkUUID string, startTime string, endTime string) string { + if startTime == "" { + startTime = "now-1h" + } + if endTime == "" { + endTime = "now" + } + return fmt.Sprintf( + "https://grafana-poc.avax-dev.network/d/kBQpRdWnk/avalanche-main-dashboard?&var-filter=network_uuid%%7C%%3D%%7C%s&var-filter=is_ephemeral_node%%7C%%3D%%7Cfalse&from=%s&to=%s", + networkUUID, + startTime, + endTime, + ) +} From f733ece4ffb145df58ff2738f665a9b2e0f244ce Mon Sep 17 00:00:00 2001 From: marun Date: Wed, 4 Sep 2024 08:54:03 -0700 Subject: [PATCH 63/69] [tmpnet] Avoid calling Stat in advance of Read/Open (#3356) --- tests/fixture/tmpnet/node_process.go | 8 +++----- tests/fixture/tmpnet/subnet.go | 9 +++------ 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/tests/fixture/tmpnet/node_process.go b/tests/fixture/tmpnet/node_process.go index d7d95a697dd5..b33fe32f0730 100644 --- a/tests/fixture/tmpnet/node_process.go +++ b/tests/fixture/tmpnet/node_process.go @@ -77,14 +77,12 @@ func (p *NodeProcess) setProcessContext(processContext node.NodeProcessContext) func (p *NodeProcess) readState() error { path := p.getProcessContextPath() - if _, err := os.Stat(path); errors.Is(err, fs.ErrNotExist) { + bytes, err := os.ReadFile(path) + if errors.Is(err, fs.ErrNotExist) { // The absence of the process context file indicates the node is not running p.setProcessContext(node.NodeProcessContext{}) return nil - } - - bytes, err := os.ReadFile(path) - if err != nil { + } else if err != nil { return fmt.Errorf("failed to read node process context: %w", err) } processContext := node.NodeProcessContext{} diff --git a/tests/fixture/tmpnet/subnet.go b/tests/fixture/tmpnet/subnet.go index a9062f2fb5cc..1e1d3c749c7a 100644 --- a/tests/fixture/tmpnet/subnet.go +++ b/tests/fixture/tmpnet/subnet.go @@ -6,6 +6,7 @@ package tmpnet import ( "context" "encoding/json" + "errors" "fmt" "io" "os" @@ -339,14 +340,10 @@ func WaitForActiveValidators( // Reads subnets from [network dir]/subnets/[subnet name].json func readSubnets(subnetDir string) ([]*Subnet, error) { - if _, err := os.Stat(subnetDir); os.IsNotExist(err) { + entries, err := os.ReadDir(subnetDir) + if errors.Is(err, os.ErrNotExist) { return nil, nil } else if err != nil { - return nil, err - } - - entries, err := os.ReadDir(subnetDir) - if err != nil { return nil, fmt.Errorf("failed to read subnet dir: %w", err) } From 84a2c77186ce66381ec1dbdca5b8537472bd46e2 Mon Sep 17 00:00:00 2001 From: containerman17 <8990432+containerman17@users.noreply.github.com> Date: Wed, 4 Sep 2024 13:42:47 -0400 Subject: [PATCH 64/69] UnmarshalFrom support in codec.Codec (#3335) Signed-off-by: aaronbuchwald Co-authored-by: aaronbuchwald Co-authored-by: Stephen Buttolph --- codec/codec.go | 3 +-- codec/codectest/codectest.go | 34 ++++++++++++++++++++++++++++++++ codec/manager.go | 15 +++++++++++++- codec/reflectcodec/type_codec.go | 19 +++--------------- 4 files changed, 52 insertions(+), 19 deletions(-) diff --git a/codec/codec.go b/codec/codec.go index 6ee799667182..8d6ab445c617 100644 --- a/codec/codec.go +++ b/codec/codec.go @@ -14,7 +14,6 @@ var ( ErrMaxSliceLenExceeded = errors.New("max slice length exceeded") ErrDoesNotImplementInterface = errors.New("does not implement interface") ErrUnexportedField = errors.New("unexported field") - ErrExtraSpace = errors.New("trailing buffer space") ErrMarshalZeroLength = errors.New("can't marshal zero length value") ErrUnmarshalZeroLength = errors.New("can't unmarshal zero length value") ) @@ -22,7 +21,7 @@ var ( // Codec marshals and unmarshals type Codec interface { MarshalInto(interface{}, *wrappers.Packer) error - Unmarshal([]byte, interface{}) error + UnmarshalFrom(*wrappers.Packer, interface{}) error // Returns the size, in bytes, of [value] when it's marshaled Size(value interface{}) (int, error) diff --git a/codec/codectest/codectest.go b/codec/codectest/codectest.go index 528782fe9139..95e4ba473ece 100644 --- a/codec/codectest/codectest.go +++ b/codec/codectest/codectest.go @@ -10,6 +10,8 @@ import ( "github.com/stretchr/testify/require" + "github.com/ava-labs/avalanchego/utils/wrappers" + codecpkg "github.com/ava-labs/avalanchego/codec" ) @@ -75,6 +77,7 @@ var ( {"Slice Length Overflow", TestSliceLengthOverflow}, {"Map", TestMap}, {"Can Marshal Large Slices", TestCanMarshalLargeSlices}, + {"Implements UnmarshalFrom", TestImplementsUnmarshalFrom}, } MultipleTagsTests = []NamedTest{ @@ -1153,3 +1156,34 @@ func FuzzStructUnmarshal(codec codecpkg.GeneralCodec, f *testing.F) { require.Len(bytes, size) }) } + +func TestImplementsUnmarshalFrom(t testing.TB, codec codecpkg.GeneralCodec) { + require := require.New(t) + + p := wrappers.Packer{MaxSize: 1024} + p.PackFixedBytes([]byte{0, 1, 2}) // pack 3 extra bytes prefix + + mySlice := []bool{true, false, true, true} + + require.NoError(codec.MarshalInto(mySlice, &p)) + + p.PackFixedBytes([]byte{7, 7, 7}) // pack 3 extra bytes suffix + + bytesLen, err := codec.Size(mySlice) + require.NoError(err) + require.Equal(3+bytesLen+3, p.Offset) + + p = wrappers.Packer{Bytes: p.Bytes, MaxSize: p.MaxSize, Offset: 3} + + var sliceUnmarshaled []bool + require.NoError(codec.UnmarshalFrom(&p, &sliceUnmarshaled)) + require.Equal(mySlice, sliceUnmarshaled) + require.Equal( + wrappers.Packer{ + Bytes: p.Bytes, + MaxSize: p.MaxSize, + Offset: 11, + }, + p, + ) +} diff --git a/codec/manager.go b/codec/manager.go index 00de14e5c9a9..8230a5430c95 100644 --- a/codec/manager.go +++ b/codec/manager.go @@ -32,6 +32,7 @@ var ( ErrCantPackVersion = errors.New("couldn't pack codec version") ErrCantUnpackVersion = errors.New("couldn't unpack codec version") ErrDuplicatedVersion = errors.New("duplicated codec version") + ErrExtraSpace = errors.New("trailing buffer space") ) var _ Manager = (*manager)(nil) @@ -157,5 +158,17 @@ func (m *manager) Unmarshal(bytes []byte, dest interface{}) (uint16, error) { if !exists { return version, ErrUnknownVersion } - return version, c.Unmarshal(p.Bytes[p.Offset:], dest) + + if err := c.UnmarshalFrom(&p, dest); err != nil { + return version, err + } + if p.Offset != len(bytes) { + return version, fmt.Errorf("%w: read %d provided %d", + ErrExtraSpace, + p.Offset, + len(bytes), + ) + } + + return version, nil } diff --git a/codec/reflectcodec/type_codec.go b/codec/reflectcodec/type_codec.go index 901ff2bc9065..649b691810be 100644 --- a/codec/reflectcodec/type_codec.go +++ b/codec/reflectcodec/type_codec.go @@ -496,31 +496,18 @@ func (c *genericCodec) marshal( } } -// Unmarshal unmarshals [bytes] into [dest], where [dest] must be a pointer or +// UnmarshalFrom unmarshals [p.Bytes] into [dest], where [dest] must be a pointer or // interface -func (c *genericCodec) Unmarshal(bytes []byte, dest interface{}) error { +func (c *genericCodec) UnmarshalFrom(p *wrappers.Packer, dest interface{}) error { if dest == nil { return codec.ErrUnmarshalNil } - p := wrappers.Packer{ - Bytes: bytes, - } destPtr := reflect.ValueOf(dest) if destPtr.Kind() != reflect.Ptr { return errNeedPointer } - if err := c.unmarshal(&p, destPtr.Elem(), nil /*=typeStack*/); err != nil { - return err - } - if p.Offset != len(bytes) { - return fmt.Errorf("%w: read %d provided %d", - codec.ErrExtraSpace, - p.Offset, - len(bytes), - ) - } - return nil + return c.unmarshal(p, destPtr.Elem(), nil /*=typeStack*/) } // Unmarshal from p.Bytes into [value]. [value] must be addressable. From 173345aa1f62041cffa6a46a2e2e28b049344ddc Mon Sep 17 00:00:00 2001 From: Stephen Buttolph Date: Wed, 4 Sep 2024 18:50:07 -0400 Subject: [PATCH 65/69] Include stacktrace in shutdown timeout message (#3360) --- snow/networking/router/chain_router.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/snow/networking/router/chain_router.go b/snow/networking/router/chain_router.go index d319e721c639..46c6e80545df 100644 --- a/snow/networking/router/chain_router.go +++ b/snow/networking/router/chain_router.go @@ -20,6 +20,7 @@ import ( "github.com/ava-labs/avalanchego/snow/networking/benchlist" "github.com/ava-labs/avalanchego/snow/networking/handler" "github.com/ava-labs/avalanchego/snow/networking/timeout" + "github.com/ava-labs/avalanchego/utils" "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/utils/linked" "github.com/ava-labs/avalanchego/utils/logging" @@ -377,6 +378,7 @@ func (cr *ChainRouter) Shutdown(ctx context.Context) { chainLog := chain.Context().Log if err != nil { chainLog.Warn("timed out while shutting down", + zap.String("stack", utils.GetStacktrace(true)), zap.Error(err), ) } else { @@ -700,6 +702,7 @@ func (cr *ChainRouter) removeChain(ctx context.Context, chainID ids.ID) { chainLog := chain.Context().Log if err != nil { chainLog.Warn("timed out while shutting down", + zap.String("stack", utils.GetStacktrace(true)), zap.Error(err), ) } else { From 718128aacc1989a2311b0551a2a1ad3d5ce52be8 Mon Sep 17 00:00:00 2001 From: marun Date: Wed, 4 Sep 2024 20:06:32 -0700 Subject: [PATCH 66/69] [testing] Cleanup ginkgo imports (#3362) --- tests/e2e/banff/suites.go | 3 +-- tests/e2e/c/dynamic_fees.go | 3 +-- tests/e2e/c/interchain_workflow.go | 3 +-- tests/e2e/e2e_test.go | 3 +-- tests/e2e/etna/suites.go | 3 +-- tests/e2e/faultinjection/duplicate_node_id.go | 3 +-- tests/e2e/p/elastic_subnets.go | 3 +-- tests/e2e/p/interchain_workflow.go | 3 +-- tests/e2e/p/owner_retrieval.go | 3 +-- tests/e2e/p/permissionless_layer_one.go | 3 +-- tests/e2e/p/staking_rewards.go | 3 +-- tests/e2e/p/validator_sets.go | 3 +-- tests/e2e/p/workflow.go | 3 +-- tests/e2e/vms/xsvm.go | 3 +-- tests/e2e/x/interchain_workflow.go | 3 +-- tests/e2e/x/transfer/virtuous.go | 3 +-- tests/fixture/e2e/describe.go | 4 +--- tests/fixture/e2e/env.go | 3 +-- tests/fixture/e2e/ginkgo_test_context.go | 3 +-- tests/fixture/e2e/metrics_link.go | 7 +++++-- 20 files changed, 24 insertions(+), 41 deletions(-) diff --git a/tests/e2e/banff/suites.go b/tests/e2e/banff/suites.go index 2790077a1a04..f89203cd510e 100644 --- a/tests/e2e/banff/suites.go +++ b/tests/e2e/banff/suites.go @@ -5,6 +5,7 @@ package banff import ( + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" @@ -14,8 +15,6 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/components/verify" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = ginkgo.Describe("[Banff]", func() { diff --git a/tests/e2e/c/dynamic_fees.go b/tests/e2e/c/dynamic_fees.go index 409d41056e1f..873b76f9a684 100644 --- a/tests/e2e/c/dynamic_fees.go +++ b/tests/e2e/c/dynamic_fees.go @@ -12,12 +12,11 @@ import ( "github.com/ava-labs/coreth/plugin/evm" "github.com/ethereum/go-ethereum/accounts/abi" "github.com/ethereum/go-ethereum/common" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" - - ginkgo "github.com/onsi/ginkgo/v2" ) // This test uses the compiled bin for `hashing.sol` as diff --git a/tests/e2e/c/interchain_workflow.go b/tests/e2e/c/interchain_workflow.go index 613020700454..f4b9cc85c544 100644 --- a/tests/e2e/c/interchain_workflow.go +++ b/tests/e2e/c/interchain_workflow.go @@ -8,6 +8,7 @@ import ( "github.com/ava-labs/coreth/core/types" "github.com/ava-labs/coreth/plugin/evm" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" @@ -17,8 +18,6 @@ import ( "github.com/ava-labs/avalanchego/utils/units" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = e2e.DescribeCChain("[Interchain Workflow]", func() { diff --git a/tests/e2e/e2e_test.go b/tests/e2e/e2e_test.go index eb2dbb6e7e6c..017687038448 100644 --- a/tests/e2e/e2e_test.go +++ b/tests/e2e/e2e_test.go @@ -8,6 +8,7 @@ import ( "encoding/json" "testing" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" // ensure test packages are scanned by ginkgo @@ -24,8 +25,6 @@ import ( "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/upgrade" - - ginkgo "github.com/onsi/ginkgo/v2" ) func TestE2E(t *testing.T) { diff --git a/tests/e2e/etna/suites.go b/tests/e2e/etna/suites.go index f78d561f9b92..60ecd0ff6252 100644 --- a/tests/e2e/etna/suites.go +++ b/tests/e2e/etna/suites.go @@ -7,12 +7,11 @@ package etna import ( "time" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/api/info" "github.com/ava-labs/avalanchego/tests/fixture/e2e" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = ginkgo.Describe("[Etna]", func() { diff --git a/tests/e2e/faultinjection/duplicate_node_id.go b/tests/e2e/faultinjection/duplicate_node_id.go index 5032a0e306bb..d0a72d5b0574 100644 --- a/tests/e2e/faultinjection/duplicate_node_id.go +++ b/tests/e2e/faultinjection/duplicate_node_id.go @@ -7,6 +7,7 @@ import ( "context" "fmt" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/api/info" @@ -16,8 +17,6 @@ import ( "github.com/ava-labs/avalanchego/tests/fixture/e2e" "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/set" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = ginkgo.Describe("Duplicate node handling", func() { diff --git a/tests/e2e/p/elastic_subnets.go b/tests/e2e/p/elastic_subnets.go index 100ff81780ce..6fdd8966c302 100644 --- a/tests/e2e/p/elastic_subnets.go +++ b/tests/e2e/p/elastic_subnets.go @@ -7,6 +7,7 @@ import ( "fmt" "time" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/api/info" @@ -21,8 +22,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/signer" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = e2e.DescribePChain("[Elastic Subnets]", func() { diff --git a/tests/e2e/p/interchain_workflow.go b/tests/e2e/p/interchain_workflow.go index e612658bb8fe..a190a5a75131 100644 --- a/tests/e2e/p/interchain_workflow.go +++ b/tests/e2e/p/interchain_workflow.go @@ -8,6 +8,7 @@ import ( "time" "github.com/ava-labs/coreth/plugin/evm" + "github.com/onsi/ginkgo/v2" "github.com/spf13/cast" "github.com/stretchr/testify/require" @@ -24,8 +25,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = e2e.DescribePChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainLabel), func() { diff --git a/tests/e2e/p/owner_retrieval.go b/tests/e2e/p/owner_retrieval.go index 2e0b08ac2c46..a92c256a2c93 100644 --- a/tests/e2e/p/owner_retrieval.go +++ b/tests/e2e/p/owner_retrieval.go @@ -4,6 +4,7 @@ package p import ( + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" @@ -11,8 +12,6 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/vms/platformvm" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = e2e.DescribePChain("[P-Chain Wallet]", func() { diff --git a/tests/e2e/p/permissionless_layer_one.go b/tests/e2e/p/permissionless_layer_one.go index 0420be83d0da..844b3a257341 100644 --- a/tests/e2e/p/permissionless_layer_one.go +++ b/tests/e2e/p/permissionless_layer_one.go @@ -6,6 +6,7 @@ package p import ( "time" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/api/info" @@ -14,8 +15,6 @@ import ( "github.com/ava-labs/avalanchego/utils/constants" "github.com/ava-labs/avalanchego/vms/platformvm" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = e2e.DescribePChain("[Permissionless L1]", func() { diff --git a/tests/e2e/p/staking_rewards.go b/tests/e2e/p/staking_rewards.go index 3f6023780f22..84156a9b74d4 100644 --- a/tests/e2e/p/staking_rewards.go +++ b/tests/e2e/p/staking_rewards.go @@ -7,6 +7,7 @@ import ( "time" "github.com/mitchellh/mapstructure" + "github.com/onsi/ginkgo/v2" "github.com/spf13/cast" "github.com/stretchr/testify/require" @@ -24,8 +25,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/reward" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = ginkgo.Describe("[Staking Rewards]", func() { diff --git a/tests/e2e/p/validator_sets.go b/tests/e2e/p/validator_sets.go index 81c6ab8178a9..78c8e4ac4bb4 100644 --- a/tests/e2e/p/validator_sets.go +++ b/tests/e2e/p/validator_sets.go @@ -7,6 +7,7 @@ import ( "fmt" "time" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/genesis" @@ -17,8 +18,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm" "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = e2e.DescribePChain("[Validator Sets]", func() { diff --git a/tests/e2e/p/workflow.go b/tests/e2e/p/workflow.go index 34e4145608d7..c3d654393ffb 100644 --- a/tests/e2e/p/workflow.go +++ b/tests/e2e/p/workflow.go @@ -6,6 +6,7 @@ package p import ( "time" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" @@ -20,8 +21,6 @@ import ( "github.com/ava-labs/avalanchego/vms/platformvm/txs" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - ginkgo "github.com/onsi/ginkgo/v2" ) // PChainWorkflow is an integration test for normal P-Chain operations diff --git a/tests/e2e/vms/xsvm.go b/tests/e2e/vms/xsvm.go index 22add7550b5d..bb0e3d81809e 100644 --- a/tests/e2e/vms/xsvm.go +++ b/tests/e2e/vms/xsvm.go @@ -7,6 +7,7 @@ import ( "fmt" "time" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" @@ -19,8 +20,6 @@ import ( "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/issue/export" "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/issue/importtx" "github.com/ava-labs/avalanchego/vms/example/xsvm/cmd/issue/transfer" - - ginkgo "github.com/onsi/ginkgo/v2" ) const pollingInterval = 50 * time.Millisecond diff --git a/tests/e2e/x/interchain_workflow.go b/tests/e2e/x/interchain_workflow.go index e1d5e5dbb8e5..33f26cbc9bb4 100644 --- a/tests/e2e/x/interchain_workflow.go +++ b/tests/e2e/x/interchain_workflow.go @@ -7,6 +7,7 @@ import ( "math/big" "github.com/ava-labs/coreth/plugin/evm" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/ids" @@ -17,8 +18,6 @@ import ( "github.com/ava-labs/avalanchego/vms/components/avax" "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - ginkgo "github.com/onsi/ginkgo/v2" ) var _ = e2e.DescribeXChain("[Interchain Workflow]", ginkgo.Label(e2e.UsesCChainLabel), func() { diff --git a/tests/e2e/x/transfer/virtuous.go b/tests/e2e/x/transfer/virtuous.go index 5c59b599ba40..20b7896a14be 100644 --- a/tests/e2e/x/transfer/virtuous.go +++ b/tests/e2e/x/transfer/virtuous.go @@ -9,6 +9,7 @@ import ( "math/rand" "time" + "github.com/onsi/ginkgo/v2" "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" @@ -25,8 +26,6 @@ import ( "github.com/ava-labs/avalanchego/vms/secp256k1fx" "github.com/ava-labs/avalanchego/wallet/subnet/primary" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - ginkgo "github.com/onsi/ginkgo/v2" ) const ( diff --git a/tests/fixture/e2e/describe.go b/tests/fixture/e2e/describe.go index 2810117758c6..1c97ccf35c01 100644 --- a/tests/fixture/e2e/describe.go +++ b/tests/fixture/e2e/describe.go @@ -3,9 +3,7 @@ package e2e -import ( - ginkgo "github.com/onsi/ginkgo/v2" -) +import "github.com/onsi/ginkgo/v2" const ( // For label usage in ginkgo invocation, see: https://onsi.github.io/ginkgo/#spec-labels diff --git a/tests/fixture/e2e/env.go b/tests/fixture/e2e/env.go index f39961dfb522..34748a9877d9 100644 --- a/tests/fixture/e2e/env.go +++ b/tests/fixture/e2e/env.go @@ -10,6 +10,7 @@ import ( "os" "time" + "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/api/info" @@ -18,8 +19,6 @@ import ( "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" "github.com/ava-labs/avalanchego/utils/crypto/secp256k1" "github.com/ava-labs/avalanchego/vms/secp256k1fx" - - ginkgo "github.com/onsi/ginkgo/v2" ) // Env is used to access shared test fixture. Intended to be diff --git a/tests/fixture/e2e/ginkgo_test_context.go b/tests/fixture/e2e/ginkgo_test_context.go index 39592ae30ce9..912c144db3e1 100644 --- a/tests/fixture/e2e/ginkgo_test_context.go +++ b/tests/fixture/e2e/ginkgo_test_context.go @@ -8,13 +8,12 @@ import ( "io" "time" + "github.com/onsi/ginkgo/v2" "github.com/onsi/ginkgo/v2/formatter" "github.com/stretchr/testify/require" "github.com/ava-labs/avalanchego/tests" "github.com/ava-labs/avalanchego/wallet/subnet/primary/common" - - ginkgo "github.com/onsi/ginkgo/v2" ) type GinkgoTestContext struct{} diff --git a/tests/fixture/e2e/metrics_link.go b/tests/fixture/e2e/metrics_link.go index 97ccd7e7d3d9..5f20e3ff88c4 100644 --- a/tests/fixture/e2e/metrics_link.go +++ b/tests/fixture/e2e/metrics_link.go @@ -7,9 +7,9 @@ import ( "strconv" "time" - "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" + "github.com/onsi/ginkgo/v2" - ginkgo "github.com/onsi/ginkgo/v2" + "github.com/ava-labs/avalanchego/tests/fixture/tmpnet" ) // The ginkgo event handlers defined in this file will be automatically @@ -36,6 +36,9 @@ var _ = ginkgo.BeforeEach(func() { var _ = ginkgo.AfterEach(func() { tc := NewTestContext() env := GetEnv(tc) + // The global env isn't guaranteed to be initialized by importers + // of this package since initializing a package-local env is also + // supported. if env == nil || !EmitMetricsLink { return } From 6e1a9055d111b7a693d2239d95706cbf9af0a2da Mon Sep 17 00:00:00 2001 From: yacovm Date: Fri, 6 Sep 2024 16:50:33 +0200 Subject: [PATCH 67/69] Abort query if not enough stake is connected (#3345) Signed-off-by: Yacov Manevich --- snow/engine/snowman/engine.go | 24 +++++++++++++++++- snow/engine/snowman/engine_test.go | 39 ++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/snow/engine/snowman/engine.go b/snow/engine/snowman/engine.go index 1b2cfb5c11d4..821ce41096d5 100644 --- a/snow/engine/snowman/engine.go +++ b/snow/engine/snowman/engine.go @@ -31,7 +31,10 @@ import ( "github.com/ava-labs/avalanchego/utils/units" ) -const nonVerifiedCacheSize = 64 * units.MiB +const ( + nonVerifiedCacheSize = 64 * units.MiB + errInsufficientStake = "insufficient connected stake" +) var _ common.Engine = (*Engine)(nil) @@ -871,6 +874,10 @@ func (e *Engine) sendQuery( blkBytes []byte, push bool, ) { + if e.abortDueToInsufficientConnectedStake(blkID) { + return + } + e.Ctx.Log.Verbo("sampling from validators", zap.Stringer("validators", e.Validators), ) @@ -916,6 +923,21 @@ func (e *Engine) sendQuery( } } +func (e *Engine) abortDueToInsufficientConnectedStake(blkID ids.ID) bool { + stakeConnectedRatio := e.Config.ConnectedValidators.ConnectedPercent() + minConnectedStakeToQuery := float64(e.Params.AlphaConfidence) / float64(e.Params.K) + + if stakeConnectedRatio < minConnectedStakeToQuery { + e.Ctx.Log.Debug("dropped query for block", + zap.String("reason", errInsufficientStake), + zap.Stringer("blkID", blkID), + zap.Float64("ratio", stakeConnectedRatio), + ) + return true + } + return false +} + // issue [blk] to consensus // If [push] is true, a push query will be used. Otherwise, a pull query will be // used. diff --git a/snow/engine/snowman/engine_test.go b/snow/engine/snowman/engine_test.go index 26eccf232ed1..c7fa4f45bbe9 100644 --- a/snow/engine/snowman/engine_test.go +++ b/snow/engine/snowman/engine_test.go @@ -22,6 +22,7 @@ import ( "github.com/ava-labs/avalanchego/snow/consensus/snowman" "github.com/ava-labs/avalanchego/snow/consensus/snowman/snowmantest" "github.com/ava-labs/avalanchego/snow/engine/common" + "github.com/ava-labs/avalanchego/snow/engine/common/tracker" "github.com/ava-labs/avalanchego/snow/engine/enginetest" "github.com/ava-labs/avalanchego/snow/engine/snowman/ancestor" "github.com/ava-labs/avalanchego/snow/engine/snowman/block/blocktest" @@ -29,6 +30,7 @@ import ( "github.com/ava-labs/avalanchego/snow/snowtest" "github.com/ava-labs/avalanchego/snow/validators" "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/version" ) @@ -3182,3 +3184,40 @@ func TestShouldIssueBlock(t *testing.T) { }) } } + +type mockConnVDR struct { + tracker.Peers + percent float64 +} + +func (m *mockConnVDR) ConnectedPercent() float64 { + return m.percent +} + +type logBuffer struct { + bytes.Buffer +} + +func (logBuffer) Close() error { + return nil +} + +func TestEngineAbortQueryWhenInPartition(t *testing.T) { + require := require.New(t) + + // Buffer to record the log entries + buff := logBuffer{} + + conf := DefaultConfig(t) + // Overwrite the log to record what it says + conf.Ctx.Log = logging.NewLogger("", logging.NewWrappedCore(logging.Verbo, &buff, logging.Plain.ConsoleEncoder())) + conf.Params = snowball.DefaultParameters + conf.ConnectedValidators = &mockConnVDR{percent: 0.7, Peers: conf.ConnectedValidators} + + _, _, _, _, engine := setup(t, conf) + + // Gossip will cause a pull query if enough stake is connected + engine.sendQuery(context.Background(), ids.ID{}, nil, false) + + require.Contains(buff.String(), errInsufficientStake) +} From cba7a50cc4c4e77088d5e18eab3f0090dfd94cfd Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Sun, 8 Sep 2024 16:33:16 +0300 Subject: [PATCH 68/69] remove unused err --- network/network.go | 1 - 1 file changed, 1 deletion(-) diff --git a/network/network.go b/network/network.go index 63f8c1f035b3..eab4ecca085e 100644 --- a/network/network.go +++ b/network/network.go @@ -52,7 +52,6 @@ var ( _ Network = (*network)(nil) errNotValidator = errors.New("node is not a validator") - errNotTracked = errors.New("subnet is not tracked") errExpectedProxy = errors.New("expected proxy") errExpectedTCPProtocol = errors.New("expected TCP protocol") errTrackingPrimaryNetwork = errors.New("cannot track primary network") From b4955d6f492929a85bdf3e40a45396a62aeecd99 Mon Sep 17 00:00:00 2001 From: Ceyhun Onur Date: Sun, 8 Sep 2024 16:36:53 +0300 Subject: [PATCH 69/69] remove subnet connector mock --- .../validatorsmock/subnet_connector.go | 55 ------------------- 1 file changed, 55 deletions(-) delete mode 100644 snow/validators/validatorsmock/subnet_connector.go diff --git a/snow/validators/validatorsmock/subnet_connector.go b/snow/validators/validatorsmock/subnet_connector.go deleted file mode 100644 index 118a287ac68a..000000000000 --- a/snow/validators/validatorsmock/subnet_connector.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by MockGen. DO NOT EDIT. -// Source: github.com/ava-labs/avalanchego/snow/validators (interfaces: SubnetConnector) -// -// Generated by this command: -// -// mockgen -package=validatorsmock -destination=snow/validators/validatorsmock/subnet_connector.go -mock_names=SubnetConnector=SubnetConnector github.com/ava-labs/avalanchego/snow/validators SubnetConnector -// - -// Package validatorsmock is a generated GoMock package. -package validatorsmock - -import ( - context "context" - reflect "reflect" - - ids "github.com/ava-labs/avalanchego/ids" - gomock "go.uber.org/mock/gomock" -) - -// SubnetConnector is a mock of SubnetConnector interface. -type SubnetConnector struct { - ctrl *gomock.Controller - recorder *SubnetConnectorMockRecorder -} - -// SubnetConnectorMockRecorder is the mock recorder for SubnetConnector. -type SubnetConnectorMockRecorder struct { - mock *SubnetConnector -} - -// NewSubnetConnector creates a new mock instance. -func NewSubnetConnector(ctrl *gomock.Controller) *SubnetConnector { - mock := &SubnetConnector{ctrl: ctrl} - mock.recorder = &SubnetConnectorMockRecorder{mock} - return mock -} - -// EXPECT returns an object that allows the caller to indicate expected use. -func (m *SubnetConnector) EXPECT() *SubnetConnectorMockRecorder { - return m.recorder -} - -// ConnectedSubnet mocks base method. -func (m *SubnetConnector) ConnectedSubnet(arg0 context.Context, arg1 ids.NodeID, arg2 ids.ID) error { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ConnectedSubnet", arg0, arg1, arg2) - ret0, _ := ret[0].(error) - return ret0 -} - -// ConnectedSubnet indicates an expected call of ConnectedSubnet. -func (mr *SubnetConnectorMockRecorder) ConnectedSubnet(arg0, arg1, arg2 any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConnectedSubnet", reflect.TypeOf((*SubnetConnector)(nil).ConnectedSubnet), arg0, arg1, arg2) -}