From 0682e3eb780556e436f6bb999e1d9f66d1e415a1 Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 20 Mar 2024 09:43:12 +0000 Subject: [PATCH 01/23] use mock client in docker framework --- pkg/testsuite/blocks.go | 6 +- pkg/testsuite/mock/client.go | 1 - pkg/testsuite/mock/wallet.go | 26 ++--- pkg/testsuite/storage_settings.go | 6 +- .../tests/committeerotation_test.go | 6 +- tools/docker-network/tests/coreapi.go | 2 +- tools/docker-network/tests/coreapi_test.go | 100 +++++++++--------- tools/docker-network/tests/dockerframework.go | 69 ++++++++---- .../docker-network/tests/eventapiframework.go | 4 +- .../tests/mempool_invalid_signatures_test.go | 6 +- tools/docker-network/tests/utils.go | 30 +++--- tools/docker-network/tests/wallet.go | 43 ++++---- 12 files changed, 158 insertions(+), 141 deletions(-) diff --git a/pkg/testsuite/blocks.go b/pkg/testsuite/blocks.go index 591a2d214..ec0afd080 100644 --- a/pkg/testsuite/blocks.go +++ b/pkg/testsuite/blocks.go @@ -17,11 +17,11 @@ func (t *TestSuite) AssertBlock(block *blocks.Block, client mock.Client) *iotago var err error loadedBlock, err = client.BlockByBlockID(context.Background(), block.ID()) if err != nil { - return ierrors.Wrapf(err, "AssertBlock: %s: block %s does not exist", client.Name(), block.ID()) + return ierrors.Wrapf(err, "AssertBlock: block %s does not exist", block.ID()) } if block.ID() != loadedBlock.MustID() { - return ierrors.Errorf("AssertBlock: %s: expected %s, got %s", client.Name(), block.ID(), loadedBlock.MustID()) + return ierrors.Errorf("AssertBlock: expected %s, got %s", block.ID(), loadedBlock.MustID()) } return nil @@ -43,7 +43,7 @@ func (t *TestSuite) AssertBlocksExist(blocks []*blocks.Block, expectedExist bool t.Eventually(func() error { _, err := client.BlockByBlockID(context.Background(), block.ID()) if err == nil { - return ierrors.Errorf("AssertBlocksExist: %s: block %s exists but should not", client.Name(), block) + return ierrors.Errorf("AssertBlocksExist: block %s exists but should not", block) } return nil diff --git a/pkg/testsuite/mock/client.go b/pkg/testsuite/mock/client.go index 96416ad41..b0df8c697 100644 --- a/pkg/testsuite/mock/client.go +++ b/pkg/testsuite/mock/client.go @@ -39,7 +39,6 @@ type Client interface { Info(ctx context.Context) (*api.InfoResponse, error) LatestAPI() iotago.API Management(ctx context.Context) (nodeclient.ManagementClient, error) - Name() string NetworkMetrics(ctx context.Context) (*api.NetworkMetricsResponse, error) NodeSupportsRoute(ctx context.Context, route string) (bool, error) OutputByID(ctx context.Context, outputID iotago.OutputID) (iotago.Output, error) diff --git a/pkg/testsuite/mock/wallet.go b/pkg/testsuite/mock/wallet.go index d50bea56b..d381fb420 100644 --- a/pkg/testsuite/mock/wallet.go +++ b/pkg/testsuite/mock/wallet.go @@ -76,8 +76,7 @@ type Wallet struct { keyManager *wallet.KeyManager - BlockIssuer *BlockIssuer - IssuerAccount *AccountData + BlockIssuer *BlockIssuer outputs map[string]*OutputData transactions map[string]*iotago.Transaction @@ -91,21 +90,18 @@ func NewWallet(t *testing.T, name string, client Client, keyManager ...*wallet.K } else { km = keyManager[0] } - issuerAccountData := &AccountData{ - ID: iotago.EmptyAccountID, - AddressIndex: 0, - } + blockIssuerAddressIndex := uint32(0) + blockIssuerID := iotago.EmptyAccountID return &Wallet{ - Testing: t, - Name: name, - Client: client, - outputs: make(map[string]*OutputData), - transactions: make(map[string]*iotago.Transaction), - keyManager: km, - IssuerAccount: issuerAccountData, - BlockIssuer: NewBlockIssuer(t, name, km, client, issuerAccountData.AddressIndex, issuerAccountData.ID, false), - clock: &TestSuiteWalletClock{}, + Testing: t, + Name: name, + Client: client, + outputs: make(map[string]*OutputData), + transactions: make(map[string]*iotago.Transaction), + keyManager: km, + BlockIssuer: NewBlockIssuer(t, name, km, client, blockIssuerAddressIndex, blockIssuerID, false), + clock: &TestSuiteWalletClock{}, } } diff --git a/pkg/testsuite/storage_settings.go b/pkg/testsuite/storage_settings.go index af5b58969..306817a92 100644 --- a/pkg/testsuite/storage_settings.go +++ b/pkg/testsuite/storage_settings.go @@ -58,16 +58,16 @@ func (t *TestSuite) AssertCommitmentSlotIndexExists(slot iotago.SlotIndex, clien latestCommitment, err := client.CommitmentByID(context.Background(), iotago.EmptyCommitmentID) require.NoError(t.Testing, err) if latestCommitment.Slot < slot { - return ierrors.Errorf("AssertCommitmentSlotIndexExists: %s: commitment with at least %v not found in settings.LatestCommitment()", client.Name(), slot) + return ierrors.Errorf("AssertCommitmentSlotIndexExists: commitment with at least %v not found in settings.LatestCommitment()", slot) } cm, err := client.CommitmentBySlot(context.Background(), slot) if err != nil { - return ierrors.Errorf("AssertCommitmentSlotIndexExists: %s: expected %v, got error %v", client.Name(), slot, err) + return ierrors.Errorf("AssertCommitmentSlotIndexExists: expected %v, got error %v", slot, err) } if cm == nil { - return ierrors.Errorf("AssertCommitmentSlotIndexExists: %s: commitment at index %v not found", client.Name(), slot) + return ierrors.Errorf("AssertCommitmentSlotIndexExists: commitment at index %v not found", slot) } return nil diff --git a/tools/docker-network/tests/committeerotation_test.go b/tools/docker-network/tests/committeerotation_test.go index 80d560486..cd3f40951 100644 --- a/tools/docker-network/tests/committeerotation_test.go +++ b/tools/docker-network/tests/committeerotation_test.go @@ -43,7 +43,7 @@ func Test_SmallerCommittee(t *testing.T) { status := d.NodeStatus("V1") - clt := d.wallet.DefaultClient() + clt := d.wallet.Client currentEpoch := clt.CommittedAPI().TimeProvider().EpochFromSlot(status.LatestAcceptedBlockSlot) // stop inx-validator plugin of validator 2 @@ -90,7 +90,7 @@ func Test_ReuseDueToNoFinalization(t *testing.T) { err = d.StopContainer(d.Node("V2").ContainerName, d.Node("V3").ContainerName) require.NoError(t, err) - clt := d.wallet.DefaultClient() + clt := d.wallet.Client status := d.NodeStatus("V1") prevFinalizedSlot := status.LatestFinalizedSlot @@ -155,7 +155,7 @@ func Test_NoCandidacyPayload(t *testing.T) { d.WaitUntilNetworkReady() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client status := d.NodeStatus("V1") prevFinalizedSlot := status.LatestFinalizedSlot fmt.Println("First finalized slot: ", prevFinalizedSlot) diff --git a/tools/docker-network/tests/coreapi.go b/tools/docker-network/tests/coreapi.go index bafa2d80e..0ad614c9b 100644 --- a/tools/docker-network/tests/coreapi.go +++ b/tools/docker-network/tests/coreapi.go @@ -226,7 +226,7 @@ func (d *DockerTestFramework) prepareAssets(totalAssetsNum int) (coreAPIAssets, d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) // issue reattachment after the fisrt one is already included - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, d.wallet.DefaultClient(), account.Address) + issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, d.wallet.Client, account.Address) secondAttachment := d.SubmitPayload(ctx, signedTx, account.Address.AccountID(), congestionResp, issuerResp) assets[valueBlockSlot].reattachments = append(assets[valueBlockSlot].reattachments, secondAttachment) diff --git a/tools/docker-network/tests/coreapi_test.go b/tools/docker-network/tests/coreapi_test.go index cb086c930..646c7b7c1 100644 --- a/tools/docker-network/tests/coreapi_test.go +++ b/tools/docker-network/tests/coreapi_test.go @@ -13,9 +13,9 @@ import ( "github.com/stretchr/testify/require" "github.com/iotaledger/hive.go/lo" + "github.com/iotaledger/iota-core/pkg/testsuite/mock" iotago "github.com/iotaledger/iota.go/v4" "github.com/iotaledger/iota.go/v4/api" - "github.com/iotaledger/iota.go/v4/nodeclient" "github.com/iotaledger/iota.go/v4/tpkg" ) @@ -45,11 +45,11 @@ func Test_ValidatorsAPI(t *testing.T) { require.NoError(t, runErr) d.WaitUntilNetworkReady() - hrp := d.wallet.DefaultClient().CommittedAPI().ProtocolParameters().Bech32HRP() + hrp := d.wallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP() // Create registered validators var wg sync.WaitGroup - clt := d.wallet.DefaultClient() + clt := d.wallet.Client status := d.NodeStatus("V1") currentEpoch := clt.CommittedAPI().TimeProvider().EpochFromSlot(status.LatestAcceptedBlockSlot) @@ -117,7 +117,7 @@ func Test_CoreAPI(t *testing.T) { { name: "Test_Info", testFunc: func(t *testing.T, nodeAlias string) { - resp, err := d.wallet.Clients[nodeAlias].Info(context.Background()) + resp, err := d.Client(nodeAlias).Info(context.Background()) require.NoError(t, err) require.NotNil(t, resp) }, @@ -126,7 +126,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_BlockByBlockID", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachBlock(t, func(t *testing.T, block *iotago.Block) { - respBlock, err := d.wallet.Clients[nodeAlias].BlockByBlockID(context.Background(), block.MustID()) + respBlock, err := d.Client(nodeAlias).BlockByBlockID(context.Background(), block.MustID()) require.NoError(t, err) require.NotNil(t, respBlock) require.Equal(t, block.MustID(), respBlock.MustID(), "BlockID of retrieved block does not match: %s != %s", block.MustID(), respBlock.MustID()) @@ -137,7 +137,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_BlockMetadataByBlockID", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachBlock(t, func(t *testing.T, block *iotago.Block) { - resp, err := d.wallet.Clients[nodeAlias].BlockMetadataByBlockID(context.Background(), block.MustID()) + resp, err := d.Client(nodeAlias).BlockMetadataByBlockID(context.Background(), block.MustID()) require.NoError(t, err) require.NotNil(t, resp) require.Equal(t, block.MustID(), resp.BlockID, "BlockID of retrieved block does not match: %s != %s", block.MustID(), resp.BlockID) @@ -145,7 +145,7 @@ func Test_CoreAPI(t *testing.T) { }) assetsPerSlot.forEachReattachment(t, func(t *testing.T, blockID iotago.BlockID) { - resp, err := d.wallet.Clients[nodeAlias].BlockMetadataByBlockID(context.Background(), blockID) + resp, err := d.Client(nodeAlias).BlockMetadataByBlockID(context.Background(), blockID) require.NoError(t, err) require.NotNil(t, resp) require.Equal(t, blockID, resp.BlockID, "BlockID of retrieved block does not match: %s != %s", blockID, resp.BlockID) @@ -157,7 +157,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_BlockWithMetadata", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachBlock(t, func(t *testing.T, block *iotago.Block) { - resp, err := d.wallet.Clients[nodeAlias].BlockWithMetadataByBlockID(context.Background(), block.MustID()) + resp, err := d.Client(nodeAlias).BlockWithMetadataByBlockID(context.Background(), block.MustID()) require.NoError(t, err) require.NotNil(t, resp) require.Equal(t, block.MustID(), resp.Block.MustID(), "BlockID of retrieved block does not match: %s != %s", block.MustID(), resp.Block.MustID()) @@ -168,7 +168,7 @@ func Test_CoreAPI(t *testing.T) { { name: "Test_BlockIssuance", testFunc: func(t *testing.T, nodeAlias string) { - resp, err := d.wallet.Clients[nodeAlias].BlockIssuance(context.Background()) + resp, err := d.Client(nodeAlias).BlockIssuance(context.Background()) require.NoError(t, err) require.NotNil(t, resp) @@ -179,7 +179,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_CommitmentBySlot", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachSlot(t, func(t *testing.T, slot iotago.SlotIndex, commitmentsPerNode map[string]iotago.CommitmentID) { - resp, err := d.wallet.Clients[nodeAlias].CommitmentBySlot(context.Background(), slot) + resp, err := d.Client(nodeAlias).CommitmentBySlot(context.Background(), slot) require.NoError(t, err) require.NotNil(t, resp) commitmentsPerNode[nodeAlias] = resp.MustID() @@ -190,7 +190,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_CommitmentByID", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachCommitment(t, func(t *testing.T, commitmentsPerNode map[string]iotago.CommitmentID) { - resp, err := d.wallet.Clients[nodeAlias].CommitmentByID(context.Background(), commitmentsPerNode[nodeAlias]) + resp, err := d.Client(nodeAlias).CommitmentByID(context.Background(), commitmentsPerNode[nodeAlias]) require.NoError(t, err) require.NotNil(t, resp) require.Equal(t, commitmentsPerNode[nodeAlias], resp.MustID(), "Commitment does not match commitment got for the same slot from the same node: %s != %s", commitmentsPerNode[nodeAlias], resp.MustID()) @@ -201,7 +201,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_CommitmentUTXOChangesByID", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachCommitment(t, func(t *testing.T, commitmentsPerNode map[string]iotago.CommitmentID) { - resp, err := d.wallet.Clients[nodeAlias].CommitmentUTXOChangesByID(context.Background(), commitmentsPerNode[nodeAlias]) + resp, err := d.Client(nodeAlias).CommitmentUTXOChangesByID(context.Background(), commitmentsPerNode[nodeAlias]) require.NoError(t, err) require.NotNil(t, resp) assetsPerSlot.assertUTXOOutputIDsInSlot(t, commitmentsPerNode[nodeAlias].Slot(), resp.CreatedOutputs, resp.ConsumedOutputs) @@ -213,7 +213,7 @@ func Test_CoreAPI(t *testing.T) { "Test_CommitmentUTXOChangesFullByID", func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachCommitment(t, func(t *testing.T, commitmentsPerNode map[string]iotago.CommitmentID) { - resp, err := d.wallet.Clients[nodeAlias].CommitmentUTXOChangesFullByID(context.Background(), commitmentsPerNode[nodeAlias]) + resp, err := d.Client(nodeAlias).CommitmentUTXOChangesFullByID(context.Background(), commitmentsPerNode[nodeAlias]) require.NoError(t, err) require.NotNil(t, resp) assetsPerSlot.assertUTXOOutputsInSlot(t, commitmentsPerNode[nodeAlias].Slot(), resp.CreatedOutputs, resp.ConsumedOutputs) @@ -225,7 +225,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_CommitmentUTXOChangesBySlot", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachCommitment(t, func(t *testing.T, commitmentsPerNode map[string]iotago.CommitmentID) { - resp, err := d.wallet.Clients[nodeAlias].CommitmentUTXOChangesBySlot(context.Background(), commitmentsPerNode[nodeAlias].Slot()) + resp, err := d.Client(nodeAlias).CommitmentUTXOChangesBySlot(context.Background(), commitmentsPerNode[nodeAlias].Slot()) require.NoError(t, err) require.NotNil(t, resp) assetsPerSlot.assertUTXOOutputIDsInSlot(t, commitmentsPerNode[nodeAlias].Slot(), resp.CreatedOutputs, resp.ConsumedOutputs) @@ -237,7 +237,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_CommitmentUTXOChangesFullBySlot", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachCommitment(t, func(t *testing.T, commitmentsPerNode map[string]iotago.CommitmentID) { - resp, err := d.wallet.Clients[nodeAlias].CommitmentUTXOChangesFullBySlot(context.Background(), commitmentsPerNode[nodeAlias].Slot()) + resp, err := d.Client(nodeAlias).CommitmentUTXOChangesFullBySlot(context.Background(), commitmentsPerNode[nodeAlias].Slot()) require.NoError(t, err) require.NotNil(t, resp) assetsPerSlot.assertUTXOOutputsInSlot(t, commitmentsPerNode[nodeAlias].Slot(), resp.CreatedOutputs, resp.ConsumedOutputs) @@ -249,7 +249,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_OutputByID", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachOutput(t, func(t *testing.T, outputID iotago.OutputID, output iotago.Output) { - resp, err := d.wallet.Clients[nodeAlias].OutputByID(context.Background(), outputID) + resp, err := d.Client(nodeAlias).OutputByID(context.Background(), outputID) require.NoError(t, err) require.NotNil(t, resp) require.EqualValues(t, output, resp, "Output created is different than retrieved from the API: %s != %s", output, resp) @@ -260,7 +260,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_OutputMetadata", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachOutput(t, func(t *testing.T, outputID iotago.OutputID, output iotago.Output) { - resp, err := d.wallet.Clients[nodeAlias].OutputMetadataByID(context.Background(), outputID) + resp, err := d.Client(nodeAlias).OutputMetadataByID(context.Background(), outputID) require.NoError(t, err) require.NotNil(t, resp) require.EqualValues(t, outputID, resp.OutputID, "OutputID of retrieved output does not match: %s != %s", outputID, resp.OutputID) @@ -272,7 +272,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_OutputWithMetadata", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachOutput(t, func(t *testing.T, outputID iotago.OutputID, output iotago.Output) { - out, outMetadata, err := d.wallet.Clients[nodeAlias].OutputWithMetadataByID(context.Background(), outputID) + out, outMetadata, err := d.Client(nodeAlias).OutputWithMetadataByID(context.Background(), outputID) require.NoError(t, err) require.NotNil(t, outMetadata) require.NotNil(t, out) @@ -286,7 +286,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_TransactionsIncludedBlock", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachTransaction(t, func(t *testing.T, transaction *iotago.SignedTransaction, firstAttachmentID iotago.BlockID) { - resp, err := d.wallet.Clients[nodeAlias].TransactionIncludedBlock(context.Background(), lo.PanicOnErr(transaction.Transaction.ID())) + resp, err := d.Client(nodeAlias).TransactionIncludedBlock(context.Background(), lo.PanicOnErr(transaction.Transaction.ID())) require.NoError(t, err) require.NotNil(t, resp) require.EqualValues(t, firstAttachmentID, resp.MustID()) @@ -297,7 +297,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_TransactionsIncludedBlockMetadata", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachTransaction(t, func(t *testing.T, transaction *iotago.SignedTransaction, firstAttachmentID iotago.BlockID) { - resp, err := d.wallet.Clients[nodeAlias].TransactionIncludedBlockMetadata(context.Background(), lo.PanicOnErr(transaction.Transaction.ID())) + resp, err := d.Client(nodeAlias).TransactionIncludedBlockMetadata(context.Background(), lo.PanicOnErr(transaction.Transaction.ID())) require.NoError(t, err) require.NotNil(t, resp) require.EqualValues(t, api.BlockStateFinalized, resp.BlockState) @@ -309,7 +309,7 @@ func Test_CoreAPI(t *testing.T) { name: "Test_TransactionsMetadata", testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachTransaction(t, func(t *testing.T, transaction *iotago.SignedTransaction, firstAttachmentID iotago.BlockID) { - resp, err := d.wallet.Clients[nodeAlias].TransactionMetadata(context.Background(), lo.PanicOnErr(transaction.Transaction.ID())) + resp, err := d.Client(nodeAlias).TransactionMetadata(context.Background(), lo.PanicOnErr(transaction.Transaction.ID())) require.NoError(t, err) require.NotNil(t, resp) require.Equal(t, api.TransactionStateFinalized, resp.TransactionState) @@ -326,17 +326,17 @@ func Test_CoreAPI(t *testing.T) { commitmentPerNode map[string]iotago.CommitmentID, bicPerNoode map[string]iotago.BlockIssuanceCredits, ) { - resp, err := d.wallet.Clients[nodeAlias].Congestion(context.Background(), accountAddress, 0) + resp, err := d.Client(nodeAlias).Congestion(context.Background(), accountAddress, 0) require.NoError(t, err) require.NotNil(t, resp) // node allows to get account only for the slot newer than lastCommittedSlot - MCA, we need fresh commitment - infoRes, err := d.wallet.Clients[nodeAlias].Info(context.Background()) + infoRes, err := d.Client(nodeAlias).Info(context.Background()) require.NoError(t, err) - commitment, err := d.wallet.Clients[nodeAlias].CommitmentBySlot(context.Background(), infoRes.Status.LatestCommitmentID.Slot()) + commitment, err := d.Client(nodeAlias).CommitmentBySlot(context.Background(), infoRes.Status.LatestCommitmentID.Slot()) require.NoError(t, err) - resp, err = d.wallet.Clients[nodeAlias].Congestion(context.Background(), accountAddress, 0, commitment.MustID()) + resp, err = d.Client(nodeAlias).Congestion(context.Background(), accountAddress, 0, commitment.MustID()) require.NoError(t, err) require.NotNil(t, resp) // later we check if all nodes have returned the same BIC value for this account @@ -348,13 +348,13 @@ func Test_CoreAPI(t *testing.T) { name: "Test_Validators", testFunc: func(t *testing.T, nodeAlias string) { pageSize := uint64(3) - resp, err := d.wallet.Clients[nodeAlias].Validators(context.Background(), pageSize) + resp, err := d.Client(nodeAlias).Validators(context.Background(), pageSize) require.NoError(t, err) require.NotNil(t, resp) //TODO after finishing validators endpoint and including registered validators //require.Equal(t, int(pageSize), len(resp.Validators), "There should be exactly %d validators returned on the first page", pageSize) - resp, err = d.wallet.Clients[nodeAlias].Validators(context.Background(), pageSize, resp.Cursor) + resp, err = d.Client(nodeAlias).Validators(context.Background(), pageSize, resp.Cursor) require.NoError(t, err) require.NotNil(t, resp) //TODO after finishing validators endpoint and including registered validators @@ -364,7 +364,7 @@ func Test_CoreAPI(t *testing.T) { { name: "Test_ValidatorsAll", testFunc: func(t *testing.T, nodeAlias string) { - resp, all, err := d.wallet.Clients[nodeAlias].ValidatorsAll(context.Background()) + resp, all, err := d.Client(nodeAlias).ValidatorsAll(context.Background()) require.NoError(t, err) require.True(t, all) require.Equal(t, 4, len(resp.Validators)) @@ -378,7 +378,7 @@ func Test_CoreAPI(t *testing.T) { return } - resp, err := d.wallet.Clients[nodeAlias].Rewards(context.Background(), outputID) + resp, err := d.Client(nodeAlias).Rewards(context.Background(), outputID) require.NoError(t, err) require.NotNil(t, resp) // rewards are zero, because we do not wait for the epoch end @@ -389,7 +389,7 @@ func Test_CoreAPI(t *testing.T) { { name: "Test_Committee", testFunc: func(t *testing.T, nodeAlias string) { - resp, err := d.wallet.Clients[nodeAlias].Committee(context.Background()) + resp, err := d.Client(nodeAlias).Committee(context.Background()) require.NoError(t, err) require.NotNil(t, resp) require.EqualValues(t, 4, len(resp.Committee)) @@ -398,7 +398,7 @@ func Test_CoreAPI(t *testing.T) { { name: "Test_CommitteeWithEpoch", testFunc: func(t *testing.T, nodeAlias string) { - resp, err := d.wallet.Clients[nodeAlias].Committee(context.Background(), 0) + resp, err := d.Client(nodeAlias).Committee(context.Background(), 0) require.NoError(t, err) require.Equal(t, iotago.EpochIndex(0), resp.Epoch) require.Equal(t, 4, len(resp.Committee)) @@ -446,7 +446,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_BlockByBlockID_Failure", testFunc: func(t *testing.T, nodeAlias string) { blockID := tpkg.RandBlockID() - respBlock, err := d.wallet.Clients[nodeAlias].BlockByBlockID(context.Background(), blockID) + respBlock, err := d.Client(nodeAlias).BlockByBlockID(context.Background(), blockID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusNotFound)) require.Nil(t, respBlock) @@ -456,7 +456,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_BlockMetadataByBlockID_Failure", testFunc: func(t *testing.T, nodeAlias string) { blockID := tpkg.RandBlockID() - resp, err := d.wallet.Clients[nodeAlias].BlockMetadataByBlockID(context.Background(), blockID) + resp, err := d.Client(nodeAlias).BlockMetadataByBlockID(context.Background(), blockID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusNotFound)) require.Nil(t, resp) @@ -466,7 +466,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_BlockWithMetadata_Failure", testFunc: func(t *testing.T, nodeAlias string) { blockID := tpkg.RandBlockID() - resp, err := d.wallet.Clients[nodeAlias].BlockWithMetadataByBlockID(context.Background(), blockID) + resp, err := d.Client(nodeAlias).BlockWithMetadataByBlockID(context.Background(), blockID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusNotFound)) require.Nil(t, resp) @@ -476,7 +476,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_CommitmentBySlot_Failure", testFunc: func(t *testing.T, nodeAlias string) { slot := iotago.SlotIndex(1000_000_000) - resp, err := d.wallet.Clients[nodeAlias].CommitmentBySlot(context.Background(), slot) + resp, err := d.Client(nodeAlias).CommitmentBySlot(context.Background(), slot) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusBadRequest)) require.Nil(t, resp) @@ -486,7 +486,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_CommitmentByID_Failure", testFunc: func(t *testing.T, nodeAlias string) { committmentID := tpkg.RandCommitmentID() - resp, err := d.wallet.Clients[nodeAlias].CommitmentByID(context.Background(), committmentID) + resp, err := d.Client(nodeAlias).CommitmentByID(context.Background(), committmentID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusBadRequest)) require.Nil(t, resp) @@ -496,7 +496,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_CommitmentUTXOChangesByID_Failure", testFunc: func(t *testing.T, nodeAlias string) { committmentID := tpkg.RandCommitmentID() - resp, err := d.wallet.Clients[nodeAlias].CommitmentUTXOChangesByID(context.Background(), committmentID) + resp, err := d.Client(nodeAlias).CommitmentUTXOChangesByID(context.Background(), committmentID) require.Error(t, err) // commitmentID is valid, but the UTXO changes does not exist in the storage require.True(t, isStatusCode(err, http.StatusNotFound)) @@ -508,7 +508,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { func(t *testing.T, nodeAlias string) { committmentID := tpkg.RandCommitmentID() - resp, err := d.wallet.Clients[nodeAlias].CommitmentUTXOChangesFullByID(context.Background(), committmentID) + resp, err := d.Client(nodeAlias).CommitmentUTXOChangesFullByID(context.Background(), committmentID) require.Error(t, err) // commitmentID is valid, but the UTXO changes does not exist in the storage require.True(t, isStatusCode(err, http.StatusNotFound)) @@ -519,7 +519,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_CommitmentUTXOChangesBySlot_Failure", testFunc: func(t *testing.T, nodeAlias string) { slot := iotago.SlotIndex(1000_000_000) - resp, err := d.wallet.Clients[nodeAlias].CommitmentUTXOChangesBySlot(context.Background(), slot) + resp, err := d.Client(nodeAlias).CommitmentUTXOChangesBySlot(context.Background(), slot) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusBadRequest)) require.Nil(t, resp) @@ -530,7 +530,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { testFunc: func(t *testing.T, nodeAlias string) { slot := iotago.SlotIndex(1000_000_000) - resp, err := d.wallet.Clients[nodeAlias].CommitmentUTXOChangesFullBySlot(context.Background(), slot) + resp, err := d.Client(nodeAlias).CommitmentUTXOChangesFullBySlot(context.Background(), slot) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusBadRequest)) require.Nil(t, resp) @@ -540,7 +540,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_OutputByID_Failure", testFunc: func(t *testing.T, nodeAlias string) { outputID := tpkg.RandOutputID(0) - resp, err := d.wallet.Clients[nodeAlias].OutputByID(context.Background(), outputID) + resp, err := d.Client(nodeAlias).OutputByID(context.Background(), outputID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusNotFound)) require.Nil(t, resp) @@ -551,7 +551,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { testFunc: func(t *testing.T, nodeAlias string) { outputID := tpkg.RandOutputID(0) - resp, err := d.wallet.Clients[nodeAlias].OutputMetadataByID(context.Background(), outputID) + resp, err := d.Client(nodeAlias).OutputMetadataByID(context.Background(), outputID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusNotFound)) require.Nil(t, resp) @@ -562,7 +562,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { testFunc: func(t *testing.T, nodeAlias string) { outputID := tpkg.RandOutputID(0) - out, outMetadata, err := d.wallet.Clients[nodeAlias].OutputWithMetadataByID(context.Background(), outputID) + out, outMetadata, err := d.Client(nodeAlias).OutputWithMetadataByID(context.Background(), outputID) require.Error(t, err) require.Nil(t, out) require.Nil(t, outMetadata) @@ -573,7 +573,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_TransactionsIncludedBlock_Failure", testFunc: func(t *testing.T, nodeAlias string) { txID := tpkg.RandTransactionID() - resp, err := d.wallet.Clients[nodeAlias].TransactionIncludedBlock(context.Background(), txID) + resp, err := d.Client(nodeAlias).TransactionIncludedBlock(context.Background(), txID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusBadRequest)) require.Nil(t, resp) @@ -584,7 +584,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { testFunc: func(t *testing.T, nodeAlias string) { txID := tpkg.RandTransactionID() - resp, err := d.wallet.Clients[nodeAlias].TransactionIncludedBlockMetadata(context.Background(), txID) + resp, err := d.Client(nodeAlias).TransactionIncludedBlockMetadata(context.Background(), txID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusBadRequest)) require.Nil(t, resp) @@ -595,7 +595,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { testFunc: func(t *testing.T, nodeAlias string) { txID := tpkg.RandTransactionID() - resp, err := d.wallet.Clients[nodeAlias].TransactionMetadata(context.Background(), txID) + resp, err := d.Client(nodeAlias).TransactionMetadata(context.Background(), txID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusNotFound)) require.Nil(t, resp) @@ -606,7 +606,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { testFunc: func(t *testing.T, nodeAlias string) { accountAddress := tpkg.RandAccountAddress() commitmentID := tpkg.RandCommitmentID() - resp, err := d.wallet.Clients[nodeAlias].Congestion(context.Background(), accountAddress, 0, commitmentID) + resp, err := d.Client(nodeAlias).Congestion(context.Background(), accountAddress, 0, commitmentID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusBadRequest)) require.Nil(t, resp) @@ -615,7 +615,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { { name: "Test_Committee_Failure", testFunc: func(t *testing.T, nodeAlias string) { - resp, err := d.wallet.Clients[nodeAlias].Committee(context.Background(), 4) + resp, err := d.Client(nodeAlias).Committee(context.Background(), 4) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusBadRequest)) require.Nil(t, resp) @@ -625,7 +625,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { name: "Test_Rewards_Failure", testFunc: func(t *testing.T, nodeAlias string) { outputID := tpkg.RandOutputID(0) - resp, err := d.wallet.Clients[nodeAlias].Rewards(context.Background(), outputID) + resp, err := d.Client(nodeAlias).Rewards(context.Background(), outputID) require.Error(t, err) require.True(t, isStatusCode(err, http.StatusNotFound)) require.Nil(t, resp) @@ -640,7 +640,7 @@ func Test_CoreAPI_BadRequests(t *testing.T) { } } -func getAllValidatorsOnEpoch(t *testing.T, clt *nodeclient.Client, epoch iotago.EpochIndex, pageSize uint64) []string { +func getAllValidatorsOnEpoch(t *testing.T, clt mock.Client, epoch iotago.EpochIndex, pageSize uint64) []string { actualValidators := make([]string, 0) cursor := "" if epoch != 0 { diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 393d5b6f7..7e49c6f97 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -70,6 +70,7 @@ type DockerTestFramework struct { Testing *testing.T nodes map[string]*Node + clients map[string]mock.Client nodesLock syncutils.RWMutex snapshotPath string @@ -89,6 +90,7 @@ func NewDockerTestFramework(t *testing.T, opts ...options.Option[DockerTestFrame return options.Apply(&DockerTestFramework{ Testing: t, nodes: make(map[string]*Node), + clients: make(map[string]mock.Client), wallet: NewDockerWallet(t), optsWaitForSync: 5 * time.Minute, optsWaitFor: 2 * time.Minute, @@ -201,8 +203,8 @@ func (d *DockerTestFramework) waitForNodesAndGetClients() error { if err != nil { return ierrors.Wrapf(err, "failed to create node client for node %s", node.Name) } - d.wallet.Clients[node.Name] = client d.nodes[node.Name] = node + d.clients[node.Name] = client } return nil @@ -242,7 +244,7 @@ func (d *DockerTestFramework) WaitUntilSync() { d.Eventually(func() error { for _, node := range d.Nodes() { for { - synced, err := d.wallet.Clients[node.Name].Health(context.TODO()) + synced, err := d.Client(node.Name).Health(context.TODO()) if err != nil { return err } @@ -318,10 +320,39 @@ func (d *DockerTestFramework) Node(name string) *Node { return node } +func (d *DockerTestFramework) Clients(names ...string) map[string]mock.Client { + d.nodesLock.RLock() + defer d.nodesLock.RUnlock() + + if len(names) == 0 { + return d.clients + } + + clients := make(map[string]mock.Client, len(names)) + for _, name := range names { + client, exist := d.clients[name] + require.True(d.Testing, exist) + + clients[name] = client + } + + return clients +} + +func (d *DockerTestFramework) Client(name string) mock.Client { + d.nodesLock.RLock() + defer d.nodesLock.RUnlock() + + client, exist := d.clients[name] + require.True(d.Testing, exist) + + return client +} + func (d *DockerTestFramework) NodeStatus(name string) *api.InfoResNodeStatus { node := d.Node(name) - info, err := d.wallet.Clients[node.Name].Info(context.TODO()) + info, err := d.Client(node.Name).Info(context.TODO()) require.NoError(d.Testing, err) return info.Status @@ -367,7 +398,7 @@ func (d *DockerTestFramework) StopIssueCandidacyPayload(nodes ...*Node) { func (d *DockerTestFramework) IssueCandidacyPayloadFromAccount(issuerId iotago.AccountID) iotago.BlockID { issuer := d.wallet.Account(issuerId) ctx := context.TODO() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) @@ -378,7 +409,7 @@ func (d *DockerTestFramework) IssueCandidacyPayloadFromAccount(issuerId iotago.A func (d *DockerTestFramework) CreateTaggedDataBlock(issuerID iotago.AccountID, tag []byte) *iotago.Block { issuer := d.wallet.Account(issuerID) ctx := context.TODO() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) @@ -388,7 +419,7 @@ func (d *DockerTestFramework) CreateTaggedDataBlock(issuerID iotago.AccountID, t } func (d *DockerTestFramework) CreateBasicOutputBlock(issuerAccountID iotago.AccountID) (*iotago.Block, *iotago.SignedTransaction, *mock.OutputData) { - clt := d.wallet.DefaultClient() + clt := d.wallet.Client ctx := context.Background() fundsOutputID := d.RequestFaucetFunds(ctx, iotago.AddressEd25519) @@ -406,7 +437,7 @@ func (d *DockerTestFramework) CreateBasicOutputBlock(issuerAccountID iotago.Acco func (d *DockerTestFramework) CreateDelegationBlockFromInput(issuerID iotago.AccountID, accountAdddress *iotago.AccountAddress, inputID iotago.OutputID) (iotago.DelegationID, iotago.OutputID, *iotago.Block) { issuer := d.wallet.Account(issuerID) ctx := context.TODO() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) @@ -422,7 +453,7 @@ func (d *DockerTestFramework) CreateDelegationBlockFromInput(issuerID iotago.Acc func (d *DockerTestFramework) CreateFoundryBlockFromInput(issuerID iotago.AccountID, inputID iotago.OutputID, mintedAmount iotago.BaseToken, maxSupply iotago.BaseToken) (iotago.FoundryID, iotago.OutputID, *iotago.Block) { issuer := d.wallet.Account(issuerID) ctx := context.TODO() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) signedTx := d.wallet.CreateFoundryAndNativeTokensFromInput(issuerID, inputID, mintedAmount, maxSupply, issuerResp) @@ -439,7 +470,7 @@ func (d *DockerTestFramework) CreateFoundryBlockFromInput(issuerID iotago.Accoun func (d *DockerTestFramework) CreateNFTBlockFromInput(issuerID iotago.AccountID, inputID iotago.OutputID, opts ...options.Option[builder.NFTOutputBuilder]) (iotago.NFTID, iotago.OutputID, *iotago.Block) { issuer := d.wallet.Account(issuerID) ctx := context.TODO() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) signedTx := d.wallet.CreateNFTFromInput(issuerID, inputID, issuerResp, opts...) @@ -453,7 +484,7 @@ func (d *DockerTestFramework) CreateNFTBlockFromInput(issuerID iotago.AccountID, // CreateFoundryTransitionBlockFromInput consumes the given foundry output, then build block by increasing the minted amount by 1. func (d *DockerTestFramework) CreateFoundryTransitionBlockFromInput(issuerID iotago.AccountID, inputID iotago.OutputID) (iotago.FoundryID, iotago.OutputID, *iotago.Block) { ctx := context.TODO() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuer := d.wallet.Account(issuerID) issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) @@ -470,7 +501,7 @@ func (d *DockerTestFramework) CreateFoundryTransitionBlockFromInput(issuerID iot // CreateAccountBlockFromInput consumes the given output, which should be either an basic output with implicit address, then build block with the given account output options. Note that after the returned transaction is issued, remember to update the account information in the wallet with AddAccount(). func (d *DockerTestFramework) CreateAccountBlockFromInput(inputID iotago.OutputID) (*mock.AccountData, iotago.OutputID, *iotago.Block) { ctx := context.TODO() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client input := d.wallet.Output(inputID) // check if the given input is an BasicOutput with implicit address @@ -517,7 +548,7 @@ func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.Accou // create an implicit account by requesting faucet funds ctx := context.TODO() implicitAccount := d.CreateImplicitAccount(ctx) - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, implicitAccount.Address) fullAccount, signedTx := d.wallet.TransitionImplicitAccountToAccountOutput(implicitAccount.OutputID, issuerResp, opts...) @@ -540,7 +571,7 @@ func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.Accou // DelegateToValidator requests faucet funds and delegate the UTXO output to the validator. func (d *DockerTestFramework) DelegateToValidator(fromID iotago.AccountID, accountAddress *iotago.AccountAddress) (iotago.OutputID, *iotago.DelegationOutput) { from := d.wallet.Account(fromID) - clt := d.wallet.DefaultClient() + clt := d.wallet.Client // requesting faucet funds as delegation input ctx := context.TODO() @@ -561,7 +592,7 @@ func (d *DockerTestFramework) DelegateToValidator(fromID iotago.AccountID, accou } // PrepareBlockIssuance prepares the BlockIssuance and Congestion response, and increase BIC of the issuer if necessary. -func (d *DockerTestFramework) PrepareBlockIssuance(ctx context.Context, clt *nodeclient.Client, issuerAddress *iotago.AccountAddress) (*api.IssuanceBlockHeaderResponse, *api.CongestionResponse) { +func (d *DockerTestFramework) PrepareBlockIssuance(ctx context.Context, clt mock.Client, issuerAddress *iotago.AccountAddress) (*api.IssuanceBlockHeaderResponse, *api.CongestionResponse) { issuerResp, err := clt.BlockIssuance(ctx) require.NoError(d.Testing, err) @@ -578,7 +609,7 @@ func (d *DockerTestFramework) AllotManaTo(fromID iotago.AccountID, toID iotago.A // requesting faucet funds for allotment ctx := context.TODO() fundsOutputID := d.RequestFaucetFunds(ctx, iotago.AddressEd25519) - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, from.Address) signedTx := d.wallet.AllotManaFromAccount(fromID, toID, manaToAllot, fundsOutputID) @@ -607,7 +638,7 @@ func (d *DockerTestFramework) CreateNativeToken(fromID iotago.AccountID, mintedA require.GreaterOrEqual(d.Testing, maxSupply, mintedAmount) ctx := context.TODO() - clt := d.wallet.DefaultClient() + clt := d.wallet.Client from := d.wallet.Account(fromID) // requesting faucet funds for native token creation @@ -740,7 +771,7 @@ func (d *DockerTestFramework) GetContainersConfigs() { } func (d *DockerTestFramework) CreateBlock(payload iotago.Payload, issuerID iotago.AccountID, congestionResp *api.CongestionResponse, issuerResp *api.IssuanceBlockHeaderResponse) *iotago.Block { - clt := d.wallet.DefaultClient() + clt := d.wallet.Client issuingTime := time.Now() apiForSlot := clt.APIForSlot(clt.LatestAPI().TimeProvider().SlotFromTime(issuingTime)) blockBuilder := builder.NewBasicBlockBuilder(apiForSlot) @@ -767,14 +798,14 @@ func (d *DockerTestFramework) CreateBlock(payload iotago.Payload, issuerID iotag } func (d *DockerTestFramework) SubmitBlock(ctx context.Context, blk *iotago.Block) { - clt := d.wallet.DefaultClient() + clt := d.wallet.Client _, err := clt.SubmitBlock(ctx, blk) require.NoError(d.Testing, err) } func (d *DockerTestFramework) SubmitPayload(ctx context.Context, payload iotago.Payload, issuerID iotago.AccountID, congestionResp *api.CongestionResponse, issuerResp *api.IssuanceBlockHeaderResponse) iotago.BlockID { - clt := d.wallet.DefaultClient() + clt := d.wallet.Client blk := d.CreateBlock(payload, issuerID, congestionResp, issuerResp) diff --git a/tools/docker-network/tests/eventapiframework.go b/tools/docker-network/tests/eventapiframework.go index 2886d8dfa..98c808ba8 100644 --- a/tools/docker-network/tests/eventapiframework.go +++ b/tools/docker-network/tests/eventapiframework.go @@ -23,7 +23,7 @@ type EventAPIDockerTestFramework struct { Testing *testing.T dockerFramework *DockerTestFramework - DefaultClient *nodeclient.Client + DefaultClient mock.Client finishChan chan struct{} @@ -35,7 +35,7 @@ func NewEventAPIDockerTestFramework(t *testing.T, dockerFramework *DockerTestFra return &EventAPIDockerTestFramework{ Testing: t, dockerFramework: dockerFramework, - DefaultClient: dockerFramework.wallet.DefaultClient(), + DefaultClient: dockerFramework.wallet.Client, finishChan: make(chan struct{}), optsWaitFor: 3 * time.Minute, optsTick: 5 * time.Second, diff --git a/tools/docker-network/tests/mempool_invalid_signatures_test.go b/tools/docker-network/tests/mempool_invalid_signatures_test.go index 85112ca10..03422c358 100644 --- a/tools/docker-network/tests/mempool_invalid_signatures_test.go +++ b/tools/docker-network/tests/mempool_invalid_signatures_test.go @@ -51,18 +51,18 @@ func Test_MempoolInvalidSignatures(t *testing.T) { } fmt.Println("Submitting block with invalid TX") - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, d.wallet.DefaultClient(), account.ID.ToAddress().(*iotago.AccountAddress)) + issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, d.wallet.Client, account.ID.ToAddress().(*iotago.AccountAddress)) d.SubmitPayload(context.Background(), invalidTX, account.ID, congestionResp, issuerResp) d.AwaitTransactionState(ctx, invalidTX.Transaction.MustID(), api.TransactionStateFailed) d.AwaitTransactionFailure(ctx, invalidTX.Transaction.MustID(), api.TxFailureUnlockSignatureInvalid) fmt.Println("Submitting block with valid TX") - issuerResp, congestionResp = d.PrepareBlockIssuance(ctx, d.wallet.DefaultClient(), account.ID.ToAddress().(*iotago.AccountAddress)) + issuerResp, congestionResp = d.PrepareBlockIssuance(ctx, d.wallet.Client, account.ID.ToAddress().(*iotago.AccountAddress)) d.SubmitPayload(context.Background(), validTX, account.ID, congestionResp, issuerResp) fmt.Println("Submitting block with invalid TX (again)") - issuerResp, congestionResp = d.PrepareBlockIssuance(ctx, d.wallet.DefaultClient(), account.ID.ToAddress().(*iotago.AccountAddress)) + issuerResp, congestionResp = d.PrepareBlockIssuance(ctx, d.wallet.Client, account.ID.ToAddress().(*iotago.AccountAddress)) d.SubmitPayload(context.Background(), invalidTX, account.ID, congestionResp, issuerResp) d.AwaitTransactionPayloadAccepted(ctx, validTX.Transaction.MustID()) diff --git a/tools/docker-network/tests/utils.go b/tools/docker-network/tests/utils.go index 244ceeb50..fe1f7212e 100644 --- a/tools/docker-network/tests/utils.go +++ b/tools/docker-network/tests/utils.go @@ -27,7 +27,7 @@ import ( func (d *DockerTestFramework) CheckAccountStatus(ctx context.Context, blkID iotago.BlockID, txID iotago.TransactionID, creationOutputID iotago.OutputID, accountAddress *iotago.AccountAddress, checkIndexer ...bool) { // request by blockID if provided, otherwise use txID // we take the slot from the blockID in case the tx is created earlier than the block. - clt := d.wallet.DefaultClient() + clt := d.wallet.Client slot := blkID.Slot() if blkID == iotago.EmptyBlockID { @@ -45,7 +45,7 @@ func (d *DockerTestFramework) CheckAccountStatus(ctx context.Context, blkID iota // Check the indexer if len(checkIndexer) > 0 && checkIndexer[0] { - indexerClt, err := d.wallet.DefaultClient().Indexer(ctx) + indexerClt, err := d.wallet.Client.Indexer(ctx) require.NoError(d.Testing, err) _, _, _, err = indexerClt.Account(ctx, accountAddress) @@ -60,7 +60,7 @@ func (d *DockerTestFramework) CheckAccountStatus(ctx context.Context, blkID iota func (d *DockerTestFramework) AssertIndexerAccount(account *mock.AccountData) { d.Eventually(func() error { ctx := context.TODO() - indexerClt, err := d.wallet.DefaultClient().Indexer(ctx) + indexerClt, err := d.wallet.Client.Indexer(ctx) if err != nil { return err } @@ -80,7 +80,7 @@ func (d *DockerTestFramework) AssertIndexerAccount(account *mock.AccountData) { func (d *DockerTestFramework) AssertIndexerFoundry(foundryID iotago.FoundryID) { d.Eventually(func() error { ctx := context.TODO() - indexerClt, err := d.wallet.DefaultClient().Indexer(ctx) + indexerClt, err := d.wallet.Client.Indexer(ctx) if err != nil { return err } @@ -97,7 +97,7 @@ func (d *DockerTestFramework) AssertIndexerFoundry(foundryID iotago.FoundryID) { func (d *DockerTestFramework) AssertValidatorExists(accountAddr *iotago.AccountAddress) { d.Eventually(func() error { for _, node := range d.Nodes() { - _, err := d.wallet.Clients[node.Name].Validator(context.TODO(), accountAddr) + _, err := d.Client(node.Name).Validator(context.TODO(), accountAddr) if err != nil { return err } @@ -114,7 +114,7 @@ func (d *DockerTestFramework) AssertCommittee(expectedEpoch iotago.EpochIndex, e sort.Strings(expectedCommitteeMember) status := d.NodeStatus("V1") - testAPI := d.wallet.DefaultClient().CommittedAPI() + testAPI := d.wallet.Client.CommittedAPI() expectedSlotStart := testAPI.TimeProvider().EpochStart(expectedEpoch) require.Greater(d.Testing, expectedSlotStart, status.LatestAcceptedBlockSlot) @@ -125,7 +125,7 @@ func (d *DockerTestFramework) AssertCommittee(expectedEpoch iotago.EpochIndex, e d.Eventually(func() error { for _, node := range d.Nodes() { - resp, err := d.wallet.Clients[node.Name].Committee(context.TODO()) + resp, err := d.Client(node.Name).Committee(context.TODO()) if err != nil { return err } @@ -195,7 +195,7 @@ func (d *DockerTestFramework) Eventually(condition func() error, waitForSync ... } func (d *DockerTestFramework) AwaitTransactionPayloadAccepted(ctx context.Context, txID iotago.TransactionID) { - clt := d.wallet.DefaultClient() + clt := d.wallet.Client d.Eventually(func() error { resp, err := clt.TransactionMetadata(ctx, txID) @@ -216,10 +216,8 @@ func (d *DockerTestFramework) AwaitTransactionPayloadAccepted(ctx context.Contex } func (d *DockerTestFramework) AwaitTransactionState(ctx context.Context, txID iotago.TransactionID, expectedState api.TransactionState) { - clt := d.wallet.DefaultClient() - d.Eventually(func() error { - resp, err := clt.TransactionMetadata(ctx, txID) + resp, err := d.wallet.Client.TransactionMetadata(ctx, txID) if err != nil { return err } @@ -233,10 +231,8 @@ func (d *DockerTestFramework) AwaitTransactionState(ctx context.Context, txID io } func (d *DockerTestFramework) AwaitTransactionFailure(ctx context.Context, txID iotago.TransactionID, expectedReason api.TransactionFailureReason) { - clt := d.wallet.DefaultClient() - d.Eventually(func() error { - resp, err := clt.TransactionMetadata(ctx, txID) + resp, err := d.wallet.Client.TransactionMetadata(ctx, txID) if err != nil { return err } @@ -275,9 +271,9 @@ func (d *DockerTestFramework) AwaitFinalization(targetSlot iotago.SlotIndex) { } func (d *DockerTestFramework) AwaitAddressUnspentOutputAccepted(ctx context.Context, addr iotago.Address) (outputID iotago.OutputID, output iotago.Output, err error) { - indexerClt, err := d.wallet.DefaultClient().Indexer(ctx) + indexerClt, err := d.wallet.Client.Indexer(ctx) require.NoError(d.Testing, err) - addrBech := addr.Bech32(d.wallet.DefaultClient().CommittedAPI().ProtocolParameters().Bech32HRP()) + addrBech := addr.Bech32(d.wallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP()) for t := time.Now(); time.Since(t) < d.optsWaitFor; time.Sleep(d.optsTick) { res, err := indexerClt.Outputs(ctx, &api.BasicOutputsQuery{ @@ -305,7 +301,7 @@ func (d *DockerTestFramework) AwaitAddressUnspentOutputAccepted(ctx context.Cont } func (d *DockerTestFramework) SendFaucetRequest(ctx context.Context, receiveAddr iotago.Address) { - cltAPI := d.wallet.DefaultClient().CommittedAPI() + cltAPI := d.wallet.Client.CommittedAPI() addrBech := receiveAddr.Bech32(cltAPI.ProtocolParameters().Bech32HRP()) type EnqueueRequest struct { diff --git a/tools/docker-network/tests/wallet.go b/tools/docker-network/tests/wallet.go index a1a70372e..da950ad71 100644 --- a/tools/docker-network/tests/wallet.go +++ b/tools/docker-network/tests/wallet.go @@ -20,7 +20,6 @@ import ( iotago "github.com/iotaledger/iota.go/v4" "github.com/iotaledger/iota.go/v4/api" "github.com/iotaledger/iota.go/v4/builder" - "github.com/iotaledger/iota.go/v4/nodeclient" "github.com/iotaledger/iota.go/v4/wallet" ) @@ -28,11 +27,12 @@ import ( type DockerWallet struct { Testing *testing.T - // a map of clients for each node in the network - Clients map[string]*nodeclient.Client + Client mock.Client keyManager *wallet.KeyManager + BlockIssuer *mock.BlockIssuer + lastUsedIndex atomic.Uint32 outputs map[iotago.OutputID]*mock.OutputData @@ -47,15 +47,10 @@ func NewDockerWallet(t *testing.T) *DockerWallet { Testing: t, outputs: make(map[iotago.OutputID]*mock.OutputData), accounts: make(map[iotago.AccountID]*mock.AccountData), - Clients: make(map[string]*nodeclient.Client), keyManager: lo.PanicOnErr(wallet.NewKeyManagerFromRandom(wallet.DefaultIOTAPath)), } } -func (w *DockerWallet) DefaultClient() *nodeclient.Client { - return w.Clients["V1"] -} - func (w *DockerWallet) AddOutput(outputID iotago.OutputID, output *mock.OutputData) { w.outputsLock.Lock() defer w.outputsLock.Unlock() @@ -149,8 +144,8 @@ func (w *DockerWallet) AllotManaFromAccount(fromID iotago.AccountID, toID iotago to := w.Account(toID) input := w.Output(inputID) - currentSlot := w.DefaultClient().LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.DefaultClient().APIForSlot(currentSlot) + currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) basicOutput, ok := input.Output.(*iotago.BasicOutput) require.True(w.Testing, ok) @@ -193,8 +188,8 @@ func (w *DockerWallet) AllotManaFromInput(toID iotago.AccountID, inputID iotago. to := w.Account(toID) input := w.Output(inputID) - currentSlot := w.DefaultClient().LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.DefaultClient().APIForSlot(currentSlot) + currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) basicOutput, err := builder.NewBasicOutputBuilder(input.Address, input.Output.BaseTokenAmount()).Build() require.NoError(w.Testing, err) @@ -229,8 +224,8 @@ func (w *DockerWallet) TransitionImplicitAccountToAccountOutput(inputID iotago.O accountAddress, ok := accountID.ToAddress().(*iotago.AccountAddress) require.True(w.Testing, ok) - currentSlot := w.DefaultClient().LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.DefaultClient().APIForSlot(currentSlot) + currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) // transition to a full account with new Ed25519 address and staking feature accEd25519AddrIndex, accEd25519Addr := w.Address() @@ -280,8 +275,8 @@ func (w *DockerWallet) TransitionImplicitAccountToAccountOutput(inputID iotago.O func (w *DockerWallet) CreateDelegationFromInput(issuerID iotago.AccountID, validatorAccountAddr *iotago.AccountAddress, inputID iotago.OutputID, issuerResp *api.IssuanceBlockHeaderResponse) *iotago.SignedTransaction { input := w.Output(inputID) - currentSlot := w.DefaultClient().LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.DefaultClient().APIForSlot(currentSlot) + currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) // construct delegation transaction //nolint:forcetypeassert @@ -317,8 +312,8 @@ func (w *DockerWallet) CreateFoundryAndNativeTokensFromInput(issuerID iotago.Acc input := w.Output(inputID) issuer := w.Account(issuerID) - currentSlot := w.DefaultClient().LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.DefaultClient().APIForSlot(currentSlot) + currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) // increase foundry counter accTransitionOutput := builder.NewAccountOutputBuilderFromPrevious(issuer.Output). @@ -409,8 +404,8 @@ func (w *DockerWallet) TransitionFoundry(issuerID iotago.AccountID, inputID iota outputAccount := builder.NewAccountOutputBuilderFromPrevious(issuer.Output). MustBuild() - currentSlot := w.DefaultClient().LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.DefaultClient().APIForSlot(currentSlot) + currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex, issuer.AddressIndex)). AddInput(&builder.TxInput{ @@ -455,8 +450,8 @@ func (w *DockerWallet) TransitionFoundry(issuerID iotago.AccountID, inputID iota func (w *DockerWallet) CreateNFTFromInput(issuerID iotago.AccountID, inputID iotago.OutputID, issuerResp *api.IssuanceBlockHeaderResponse, opts ...options.Option[builder.NFTOutputBuilder]) *iotago.SignedTransaction { input := w.Output(inputID) - currentSlot := w.DefaultClient().LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.DefaultClient().APIForSlot(currentSlot) + currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) nftAddressIndex, nftAddress := w.Address() nftOutputBuilder := builder.NewNFTOutputBuilder(nftAddress, input.Output.BaseTokenAmount()) @@ -490,8 +485,8 @@ func (w *DockerWallet) CreateNFTFromInput(issuerID iotago.AccountID, inputID iot } func (w *DockerWallet) CreateBasicOutputFromInput(input *mock.OutputData, issuerAccountID iotago.AccountID) *iotago.SignedTransaction { - currentSlot := w.DefaultClient().LatestAPI().TimeProvider().SlotFromTime(time.Now()) - apiForSlot := w.DefaultClient().APIForSlot(currentSlot) + currentSlot := w.Client.LatestAPI().TimeProvider().SlotFromTime(time.Now()) + apiForSlot := w.Client.APIForSlot(currentSlot) _, ed25519Addr := w.Address() basicOutput := builder.NewBasicOutputBuilder(ed25519Addr, input.Output.BaseTokenAmount()).MustBuild() signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex)). From b03dbd43f9cd5f7a08059d1bc381459191a7ca9b Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 20 Mar 2024 10:42:18 +0000 Subject: [PATCH 02/23] initialise wallet client correctly --- tools/docker-network/tests/dockerframework.go | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 7e49c6f97..dbd13fe99 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -206,6 +206,7 @@ func (d *DockerTestFramework) waitForNodesAndGetClients() error { d.nodes[node.Name] = node d.clients[node.Name] = client } + d.wallet.Client = d.clients["V1"] return nil } From 6a361b05805891c21e56e34c9ee1d40d7b4caf62 Mon Sep 17 00:00:00 2001 From: Andrew Date: Tue, 26 Mar 2024 16:44:24 +0000 Subject: [PATCH 03/23] unify wallets (with some bugs) --- pkg/tests/accounts_test.go | 5 +- pkg/tests/booker_test.go | 2 +- pkg/tests/combined_account_transition_test.go | 4 +- pkg/tests/reward_test.go | 14 +- pkg/testsuite/mock/blockissuer.go | 4 +- pkg/testsuite/mock/wallet.go | 54 +++- pkg/testsuite/mock/wallet_transactions.go | 152 ++++++++-- pkg/testsuite/workscore_regression_test.go | 16 +- .../tests/accounttransition_test.go | 8 +- .../tests/committeerotation_test.go | 14 +- tools/docker-network/tests/coreapi.go | 15 +- tools/docker-network/tests/coreapi_test.go | 10 +- tools/docker-network/tests/dockerframework.go | 282 +++++++----------- tools/docker-network/tests/eventapi_test.go | 41 ++- .../docker-network/tests/eventapiframework.go | 6 +- .../tests/mempool_invalid_signatures_test.go | 17 +- tools/docker-network/tests/utils.go | 26 +- tools/docker-network/tests/wallet.go | 88 ------ 18 files changed, 377 insertions(+), 381 deletions(-) diff --git a/pkg/tests/accounts_test.go b/pkg/tests/accounts_test.go index dfe4cde40..059febe6e 100644 --- a/pkg/tests/accounts_test.go +++ b/pkg/tests/accounts_test.go @@ -268,7 +268,7 @@ func Test_StakeDelegateAndDelayedClaim(t *testing.T) { block2Slot := ts.CurrentSlot() tx2 := ts.DefaultWallet().CreateDelegationFromInput( "TX2", - "TX1:1", + ts.DefaultWallet().OutputData("TX1:1"), mock.WithDelegatedValidatorAddress(&accountAddress), mock.WithDelegationStartEpoch(1), ) @@ -414,9 +414,10 @@ func Test_ImplicitAccounts(t *testing.T) { fullAccountBlockIssuerKey := tpkg.RandBlockIssuerKey() block2Slot := ts.CurrentSlot() + implicitAccountData := newUserWallet.OutputData("TX1:0") tx2 := newUserWallet.TransitionImplicitAccountToAccountOutput( "TX2", - []string{"TX1:0"}, + []*mock.OutputData{implicitAccountData}, mock.WithBlockIssuerFeature( iotago.BlockIssuerKeys{fullAccountBlockIssuerKey}, iotago.MaxSlotIndex, diff --git a/pkg/tests/booker_test.go b/pkg/tests/booker_test.go index 7b6b78e26..fed22db19 100644 --- a/pkg/tests/booker_test.go +++ b/pkg/tests/booker_test.go @@ -855,7 +855,7 @@ func Test_BlockWithInvalidTransactionGetsBooked(t *testing.T) { var block1Slot iotago.SlotIndex = ts.API.ProtocolParameters().GenesisSlot() + 1 ts.SetCurrentSlot(block1Slot) - tx1 := ts.DefaultWallet().CreateNFTFromInput("TX1", "Genesis:0", + tx1 := ts.DefaultWallet().CreateNFTFromInput("TX1", ts.DefaultWallet().OutputData("Genesis:0"), func(nftBuilder *builder.NFTOutputBuilder) { // Set an issuer ID that is not unlocked in the TX which will cause the TX to be invalid. nftBuilder.ImmutableIssuer(&iotago.Ed25519Address{}) diff --git a/pkg/tests/combined_account_transition_test.go b/pkg/tests/combined_account_transition_test.go index 5717b6f37..e82b1330d 100644 --- a/pkg/tests/combined_account_transition_test.go +++ b/pkg/tests/combined_account_transition_test.go @@ -152,9 +152,11 @@ func createImplicitToFullAccount(ts *testsuite.TestSuite) iotago.AccountID { // TRANSITION IMPLICIT ACCOUNT TO ACCOUNT OUTPUT. block3Slot := ts.CurrentSlot() + implicitAccoutData := newUserWallet.OutputData("TX3:0") + basicOutputData := newUserWallet.OutputData("TX3:1") tx4 := newUserWallet.TransitionImplicitAccountToAccountOutput( "TX4", - []string{"TX3:0", "TX3:1"}, + []*mock.OutputData{implicitAccoutData, basicOutputData}, mock.WithBlockIssuerFeature( iotago.BlockIssuerKeys{implicitBlockIssuerKey}, iotago.MaxSlotIndex, diff --git a/pkg/tests/reward_test.go b/pkg/tests/reward_test.go index a82fa3736..292cbbcb4 100644 --- a/pkg/tests/reward_test.go +++ b/pkg/tests/reward_test.go @@ -75,7 +75,7 @@ func Test_Delegation_DestroyOutputWithoutRewards(t *testing.T) { ts.SetCurrentSlot(block1Slot) tx1 := ts.DefaultWallet().CreateDelegationFromInput( "TX1", - "Genesis:0", + ts.DefaultWallet().OutputData("Genesis:0"), mock.WithDelegatedValidatorAddress(accountAddress), mock.WithDelegationStartEpoch(1), ) @@ -103,7 +103,7 @@ func Test_Delegation_DelayedClaimingDestroyOutputWithoutRewards(t *testing.T) { ts.SetCurrentSlot(block1_2Slot) tx1 := ts.DefaultWallet().CreateDelegationFromInput( "TX1", - "Genesis:0", + ts.DefaultWallet().OutputData("Genesis:0"), mock.WithDelegatedValidatorAddress(accountAddress), mock.WithDelegationStartEpoch(1), ) @@ -227,7 +227,7 @@ func Test_RewardInputCannotPointToNFTOutput(t *testing.T) { var block1Slot iotago.SlotIndex = 1 ts.SetCurrentSlot(block1Slot) - tx1 := ts.DefaultWallet().CreateNFTFromInput("TX1", "Genesis:0") + tx1 := ts.DefaultWallet().CreateNFTFromInput("TX1", ts.DefaultWallet().OutputData("Genesis:0")) block1 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block1", ts.DefaultWallet(), tx1)) latestParents := ts.CommitUntilSlot(block1Slot, block1.ID()) @@ -301,7 +301,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { blockIssuanceResp := ts.DefaultWallet().GetNewBlockIssuanceResponse() tx2 := ts.DefaultWallet().CreateDelegationFromInput( "TX2", - "TX1:1", + ts.DefaultWallet().OutputData("TX1:1"), mock.WithDelegationAmount(deleg1), mock.WithDelegatedAmount(deleg1), mock.WithDelegatedValidatorAddress(&accountAddress), @@ -326,7 +326,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { // Create another delegation. tx4 := ts.DefaultWallet().CreateDelegationFromInput( "TX4", - "TX2:1", + ts.DefaultWallet().OutputData("TX2:1"), mock.WithDelegationAmount(deleg2), mock.WithDelegatedAmount(deleg2), mock.WithDelegatedValidatorAddress(&accountAddress), @@ -343,7 +343,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { blockIssuanceResp = ts.DefaultWallet().GetNewBlockIssuanceResponse() tx5 := ts.DefaultWallet().CreateDelegationFromInput( "TX5", - "TX4:1", + ts.DefaultWallet().OutputData("TX4:1"), mock.WithDelegationAmount(deleg3), mock.WithDelegatedAmount(deleg3), mock.WithDelegatedValidatorAddress(&accountAddress), @@ -365,7 +365,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { blockIssuanceResp = ts.DefaultWallet().GetNewBlockIssuanceResponse() tx7 := ts.DefaultWallet().CreateDelegationFromInput( "TX7", - "TX5:1", + ts.DefaultWallet().OutputData("TX5:1"), mock.WithDelegationAmount(deleg4), mock.WithDelegatedAmount(deleg4), mock.WithDelegatedValidatorAddress(&accountAddress), diff --git a/pkg/testsuite/mock/blockissuer.go b/pkg/testsuite/mock/blockissuer.go index 0c5391fb3..6f7ba0f75 100644 --- a/pkg/testsuite/mock/blockissuer.go +++ b/pkg/testsuite/mock/blockissuer.go @@ -51,7 +51,7 @@ type BlockIssuer struct { blockIssuanceResponseUsed bool mutex syncutils.RWMutex - AccountData AccountData + AccountData *AccountData } func NewBlockIssuer(t *testing.T, name string, keyManager *wallet.KeyManager, client Client, addressIndex uint32, accountID iotago.AccountID, validator bool, opts ...options.Option[BlockIssuer]) *BlockIssuer { @@ -72,7 +72,7 @@ func NewBlockIssuer(t *testing.T, name string, keyManager *wallet.KeyManager, cl keyManager: keyManager, Client: client, blockIssuanceResponseUsed: true, - AccountData: AccountData{ + AccountData: &AccountData{ ID: accountID, AddressIndex: addressIndex, Address: accountAddress, diff --git a/pkg/testsuite/mock/wallet.go b/pkg/testsuite/mock/wallet.go index d381fb420..545ce9e51 100644 --- a/pkg/testsuite/mock/wallet.go +++ b/pkg/testsuite/mock/wallet.go @@ -2,6 +2,7 @@ package mock import ( "crypto/ed25519" + "sync" "testing" "github.com/iotaledger/hive.go/ierrors" @@ -79,8 +80,13 @@ type Wallet struct { BlockIssuer *BlockIssuer outputs map[string]*OutputData + outputsByID map[iotago.OutputID]*OutputData transactions map[string]*iotago.Transaction - clock WalletClock + + accounts map[iotago.AccountID]*AccountData + accountsLock sync.RWMutex + + clock WalletClock } func NewWallet(t *testing.T, name string, client Client, keyManager ...*wallet.KeyManager) *Wallet { @@ -98,6 +104,8 @@ func NewWallet(t *testing.T, name string, client Client, keyManager ...*wallet.K Name: name, Client: client, outputs: make(map[string]*OutputData), + outputsByID: make(map[iotago.OutputID]*OutputData), + accounts: make(map[iotago.AccountID]*AccountData), transactions: make(map[string]*iotago.Transaction), keyManager: km, BlockIssuer: NewBlockIssuer(t, name, km, client, blockIssuerAddressIndex, blockIssuerID, false), @@ -124,6 +132,7 @@ func (w *Wallet) CurrentSlot() iotago.SlotIndex { func (w *Wallet) AddOutput(outputName string, output *OutputData) { w.outputs[outputName] = output + w.outputsByID[output.ID] = output } func (w *Wallet) Balance() iotago.BaseToken { @@ -144,6 +153,15 @@ func (w *Wallet) OutputData(outputName string) *OutputData { return output } +func (w *Wallet) Output(outputID iotago.OutputID) *OutputData { + output, exists := w.outputsByID[outputID] + if !exists { + panic(ierrors.Errorf("output %s not registered in wallet %s", outputID.ToHex(), w.Name)) + } + + return output +} + func (w *Wallet) AccountOutputData(outputName string) *OutputData { output := w.OutputData(outputName) if _, ok := output.Output.(*iotago.AccountOutput); !ok { @@ -170,6 +188,40 @@ func (w *Wallet) TransactionID(alias string) iotago.TransactionID { return w.Transaction(alias).MustID() } +func (w *Wallet) Account(accountID iotago.AccountID) *AccountData { + w.accountsLock.RLock() + defer w.accountsLock.RUnlock() + + acc, exists := w.accounts[accountID] + if !exists { + panic(ierrors.Errorf("account %s not registered in wallet", accountID.ToHex())) + } + + return acc +} + +func (w *Wallet) Accounts(accountIDs ...iotago.AccountID) []*AccountData { + w.accountsLock.RLock() + defer w.accountsLock.RUnlock() + + accounts := make([]*AccountData, 0) + if len(accountIDs) == 0 { + for _, acc := range w.accounts { + accounts = append(accounts, acc) + } + } + + for _, id := range accountIDs { + acc, exists := w.accounts[id] + if !exists { + panic(ierrors.Errorf("account %s not registered in wallet", id.ToHex())) + } + accounts = append(accounts, acc) + } + + return accounts +} + func (w *Wallet) Address(index ...uint32) iotago.DirectUnlockableAddress { address := w.keyManager.Address(iotago.AddressEd25519, index...) //nolint:forcetypeassert diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 9a4362755..19e40e7fe 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -95,9 +95,7 @@ func (w *Wallet) CreateAccountsFromInput(transactionName string, inputName strin // CreateDelegationFromInput creates a new DelegationOutput with given options from an input. If the remainder Output // is not created, then StoredMana from the input is not passed and can potentially be burned. // In order not to burn it, it needs to be assigned manually in another output in the transaction. -func (w *Wallet) CreateDelegationFromInput(transactionName string, inputName string, opts ...options.Option[builder.DelegationOutputBuilder]) *iotago.SignedTransaction { - input := w.OutputData(inputName) - +func (w *Wallet) CreateDelegationFromInput(transactionName string, input *OutputData, opts ...options.Option[builder.DelegationOutputBuilder]) *iotago.SignedTransaction { delegationOutput := options.Apply(builder.NewDelegationOutputBuilder(&iotago.AccountAddress{}, w.Address(), input.Output.BaseTokenAmount()). DelegatedAmount(input.Output.BaseTokenAmount()), opts).MustBuild() @@ -385,15 +383,13 @@ func (w *Wallet) CreateImplicitAccountAndBasicOutputFromInput(transactionName st return signedTransaction } -func (w *Wallet) TransitionImplicitAccountToAccountOutput(transactionName string, inputNames []string, opts ...options.Option[builder.AccountOutputBuilder]) *iotago.SignedTransaction { +func (w *Wallet) TransitionImplicitAccountToAccountOutput(transactionName string, inputs []*OutputData, opts ...options.Option[builder.AccountOutputBuilder]) *iotago.SignedTransaction { var implicitAccountOutput *OutputData var baseTokenAmount iotago.BaseToken - inputs := make([]*OutputData, 0, len(inputNames)) - for _, inputName := range inputNames { - input := w.OutputData(inputName) + for _, input := range inputs { basicOutput, isBasic := input.Output.(*iotago.BasicOutput) if !isBasic { - panic(fmt.Sprintf("output with alias %s is not *iotago.BasicOutput", inputName)) + panic("input is not *iotago.BasicOutput") } if basicOutput.UnlockConditionSet().Address().Address.Type() == iotago.AddressImplicitAccountCreation { if implicitAccountOutput != nil { @@ -401,7 +397,6 @@ func (w *Wallet) TransitionImplicitAccountToAccountOutput(transactionName string } implicitAccountOutput = input } - inputs = append(inputs, input) baseTokenAmount += input.Output.BaseTokenAmount() } if implicitAccountOutput == nil { @@ -430,14 +425,77 @@ func (w *Wallet) TransitionImplicitAccountToAccountOutput(transactionName string return signedTransaction } -func (w *Wallet) CreateFoundryAndNativeTokensFromInput(transactionName string, inputName string, accountName string, addressIndexes ...uint32) *iotago.SignedTransaction { +func (w *Wallet) CreateFoundryAndNativeTokensFromInput(input *OutputData, mintedAmount iotago.BaseToken, maxSupply iotago.BaseToken) *iotago.SignedTransaction { + issuer := w.BlockIssuer.AccountData + currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) + + // increase foundry counter + accTransitionOutput := builder.NewAccountOutputBuilderFromPrevious(issuer.Output). + FoundriesToGenerate(1).MustBuild() + + // build foundry output + foundryID, err := iotago.FoundryIDFromAddressAndSerialNumberAndTokenScheme(issuer.Address, accTransitionOutput.FoundryCounter, iotago.TokenSchemeSimple) + require.NoError(w.Testing, err) + tokenScheme := &iotago.SimpleTokenScheme{ + MintedTokens: big.NewInt(int64(mintedAmount)), + MaximumSupply: big.NewInt(int64(maxSupply)), + MeltedTokens: big.NewInt(0), + } + + foundryOutput := builder.NewFoundryOutputBuilder(issuer.Address, input.Output.BaseTokenAmount(), accTransitionOutput.FoundryCounter, tokenScheme). + NativeToken(&iotago.NativeTokenFeature{ + ID: foundryID, + Amount: big.NewInt(int64(mintedAmount)), + }).MustBuild() + + signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex, issuer.AddressIndex)). + AddInput(&builder.TxInput{ + UnlockTarget: input.Address, + InputID: input.ID, + Input: input.Output, + }). + AddInput(&builder.TxInput{ + UnlockTarget: issuer.Output.UnlockConditionSet().Address().Address, + InputID: issuer.OutputID, + Input: issuer.Output, + }). + AddOutput(accTransitionOutput). + AddOutput(foundryOutput). + SetCreationSlot(currentSlot). + AddBlockIssuanceCreditInput(&iotago.BlockIssuanceCreditInput{AccountID: issuer.ID}). + AddCommitmentInput(&iotago.CommitmentInput{CommitmentID: w.GetNewBlockIssuanceResponse().LatestCommitment.MustID()}). + AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("foundry")}). + AllotAllMana(currentSlot, issuer.ID, 0). + Build() + require.NoError(w.Testing, err) + + foundryOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 1) + w.AddOutput("", &OutputData{ + ID: foundryOutputID, + Output: foundryOutput, + Address: issuer.Address, + }) + + //nolint:forcetypeassert + w.BlockIssuer.AccountData = &AccountData{ + ID: issuer.ID, + Address: issuer.Address, + AddressIndex: issuer.AddressIndex, + Output: signedTx.Transaction.Outputs[0].(*iotago.AccountOutput), + OutputID: iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0), + } + + return signedTx +} + +func (w *Wallet) CreateFoundryAndNativeTokensOnOutputsFromInput(transactionName string, input *OutputData, accountName string, addressIndexes ...uint32) *iotago.SignedTransaction { nNativeTokens := len(addressIndexes) if nNativeTokens > iotago.MaxOutputsCount-2 { panic("too many address indexes provided") } outputStates := make(iotago.Outputs[iotago.Output], 0, nNativeTokens+2) - inputState := w.OutputData(inputName) inputAccountState := w.AccountOutputData(accountName) inputAccount, isAccount := inputAccountState.Output.(*iotago.AccountOutput) if !isAccount { @@ -449,7 +507,7 @@ func (w *Wallet) CreateFoundryAndNativeTokensFromInput(transactionName string, i } serialNumber := inputAccount.FoundryCounter + 1 - totalIn := inputState.Output.BaseTokenAmount() + totalIn := input.Output.BaseTokenAmount() outputAmount := totalIn / iotago.BaseToken(nNativeTokens+1) remainder := totalIn - outputAmount*iotago.BaseToken(nNativeTokens+1) @@ -487,7 +545,7 @@ func (w *Wallet) CreateFoundryAndNativeTokensFromInput(transactionName string, i signedTransaction := w.createSignedTransactionWithOptions( transactionName, []uint32{0}, - WithInputs(inputState, inputAccountState), + WithInputs(input, inputAccountState), WithOutputs(outputStates...), WithBlockIssuanceCreditInput(&iotago.BlockIssuanceCreditInput{ AccountID: accountOutput.AccountID, @@ -501,13 +559,16 @@ func (w *Wallet) CreateFoundryAndNativeTokensFromInput(transactionName string, i } // TransitionFoundry transitions a FoundryOutput by increasing the native token amount on the output by one. -func (w *Wallet) TransitionFoundry(transactionName string, inputName string, accountName string) *iotago.SignedTransaction { - input := w.OutputData(inputName) - inputFoundry, isFoundry := input.Output.(*iotago.FoundryOutput) +func (w *Wallet) TransitionFoundry(transactionName string, foundryInput *OutputData, accountInput *OutputData) *iotago.SignedTransaction { + + inputFoundry, isFoundry := foundryInput.Output.(*iotago.FoundryOutput) if !isFoundry { - panic(fmt.Sprintf("output with alias %s is not *iotago.FoundryOutput", inputName)) + panic("foundry input is not *iotago.FoundryOutput") + } + inputAccount, isAccount := foundryInput.Output.(*iotago.AccountOutput) + if !isAccount { + panic("account input is not *iotago.AccountOutput") } - inputAccount := w.AccountOutputData(accountName) nativeTokenAmount := inputFoundry.FeatureSet().NativeToken().Amount previousTokenScheme, isSimple := inputFoundry.TokenScheme.(*iotago.SimpleTokenScheme) if !isSimple { @@ -530,18 +591,13 @@ func (w *Wallet) TransitionFoundry(transactionName string, inputName string, acc }). TokenScheme(tokenScheme). MustBuild() - - inputAccountOutput, isAccountOutput := inputAccount.Output.(*iotago.AccountOutput) - if !isAccountOutput { - panic(fmt.Sprintf("output with alias %s is not *iotago.AccountOutput", accountName)) - } - outputAccount := builder.NewAccountOutputBuilderFromPrevious(inputAccountOutput). + outputAccount := builder.NewAccountOutputBuilderFromPrevious(inputAccount). MustBuild() signedTransaction := w.createSignedTransactionWithOptions( transactionName, []uint32{0}, - WithInputs(inputAccount, input), + WithInputs(accountInput, foundryInput), WithOutputs(outputAccount, outputFoundry), WithBlockIssuanceCreditInput(&iotago.BlockIssuanceCreditInput{ AccountID: outputAccount.AccountID, @@ -554,10 +610,9 @@ func (w *Wallet) TransitionFoundry(transactionName string, inputName string, acc return signedTransaction } -func (w *Wallet) AllotManaFromBasicOutput(transactionName string, inputName string, accountIDs ...iotago.AccountID) *iotago.SignedTransaction { - input := w.OutputData(inputName) +func (w *Wallet) AllotManaFromBasicOutput(transactionName string, input *OutputData, accountIDs ...iotago.AccountID) *iotago.SignedTransaction { if _, isBasic := input.Output.(*iotago.BasicOutput); !isBasic { - panic(fmt.Sprintf("output with alias %s is not *iotago.BasicOutput", inputName)) + panic("input is not *iotago.BasicOutput") } output := &iotago.BasicOutput{ Amount: input.Output.BaseTokenAmount(), @@ -1012,9 +1067,7 @@ func (w *Wallet) AllotManaToWallet(transactionName string, inputName string, rec return signedTransaction } -func (w *Wallet) CreateNFTFromInput(transactionName string, inputName string, opts ...options.Option[builder.NFTOutputBuilder]) *iotago.SignedTransaction { - input := w.OutputData(inputName) - +func (w *Wallet) CreateNFTFromInput(transactionName string, input *OutputData, opts ...options.Option[builder.NFTOutputBuilder]) *iotago.SignedTransaction { nftOutputBuilder := builder.NewNFTOutputBuilder(w.Address(), input.Output.BaseTokenAmount()) options.Apply(nftOutputBuilder, opts) nftOutput := nftOutputBuilder.MustBuild() @@ -1137,14 +1190,28 @@ func (w *Wallet) registerOutputs(transactionName string, transaction *iotago.Tra clonedOutput := output.Clone() actualOutputID := iotago.OutputIDFromTransactionIDAndIndex(transaction.MustID(), outputID.Index()) if clonedOutput.Type() == iotago.OutputAccount { - if accountOutput, ok := clonedOutput.(*iotago.AccountOutput); ok && accountOutput.AccountID == iotago.EmptyAccountID { + accountOutput, ok := clonedOutput.(*iotago.AccountOutput) + if ok && accountOutput.AccountID == iotago.EmptyAccountID { accountOutput.AccountID = iotago.AccountIDFromOutputID(actualOutputID) } + //nolint:forcetypeassert + w.accounts[accountOutput.AccountID] = &AccountData{ + ID: accountOutput.AccountID, + Address: accountOutput.AccountID.ToAddress().(*iotago.AccountAddress), + AddressIndex: index, + Output: clonedOutput.(*iotago.AccountOutput), + OutputID: actualOutputID, + } } + // register the output by both name and ID w.outputs[fmt.Sprintf("%s:%d", transactionName, outputID.Index())] = &OutputData{ ID: actualOutputID, Output: clonedOutput, } + w.outputsByID[actualOutputID] = &OutputData{ + ID: actualOutputID, + Output: clonedOutput, + } break } @@ -1152,3 +1219,24 @@ func (w *Wallet) registerOutputs(transactionName string, transaction *iotago.Tra } } + +func (w *Wallet) CreateBasicOutputFromInput(input *OutputData, issuerAccountID iotago.AccountID) *iotago.SignedTransaction { + currentSlot := w.CurrentSlot() + apiForSlot := w.Client.APIForSlot(currentSlot) + ed25519Addr := w.Address() + basicOutput := builder.NewBasicOutputBuilder(ed25519Addr, input.Output.BaseTokenAmount()).MustBuild() + signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex)). + AddInput(&builder.TxInput{ + UnlockTarget: input.Address, + InputID: input.ID, + Input: input.Output, + }). + AddOutput(basicOutput). + SetCreationSlot(currentSlot). + AllotAllMana(currentSlot, issuerAccountID, 0). + AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("basic")}). + Build() + require.NoError(w.Testing, err) + + return signedTx +} diff --git a/pkg/testsuite/workscore_regression_test.go b/pkg/testsuite/workscore_regression_test.go index 3f8fbd216..d57647427 100644 --- a/pkg/testsuite/workscore_regression_test.go +++ b/pkg/testsuite/workscore_regression_test.go @@ -320,9 +320,9 @@ func basicInNativeOut(t *testing.T, nNative int) (float64, []float64) { for i := 0; i < nNative-1; i++ { addressIndexes = append(addressIndexes, uint32(i)) } - tx1 := ts.DefaultWallet().CreateFoundryAndNativeTokensFromInput( + tx1 := ts.DefaultWallet().CreateFoundryAndNativeTokensOnOutputsFromInput( "tx1", - "Genesis:0", + ts.DefaultWallet().OutputData("Genesis:0"), "Genesis:2", addressIndexes..., ) @@ -353,9 +353,9 @@ func nativeInNativeOut(t *testing.T) (float64, []float64) { fn := func(b *testing.B) { for i := 0; i < b.N; i++ { ts, node := initializeTestSuite(b, t, blockScheduled) - tx1 := ts.DefaultWallet().CreateFoundryAndNativeTokensFromInput( + tx1 := ts.DefaultWallet().CreateFoundryAndNativeTokensOnOutputsFromInput( "tx1", - "Genesis:0", + ts.DefaultWallet().OutputData("Genesis:0"), "Genesis:2", ) commitment := node.Protocol.Chains.Main.Get().LatestCommitment.Get().Commitment.Commitment() @@ -365,10 +365,12 @@ func nativeInNativeOut(t *testing.T) (float64, []float64) { node.Protocol.IssueBlock(modelBlock) <-blockScheduled + foundryInput := ts.DefaultWallet().OutputData("tx1:0") + accountInput := ts.DefaultWallet().OutputData("tx1:1") tx2 := ts.DefaultWallet().TransitionFoundry( "tx2", - "tx1:0", - "tx1:1", + foundryInput, + accountInput, ) commitment = node.Protocol.Chains.Main.Get().LatestCommitment.Get().Commitment.Commitment() block2 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block2", ts.DefaultWallet(), tx2, mock.WithSlotCommitment(commitment))) @@ -414,7 +416,7 @@ func allotments(t *testing.T, numAllotments int) (float64, []float64) { } tx1 := ts.DefaultWallet().AllotManaFromBasicOutput( "tx1", - "Genesis:0", + ts.DefaultWallet().OutputData("Genesis:0"), accountIDs..., ) commitment := node.Protocol.Chains.Main.Get().LatestCommitment.Get().Commitment.Commitment() diff --git a/tools/docker-network/tests/accounttransition_test.go b/tools/docker-network/tests/accounttransition_test.go index abf4c777f..d13ad2867 100644 --- a/tools/docker-network/tests/accounttransition_test.go +++ b/tools/docker-network/tests/accounttransition_test.go @@ -40,17 +40,17 @@ func Test_AccountTransitions(t *testing.T) { // create account1 fmt.Println("Creating account1") - account1 := d.CreateAccount() + wallet1, _ := d.CreateAccount() // create account2 fmt.Println("Creating account2") - account2 := d.CreateAccount() + _, account2 := d.CreateAccount() // allot 1000 mana from account1 to account2 fmt.Println("Allotting mana from account1 to account2") - d.AllotManaTo(account1.ID, account2.ID, 1000) + d.AllotManaTo(wallet1, account2.ID, 1000) // create native token fmt.Println("Creating native token") - d.CreateNativeToken(account2.ID, 5_000_000, 10_000_000_000) + d.CreateNativeToken(wallet1, 5_000_000, 10_000_000_000) } diff --git a/tools/docker-network/tests/committeerotation_test.go b/tools/docker-network/tests/committeerotation_test.go index cd3f40951..6fa812138 100644 --- a/tools/docker-network/tests/committeerotation_test.go +++ b/tools/docker-network/tests/committeerotation_test.go @@ -43,7 +43,7 @@ func Test_SmallerCommittee(t *testing.T) { status := d.NodeStatus("V1") - clt := d.wallet.Client + clt := d.defaultWallet.Client currentEpoch := clt.CommittedAPI().TimeProvider().EpochFromSlot(status.LatestAcceptedBlockSlot) // stop inx-validator plugin of validator 2 @@ -90,7 +90,7 @@ func Test_ReuseDueToNoFinalization(t *testing.T) { err = d.StopContainer(d.Node("V2").ContainerName, d.Node("V3").ContainerName) require.NoError(t, err) - clt := d.wallet.Client + clt := d.defaultWallet.Client status := d.NodeStatus("V1") prevFinalizedSlot := status.LatestFinalizedSlot @@ -155,7 +155,7 @@ func Test_NoCandidacyPayload(t *testing.T) { d.WaitUntilNetworkReady() - clt := d.wallet.Client + clt := d.defaultWallet.Client status := d.NodeStatus("V1") prevFinalizedSlot := status.LatestFinalizedSlot fmt.Println("First finalized slot: ", prevFinalizedSlot) @@ -205,7 +205,7 @@ func Test_Staking(t *testing.T) { d.WaitUntilNetworkReady() - account := d.CreateAccount(WithStakingFeature(100, 1, 0)) + _, account := d.CreateAccount(WithStakingFeature(100, 1, 0)) d.AssertValidatorExists(account.Address) } @@ -242,13 +242,13 @@ func Test_Delegation(t *testing.T) { d.WaitUntilNetworkReady() // create an account to perform delegation - account := d.CreateAccount() + wallet, _ := d.CreateAccount() // delegate all faucet funds to V2, V2 should replace V3 - _, delegationOutput := d.DelegateToValidator(account.ID, d.Node("V2").AccountAddress(t)) + _, delegationOutput := d.DelegateToValidator(wallet, d.Node("V2").AccountAddress(t)) d.AssertCommittee(delegationOutput.StartEpoch+1, d.AccountsFromNodes(d.Nodes("V1", "V2", "V4")...)) // delegate all faucet funds to V3, V3 should replace V1 - _, delegationOutput = d.DelegateToValidator(account.ID, d.Node("V3").AccountAddress(t)) + _, delegationOutput = d.DelegateToValidator(wallet, d.Node("V3").AccountAddress(t)) d.AssertCommittee(delegationOutput.StartEpoch+1, d.AccountsFromNodes(d.Nodes("V2", "V3", "V4")...)) } diff --git a/tools/docker-network/tests/coreapi.go b/tools/docker-network/tests/coreapi.go index 0ad614c9b..44bfa1ca5 100644 --- a/tools/docker-network/tests/coreapi.go +++ b/tools/docker-network/tests/coreapi.go @@ -11,6 +11,7 @@ import ( "github.com/iotaledger/hive.go/ds/types" "github.com/iotaledger/hive.go/lo" + "github.com/iotaledger/iota-core/pkg/testsuite/mock" iotago "github.com/iotaledger/iota.go/v4" "github.com/iotaledger/iota.go/v4/api" ) @@ -201,12 +202,12 @@ func (d *DockerTestFramework) prepareAssets(totalAssetsNum int) (coreAPIAssets, for i := 0; i < totalAssetsNum; i++ { // account - account := d.CreateAccount() + wallet, account := d.CreateAccount() assets.setupAssetsForSlot(account.OutputID.Slot()) assets[account.OutputID.Slot()].accountAddress = account.Address // data block - block := d.CreateTaggedDataBlock(account.ID, []byte("tag")) + block := d.CreateTaggedDataBlock(wallet, []byte("tag")) blockSlot := lo.PanicOnErr(block.ID()).Slot() assets.setupAssetsForSlot(blockSlot) assets[blockSlot].dataBlocks = append(assets[blockSlot].dataBlocks, block) @@ -226,16 +227,16 @@ func (d *DockerTestFramework) prepareAssets(totalAssetsNum int) (coreAPIAssets, d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) // issue reattachment after the fisrt one is already included - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, d.wallet.Client, account.Address) - secondAttachment := d.SubmitPayload(ctx, signedTx, account.Address.AccountID(), congestionResp, issuerResp) - assets[valueBlockSlot].reattachments = append(assets[valueBlockSlot].reattachments, secondAttachment) + secondAttachment, err := wallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + require.NoError(d.Testing, err) + assets[valueBlockSlot].reattachments = append(assets[valueBlockSlot].reattachments, secondAttachment.ID()) // delegation - delegationOutputID, delegationOutput := d.DelegateToValidator(account.ID, d.Node("V1").AccountAddress(d.Testing)) + delegationOutputID, delegationOutput := d.DelegateToValidator(wallet, d.Node("V1").AccountAddress(d.Testing)) assets.setupAssetsForSlot(delegationOutputID.CreationSlot()) assets[delegationOutputID.CreationSlot()].delegationOutputs[delegationOutputID] = delegationOutput - latestSlot = lo.Max[iotago.SlotIndex](latestSlot, blockSlot, valueBlockSlot, delegationOutputID.CreationSlot(), secondAttachment.Slot()) + latestSlot = lo.Max[iotago.SlotIndex](latestSlot, blockSlot, valueBlockSlot, delegationOutputID.CreationSlot(), secondAttachment.ID().Slot()) fmt.Printf("Assets for slot %d\n: dataBlock: %s block: %s\ntx: %s\nbasic output: %s, faucet output: %s\n delegation output: %s\n", valueBlockSlot, block.MustID().String(), valueBlock.MustID().String(), lo.PanicOnErr(signedTx.ID()).String(), diff --git a/tools/docker-network/tests/coreapi_test.go b/tools/docker-network/tests/coreapi_test.go index 646c7b7c1..4dad462e1 100644 --- a/tools/docker-network/tests/coreapi_test.go +++ b/tools/docker-network/tests/coreapi_test.go @@ -45,11 +45,11 @@ func Test_ValidatorsAPI(t *testing.T) { require.NoError(t, runErr) d.WaitUntilNetworkReady() - hrp := d.wallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP() + hrp := d.defaultWallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP() // Create registered validators var wg sync.WaitGroup - clt := d.wallet.Client + clt := d.defaultWallet.Client status := d.NodeStatus("V1") currentEpoch := clt.CommittedAPI().TimeProvider().EpochFromSlot(status.LatestAcceptedBlockSlot) @@ -58,11 +58,11 @@ func Test_ValidatorsAPI(t *testing.T) { go func() { defer wg.Done() - account := d.CreateAccount(WithStakingFeature(100, 1, 0)) + wallet, _ := d.CreateAccount(WithStakingFeature(100, 1, 0)) // issue candidacy payload in the next epoch (currentEpoch + 1), in order to issue it before epochNearingThreshold d.AwaitCommitment(clt.CommittedAPI().TimeProvider().EpochEnd(currentEpoch)) - blkID := d.IssueCandidacyPayloadFromAccount(account.ID) + blkID := d.IssueCandidacyPayloadFromAccount(wallet) fmt.Println("Candidacy payload:", blkID.ToHex(), blkID.Slot()) d.AwaitCommitment(blkID.Slot()) }() @@ -70,7 +70,7 @@ func Test_ValidatorsAPI(t *testing.T) { wg.Wait() expectedValidators := d.AccountsFromNodes(d.Nodes()...) - for _, v := range d.wallet.Accounts() { + for _, v := range d.defaultWallet.Accounts() { expectedValidators = append(expectedValidators, v.Address.Bech32(hrp)) } // get all validators of currentEpoch+1 with pageSize 10 diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index dbd13fe99..40488c4b9 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -76,7 +76,7 @@ type DockerTestFramework struct { snapshotPath string logDirectoryPath string - wallet *DockerWallet + defaultWallet *mock.Wallet optsProtocolParameterOptions []options.Option[iotago.V3ProtocolParameters] optsSnapshotOptions []options.Option[snapshotcreator.Options] @@ -91,7 +91,6 @@ func NewDockerTestFramework(t *testing.T, opts ...options.Option[DockerTestFrame Testing: t, nodes: make(map[string]*Node), clients: make(map[string]mock.Client), - wallet: NewDockerWallet(t), optsWaitForSync: 5 * time.Minute, optsWaitFor: 2 * time.Minute, optsTick: 5 * time.Second, @@ -206,7 +205,12 @@ func (d *DockerTestFramework) waitForNodesAndGetClients() error { d.nodes[node.Name] = node d.clients[node.Name] = client } - d.wallet.Client = d.clients["V1"] + d.defaultWallet = mock.NewWallet( + d.Testing, + "default", + d.clients["V1"], + lo.PanicOnErr(wallet.NewKeyManagerFromRandom(wallet.DefaultIOTAPath)), + ) return nil } @@ -396,114 +400,89 @@ func (d *DockerTestFramework) StopIssueCandidacyPayload(nodes ...*Node) { require.NoError(d.Testing, err) } -func (d *DockerTestFramework) IssueCandidacyPayloadFromAccount(issuerId iotago.AccountID) iotago.BlockID { - issuer := d.wallet.Account(issuerId) - ctx := context.TODO() - clt := d.wallet.Client - - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) +func (d *DockerTestFramework) IssueCandidacyPayloadFromAccount(wallet *mock.Wallet) iotago.BlockID { + block, err := wallet.IssueBasicBlock(context.TODO(), "", mock.WithPayload(&iotago.CandidacyAnnouncement{})) + require.NoError(d.Testing, err) - return d.SubmitPayload(ctx, &iotago.CandidacyAnnouncement{}, issuerId, congestionResp, issuerResp) + return block.ID() } // CreateTaggedDataBlock creates a block of a tagged data payload. -func (d *DockerTestFramework) CreateTaggedDataBlock(issuerID iotago.AccountID, tag []byte) *iotago.Block { - issuer := d.wallet.Account(issuerID) +func (d *DockerTestFramework) CreateTaggedDataBlock(wallet *mock.Wallet, tag []byte) *iotago.Block { ctx := context.TODO() - clt := d.wallet.Client - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) - - return d.CreateBlock(&iotago.TaggedData{ + return lo.PanicOnErr(wallet.IssueBasicBlock(ctx, "", mock.WithPayload(&iotago.TaggedData{ Tag: tag, - }, issuerID, congestionResp, issuerResp) + }))).ProtocolBlock() } func (d *DockerTestFramework) CreateBasicOutputBlock(issuerAccountID iotago.AccountID) (*iotago.Block, *iotago.SignedTransaction, *mock.OutputData) { - clt := d.wallet.Client ctx := context.Background() - fundsOutputID := d.RequestFaucetFunds(ctx, iotago.AddressEd25519) - - input := d.wallet.Output(fundsOutputID) - signedTx := d.wallet.CreateBasicOutputFromInput(input, issuerAccountID) + fundsOutputData := d.RequestFaucetFunds(ctx, d.defaultWallet, iotago.AddressEd25519) - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuerAccountID.ToAddress().(*iotago.AccountAddress)) - block := d.CreateBlock(signedTx, issuerAccountID, congestionResp, issuerResp) + signedTx := d.defaultWallet.CreateBasicOutputFromInput(fundsOutputData, issuerAccountID) + block := lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() - return block, signedTx, input + return block, signedTx, fundsOutputData } // CreateDelegationBlockFromInput consumes the given basic output, then build a block of a transaction that includes a delegation output, in order to delegate the given validator. -func (d *DockerTestFramework) CreateDelegationBlockFromInput(issuerID iotago.AccountID, accountAdddress *iotago.AccountAddress, inputID iotago.OutputID) (iotago.DelegationID, iotago.OutputID, *iotago.Block) { - issuer := d.wallet.Account(issuerID) +func (d *DockerTestFramework) CreateDelegationBlockFromInput(issuerID iotago.AccountID, accountAdddress *iotago.AccountAddress, input *mock.OutputData) (iotago.DelegationID, iotago.OutputID, *iotago.Block) { ctx := context.TODO() - clt := d.wallet.Client - - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) - - signedTx := d.wallet.CreateDelegationFromInput(issuerID, accountAdddress, inputID, issuerResp) + clt := d.defaultWallet.Client + + signedTx := d.defaultWallet.CreateDelegationFromInput( + "", + input, + mock.WithDelegatedValidatorAddress(accountAdddress), + mock.WithDelegationStartEpoch(getDelegationStartEpoch(clt.LatestAPI(), d.defaultWallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot)), + ) outputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) return iotago.DelegationIDFromOutputID(outputID), outputID, - d.CreateBlock(signedTx, issuerID, congestionResp, issuerResp) + lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateFoundryBlockFromInput consumes the given basic output, then build a block of a transaction that includes a foundry output with the given mintedAmount and maxSupply. -func (d *DockerTestFramework) CreateFoundryBlockFromInput(issuerID iotago.AccountID, inputID iotago.OutputID, mintedAmount iotago.BaseToken, maxSupply iotago.BaseToken) (iotago.FoundryID, iotago.OutputID, *iotago.Block) { - issuer := d.wallet.Account(issuerID) - ctx := context.TODO() - clt := d.wallet.Client - - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) - signedTx := d.wallet.CreateFoundryAndNativeTokensFromInput(issuerID, inputID, mintedAmount, maxSupply, issuerResp) +func (d *DockerTestFramework) CreateFoundryBlockFromInput(wallet *mock.Wallet, inputID iotago.OutputID, mintedAmount iotago.BaseToken, maxSupply iotago.BaseToken) (iotago.FoundryID, iotago.OutputID, *iotago.Block) { + input := wallet.Output(inputID) + signedTx := wallet.CreateFoundryAndNativeTokensFromInput(input, mintedAmount, maxSupply) txID, err := signedTx.Transaction.ID() require.NoError(d.Testing, err) //nolint:forcetypeassert return signedTx.Transaction.Outputs[1].(*iotago.FoundryOutput).MustFoundryID(), iotago.OutputIDFromTransactionIDAndIndex(txID, 1), - d.CreateBlock(signedTx, issuerID, congestionResp, issuerResp) + lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateNFTBlockFromInput consumes the given basic output, then build a block of a transaction that includes a NFT output with the given NFT output options. -func (d *DockerTestFramework) CreateNFTBlockFromInput(issuerID iotago.AccountID, inputID iotago.OutputID, opts ...options.Option[builder.NFTOutputBuilder]) (iotago.NFTID, iotago.OutputID, *iotago.Block) { - issuer := d.wallet.Account(issuerID) - ctx := context.TODO() - clt := d.wallet.Client - - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) - signedTx := d.wallet.CreateNFTFromInput(issuerID, inputID, issuerResp, opts...) +func (d *DockerTestFramework) CreateNFTBlockFromInput(wallet *mock.Wallet, input *mock.OutputData, opts ...options.Option[builder.NFTOutputBuilder]) (iotago.NFTID, iotago.OutputID, *iotago.Block) { + signedTx := wallet.CreateNFTFromInput("", input, opts...) outputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) return iotago.NFTIDFromOutputID(outputID), outputID, - d.CreateBlock(signedTx, issuerID, congestionResp, issuerResp) + lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateFoundryTransitionBlockFromInput consumes the given foundry output, then build block by increasing the minted amount by 1. -func (d *DockerTestFramework) CreateFoundryTransitionBlockFromInput(issuerID iotago.AccountID, inputID iotago.OutputID) (iotago.FoundryID, iotago.OutputID, *iotago.Block) { - ctx := context.TODO() - clt := d.wallet.Client - issuer := d.wallet.Account(issuerID) - - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, issuer.Address) - signedTx := d.wallet.TransitionFoundry(issuerID, inputID, issuerResp) +func (d *DockerTestFramework) CreateFoundryTransitionBlockFromInput(issuerID iotago.AccountID, foundryInput, accountInput *mock.OutputData) (iotago.FoundryID, iotago.OutputID, *iotago.Block) { + signedTx := d.defaultWallet.TransitionFoundry("", foundryInput, accountInput) txID, err := signedTx.Transaction.ID() require.NoError(d.Testing, err) //nolint:forcetypeassert return signedTx.Transaction.Outputs[1].(*iotago.FoundryOutput).MustFoundryID(), iotago.OutputIDFromTransactionIDAndIndex(txID, 1), - d.CreateBlock(signedTx, issuerID, congestionResp, issuerResp) + lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateAccountBlockFromInput consumes the given output, which should be either an basic output with implicit address, then build block with the given account output options. Note that after the returned transaction is issued, remember to update the account information in the wallet with AddAccount(). -func (d *DockerTestFramework) CreateAccountBlockFromInput(inputID iotago.OutputID) (*mock.AccountData, iotago.OutputID, *iotago.Block) { - ctx := context.TODO() - clt := d.wallet.Client - input := d.wallet.Output(inputID) +func (d *DockerTestFramework) CreateAccountBlockFromInput(wallet *mock.Wallet, inputID iotago.OutputID) (*mock.AccountData, iotago.OutputID, *iotago.Block) { + input := wallet.Output(inputID) // check if the given input is an BasicOutput with implicit address implicitOutput, ok := input.Output.(*iotago.BasicOutput) @@ -511,77 +490,80 @@ func (d *DockerTestFramework) CreateAccountBlockFromInput(inputID iotago.OutputI require.Equal(d.Testing, iotago.AddressImplicitAccountCreation, implicitOutput.UnlockConditionSet().Address().Address.Type()) accAddress := iotago.AccountAddressFromOutputID(inputID) - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, accAddress) - fullAccount, signedTx := d.wallet.TransitionImplicitAccountToAccountOutput(input.ID, issuerResp) + signedTx := wallet.TransitionImplicitAccountToAccountOutput( + "", + []*mock.OutputData{input}, + ) txID, err := signedTx.Transaction.ID() require.NoError(d.Testing, err) + accountOutput := signedTx.Transaction.Outputs[0].(*iotago.AccountOutput) + fullAccount := &mock.AccountData{ + ID: accountOutput.AccountID, + Address: accAddress, + AddressIndex: wallet.Output(inputID).AddressIndex, + Output: accountOutput, + OutputID: iotago.OutputIDFromTransactionIDAndIndex(txID, 0), + } + return fullAccount, iotago.OutputIDFromTransactionIDAndIndex(txID, 0), - d.CreateBlock(signedTx, fullAccount.ID, congestionResp, issuerResp) + lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateImplicitAccount requests faucet funds and creates an implicit account. It already wait until the transaction is committed and the created account is useable. -func (d *DockerTestFramework) CreateImplicitAccount(ctx context.Context) *mock.AccountData { - fundsOutputID := d.RequestFaucetFunds(ctx, iotago.AddressImplicitAccountCreation) +func (d *DockerTestFramework) CreateImplicitAccount(ctx context.Context) (*mock.Wallet, *mock.OutputData) { + newWallet := mock.NewWallet(d.Testing, "", d.defaultWallet.Client) + implicitAccountOutputData := d.RequestFaucetFunds(ctx, newWallet, iotago.AddressImplicitAccountCreation) - accountID := iotago.AccountIDFromOutputID(fundsOutputID) + accountID := iotago.AccountIDFromOutputID(implicitAccountOutputData.ID) accountAddress, ok := accountID.ToAddress().(*iotago.AccountAddress) require.True(d.Testing, ok) - // Note: the implicit account output is not an AccountOutput, thus we ignore the Output here. - accountInfo := &mock.AccountData{ - ID: accountID, - Address: accountAddress, - AddressIndex: d.wallet.Output(fundsOutputID).AddressIndex, - OutputID: fundsOutputID, - } - d.wallet.AddAccount(accountID, accountInfo) - // make sure an implicit account is committed - d.CheckAccountStatus(ctx, iotago.EmptyBlockID, fundsOutputID.TransactionID(), fundsOutputID, accountAddress) + d.CheckAccountStatus(ctx, iotago.EmptyBlockID, implicitAccountOutputData.ID.TransactionID(), implicitAccountOutputData.ID, accountAddress) - return accountInfo + return newWallet, implicitAccountOutputData } // CreateAccount creates an new account from implicit one to full one, it already wait until the transaction is committed and the created account is useable. -func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.AccountOutputBuilder]) *mock.AccountData { +func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.AccountOutputBuilder]) (*mock.Wallet, *mock.AccountData) { // create an implicit account by requesting faucet funds ctx := context.TODO() - implicitAccount := d.CreateImplicitAccount(ctx) - clt := d.wallet.Client + newWallet, implicitAccountOutputData := d.CreateImplicitAccount(ctx) + clt := d.defaultWallet.Client - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, implicitAccount.Address) - fullAccount, signedTx := d.wallet.TransitionImplicitAccountToAccountOutput(implicitAccount.OutputID, issuerResp, opts...) + signedTx := newWallet.TransitionImplicitAccountToAccountOutput("", []*mock.OutputData{implicitAccountOutputData}, opts...) // The account transition block should be issued by the implicit account block issuer key. - blkID := d.SubmitPayload(ctx, signedTx, fullAccount.ID, congestionResp, issuerResp) + block, err := newWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + require.NoError(d.Testing, err) // check if the account is committed accOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) - d.CheckAccountStatus(ctx, blkID, signedTx.Transaction.MustID(), accOutputID, fullAccount.Address, true) + accOutput := signedTx.Transaction.Outputs[0].(*iotago.AccountOutput) + accAddress := (accOutput.AccountID).ToAddress().(*iotago.AccountAddress) + d.CheckAccountStatus(ctx, block.ID(), signedTx.Transaction.MustID(), accOutputID, accAddress, true) - // update account info after it's transitioned to full account - d.wallet.AddAccount(fullAccount.ID, fullAccount) + fmt.Printf("Account created, Bech addr: %s, in txID: %s, slot: %d\n", accAddress.Bech32(clt.CommittedAPI().ProtocolParameters().Bech32HRP()), signedTx.Transaction.MustID().ToHex(), block.ID().Slot()) - fmt.Printf("Account created, Bech addr: %s, in txID: %s, slot: %d\n", fullAccount.Address.Bech32(clt.CommittedAPI().ProtocolParameters().Bech32HRP()), signedTx.Transaction.MustID().ToHex(), blkID.Slot()) - - return fullAccount + return newWallet, newWallet.Account(accOutput.AccountID) } // DelegateToValidator requests faucet funds and delegate the UTXO output to the validator. -func (d *DockerTestFramework) DelegateToValidator(fromID iotago.AccountID, accountAddress *iotago.AccountAddress) (iotago.OutputID, *iotago.DelegationOutput) { - from := d.wallet.Account(fromID) - clt := d.wallet.Client - +func (d *DockerTestFramework) DelegateToValidator(fromWallet *mock.Wallet, accountAddress *iotago.AccountAddress) (iotago.OutputID, *iotago.DelegationOutput) { // requesting faucet funds as delegation input ctx := context.TODO() - fundsOutputID := d.RequestFaucetFunds(ctx, iotago.AddressEd25519) + fundsOutputData := d.RequestFaucetFunds(ctx, fromWallet, iotago.AddressEd25519) - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, from.Address) - signedTx := d.wallet.CreateDelegationFromInput(fromID, accountAddress, fundsOutputID, issuerResp) + signedTx := fromWallet.CreateDelegationFromInput( + "", + fundsOutputData, + mock.WithDelegatedValidatorAddress(accountAddress), + mock.WithDelegationStartEpoch(getDelegationStartEpoch(fromWallet.Client.LatestAPI(), fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot)), + ) - d.SubmitPayload(ctx, signedTx, from.ID, congestionResp, issuerResp) + d.defaultWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) delegationOutput, ok := signedTx.Transaction.Outputs[0].(*iotago.DelegationOutput) @@ -604,27 +586,30 @@ func (d *DockerTestFramework) PrepareBlockIssuance(ctx context.Context, clt mock } // AllotManaTo requests faucet funds then uses it to allots mana from one account to another. -func (d *DockerTestFramework) AllotManaTo(fromID iotago.AccountID, toID iotago.AccountID, manaToAllot iotago.Mana) { - from := d.wallet.Account(fromID) - to := d.wallet.Account(toID) +func (d *DockerTestFramework) AllotManaTo(fromWallet *mock.Wallet, toID iotago.AccountID, manaToAllot iotago.Mana) { + to := d.defaultWallet.Account(toID) // requesting faucet funds for allotment ctx := context.TODO() - fundsOutputID := d.RequestFaucetFunds(ctx, iotago.AddressEd25519) - clt := d.wallet.Client + fundsOutputID := d.RequestFaucetFunds(ctx, fromWallet, iotago.AddressEd25519) + clt := fromWallet.Client - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, from.Address) - signedTx := d.wallet.AllotManaFromAccount(fromID, toID, manaToAllot, fundsOutputID) - blkID := d.SubmitPayload(ctx, signedTx, from.ID, congestionResp, issuerResp) + signedTx := fromWallet.AllotManaFromBasicOutput( + "", + fundsOutputID, + toID, + ) - fmt.Println("Allot mana transaction sent, blkID:", blkID.ToHex(), ", txID:", signedTx.Transaction.MustID().ToHex(), ", slot:", blkID.Slot()) + block, err := fromWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + require.NoError(d.Testing, err) + fmt.Println("Allot mana transaction sent, blkID:", block.ID().ToHex(), ", txID:", signedTx.Transaction.MustID().ToHex(), ", slot:", block.ID().Slot()) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) // allotment is updated until the transaction is committed - d.AwaitCommitment(blkID.Slot()) + d.AwaitCommitment(block.ID().Slot()) // check if the mana is allotted - toCongestionResp, err := clt.Congestion(ctx, to.Address, 0, lo.PanicOnErr(issuerResp.LatestCommitment.ID())) + toCongestionResp, err := clt.Congestion(ctx, to.Address, 0, lo.PanicOnErr(fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.ID())) require.NoError(d.Testing, err) oldBIC := toCongestionResp.BlockIssuanceCredits @@ -635,60 +620,57 @@ func (d *DockerTestFramework) AllotManaTo(fromID iotago.AccountID, toID iotago.A } // CreateNativeToken request faucet funds then use it to create native token for the account, and returns the updated Account. -func (d *DockerTestFramework) CreateNativeToken(fromID iotago.AccountID, mintedAmount iotago.BaseToken, maxSupply iotago.BaseToken) { +func (d *DockerTestFramework) CreateNativeToken(fromWallet *mock.Wallet, mintedAmount iotago.BaseToken, maxSupply iotago.BaseToken) { require.GreaterOrEqual(d.Testing, maxSupply, mintedAmount) ctx := context.TODO() - clt := d.wallet.Client - from := d.wallet.Account(fromID) // requesting faucet funds for native token creation - fundsOutputID := d.RequestFaucetFunds(ctx, iotago.AddressEd25519) + fundsOutputData := d.RequestFaucetFunds(ctx, d.defaultWallet, iotago.AddressEd25519) - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, clt, from.Address) - signedTx := d.wallet.CreateFoundryAndNativeTokensFromInput(fromID, fundsOutputID, mintedAmount, maxSupply, issuerResp) + signedTx := d.defaultWallet.CreateFoundryAndNativeTokensFromInput(fundsOutputData, mintedAmount, maxSupply) - blkID := d.SubmitPayload(ctx, signedTx, from.ID, congestionResp, issuerResp) + block, err := fromWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + require.NoError(d.Testing, err) txID := signedTx.Transaction.MustID() d.AwaitTransactionPayloadAccepted(ctx, txID) - fmt.Println("Create native tokens transaction sent, blkID:", blkID.ToHex(), ", txID:", signedTx.Transaction.MustID().ToHex(), ", slot:", blkID.Slot()) + fmt.Println("Create native tokens transaction sent, blkID:", block.ID().ToHex(), ", txID:", signedTx.Transaction.MustID().ToHex(), ", slot:", block.ID().Slot()) // wait for the account to be committed - d.AwaitCommitment(blkID.Slot()) + d.AwaitCommitment(block.ID().Slot()) - from = d.wallet.Account(fromID) - d.AssertIndexerAccount(from) + d.AssertIndexerAccount(fromWallet.BlockIssuer.AccountData) //nolint:forcetypeassert d.AssertIndexerFoundry(signedTx.Transaction.Outputs[1].(*iotago.FoundryOutput).MustFoundryID()) } // RequestFaucetFunds requests faucet funds for the given address type, and returns the outputID of the received funds. -func (d *DockerTestFramework) RequestFaucetFunds(ctx context.Context, addressType iotago.AddressType) iotago.OutputID { +func (d *DockerTestFramework) RequestFaucetFunds(ctx context.Context, wallet *mock.Wallet, addressType iotago.AddressType) *mock.OutputData { var address iotago.Address - var addrIndex uint32 if addressType == iotago.AddressImplicitAccountCreation { - addrIndex, address = d.wallet.ImplicitAccountCreationAddress() + address = wallet.ImplicitAccountCreationAddress(wallet.BlockIssuer.AccountData.AddressIndex) } else { - addrIndex, address = d.wallet.Address() + address = wallet.Address() } - d.SendFaucetRequest(ctx, address) + d.SendFaucetRequest(ctx, wallet, address) - outputID, output, err := d.AwaitAddressUnspentOutputAccepted(ctx, address) + outputID, output, err := d.AwaitAddressUnspentOutputAccepted(ctx, wallet, address) require.NoError(d.Testing, err) - d.wallet.AddOutput(outputID, &mock.OutputData{ + outputData := &mock.OutputData{ ID: outputID, Address: address, - AddressIndex: addrIndex, + AddressIndex: wallet.BlockIssuer.AccountData.AddressIndex, Output: output, - }) + } + wallet.AddOutput("", outputData) fmt.Printf("Faucet funds received, txID: %s, amount: %d, mana: %d\n", outputID.TransactionID().ToHex(), output.BaseTokenAmount(), output.StoredMana()) - return outputID + return outputData } func (d *DockerTestFramework) Stop() { @@ -771,47 +753,9 @@ func (d *DockerTestFramework) GetContainersConfigs() { } } -func (d *DockerTestFramework) CreateBlock(payload iotago.Payload, issuerID iotago.AccountID, congestionResp *api.CongestionResponse, issuerResp *api.IssuanceBlockHeaderResponse) *iotago.Block { - clt := d.wallet.Client - issuingTime := time.Now() - apiForSlot := clt.APIForSlot(clt.LatestAPI().TimeProvider().SlotFromTime(issuingTime)) - blockBuilder := builder.NewBasicBlockBuilder(apiForSlot) - issuer := d.wallet.Account(issuerID) - - commitmentID, err := issuerResp.LatestCommitment.ID() - require.NoError(d.Testing, err) - - blockBuilder.ProtocolVersion(apiForSlot.Version()). - SlotCommitmentID(commitmentID). - LatestFinalizedSlot(issuerResp.LatestFinalizedSlot). - IssuingTime(issuingTime). - StrongParents(issuerResp.StrongParents). - WeakParents(issuerResp.WeakParents). - ShallowLikeParents(issuerResp.ShallowLikeParents). - Payload(payload). - CalculateAndSetMaxBurnedMana(congestionResp.ReferenceManaCost). - Sign(issuerID, lo.Return1(d.wallet.KeyPair(issuer.AddressIndex))) - - blk, err := blockBuilder.Build() - require.NoError(d.Testing, err) - - return blk -} - func (d *DockerTestFramework) SubmitBlock(ctx context.Context, blk *iotago.Block) { - clt := d.wallet.Client + clt := d.defaultWallet.Client _, err := clt.SubmitBlock(ctx, blk) require.NoError(d.Testing, err) } - -func (d *DockerTestFramework) SubmitPayload(ctx context.Context, payload iotago.Payload, issuerID iotago.AccountID, congestionResp *api.CongestionResponse, issuerResp *api.IssuanceBlockHeaderResponse) iotago.BlockID { - clt := d.wallet.Client - - blk := d.CreateBlock(payload, issuerID, congestionResp, issuerResp) - - blkID, err := clt.SubmitBlock(ctx, blk) - require.NoError(d.Testing, err) - - return blkID -} diff --git a/tools/docker-network/tests/eventapi_test.go b/tools/docker-network/tests/eventapi_test.go index 38f4a8abe..553ca1e2d 100644 --- a/tools/docker-network/tests/eventapi_test.go +++ b/tools/docker-network/tests/eventapi_test.go @@ -126,12 +126,12 @@ func test_BasicTaggedDataBlocks(t *testing.T, e *EventAPIDockerTestFramework) { defer eventClt.Close() // create an account to issue blocks - account := e.dockerFramework.CreateAccount() + wallet, _ := e.dockerFramework.CreateAccount() // prepare data blocks to send expectedBlocks := make(map[string]*iotago.Block) for i := 0; i < 10; i++ { - blk := e.dockerFramework.CreateTaggedDataBlock(account.ID, []byte("tag")) + blk := e.dockerFramework.CreateTaggedDataBlock(wallet, []byte("tag")) expectedBlocks[blk.MustID().ToHex()] = blk } @@ -173,15 +173,15 @@ func test_DelegationTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramewo defer eventClt.Close() // create an account to issue blocks - account := e.dockerFramework.CreateAccount() - fundsOutputID := e.dockerFramework.RequestFaucetFunds(ctx, iotago.AddressEd25519) + wallet, account := e.dockerFramework.CreateAccount() + fundsOutputData := e.dockerFramework.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) // prepare data blocks to send - delegationId, outputId, blk := e.dockerFramework.CreateDelegationBlockFromInput(account.ID, e.dockerFramework.Node("V2").AccountAddress(t), fundsOutputID) + delegationId, outputId, blk := e.dockerFramework.CreateDelegationBlockFromInput(account.ID, e.dockerFramework.Node("V2").AccountAddress(t), fundsOutputData) expectedBlocks := map[string]*iotago.Block{ blk.MustID().ToHex(): blk, } - delegationOutput := e.dockerFramework.wallet.Output(outputId) + delegationOutput := e.dockerFramework.defaultWallet.Output(outputId) asserts := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, @@ -231,14 +231,14 @@ func test_AccountTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) // implicit account transition { - implicitAccount := e.dockerFramework.CreateImplicitAccount(ctx) + wallet, implicitAccount := e.dockerFramework.CreateImplicitAccount(ctx) // prepare fullAccount transaction block to send - fullAccount, outputId, blk := e.dockerFramework.CreateAccountBlockFromInput(implicitAccount.OutputID) + fullAccount, outputId, blk := e.dockerFramework.CreateAccountBlockFromInput(wallet, implicitAccount.ID) expectedBlocks := map[string]*iotago.Block{ blk.MustID().ToHex(): blk, } - accountOutput := e.dockerFramework.wallet.Output(outputId) + accountOutput := e.dockerFramework.defaultWallet.Output(outputId) assertions := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, @@ -275,9 +275,6 @@ func test_AccountTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) } }() - // update full account information - e.dockerFramework.wallet.AddAccount(fullAccount.ID, fullAccount) - // wait until all topics receives all expected objects err = e.AwaitEventAPITopics(t, cancel, totalTopics) require.NoError(t, err) @@ -291,15 +288,15 @@ func test_FoundryTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) defer eventClt.Close() { - account := e.dockerFramework.CreateAccount() - fundsOutputID := e.dockerFramework.RequestFaucetFunds(ctx, iotago.AddressEd25519) + wallet, account := e.dockerFramework.CreateAccount() + fundsOutputData := e.dockerFramework.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) // prepare foundry output block - foundryId, outputId, blk := e.dockerFramework.CreateFoundryBlockFromInput(account.ID, fundsOutputID, 5_000_000, 10_000_000_000) + foundryId, outputId, blk := e.dockerFramework.CreateFoundryBlockFromInput(wallet, fundsOutputData.ID, 5_000_000, 10_000_000_000) expectedBlocks := map[string]*iotago.Block{ blk.MustID().ToHex(): blk, } - foundryOutput := e.dockerFramework.wallet.Output(outputId) + foundryOutput := e.dockerFramework.defaultWallet.Output(outputId) assertions := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, @@ -351,15 +348,15 @@ func test_NFTTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) { defer eventClt.Close() { - account := e.dockerFramework.CreateAccount() - fundsOutputID := e.dockerFramework.RequestFaucetFunds(ctx, iotago.AddressEd25519) + wallet, _ := e.dockerFramework.CreateAccount() + fundsOutputID := e.dockerFramework.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) // prepare foundry output block - nftId, outputId, blk := e.dockerFramework.CreateNFTBlockFromInput(account.ID, fundsOutputID) + nftId, outputId, blk := e.dockerFramework.CreateNFTBlockFromInput(wallet, fundsOutputID) expectedBlocks := map[string]*iotago.Block{ blk.MustID().ToHex(): blk, } - nftOutput := e.dockerFramework.wallet.Output(outputId) + nftOutput := e.dockerFramework.defaultWallet.Output(outputId) assertions := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, @@ -409,7 +406,7 @@ func test_BlockMetadataMatchedCoreAPI(t *testing.T, e *EventAPIDockerTestFramewo defer eventClt.Close() { - account := e.dockerFramework.CreateAccount() + wallet, _ := e.dockerFramework.CreateAccount() assertions := []func(){ func() { e.AssertBlockMetadataStateAcceptedBlocks(ctx, eventClt) }, @@ -426,7 +423,7 @@ func test_BlockMetadataMatchedCoreAPI(t *testing.T, e *EventAPIDockerTestFramewo require.NoError(t, err) // issue blocks - e.SubmitDataBlockStream(account, 5*time.Minute) + e.SubmitDataBlockStream(wallet, 5*time.Minute) cancel() } diff --git a/tools/docker-network/tests/eventapiframework.go b/tools/docker-network/tests/eventapiframework.go index 98c808ba8..35bdbbc47 100644 --- a/tools/docker-network/tests/eventapiframework.go +++ b/tools/docker-network/tests/eventapiframework.go @@ -35,7 +35,7 @@ func NewEventAPIDockerTestFramework(t *testing.T, dockerFramework *DockerTestFra return &EventAPIDockerTestFramework{ Testing: t, dockerFramework: dockerFramework, - DefaultClient: dockerFramework.wallet.Client, + DefaultClient: dockerFramework.defaultWallet.Client, finishChan: make(chan struct{}), optsWaitFor: 3 * time.Minute, optsTick: 5 * time.Second, @@ -52,7 +52,7 @@ func (e *EventAPIDockerTestFramework) ConnectEventAPIClient(ctx context.Context) } // SubmitDataBlockStream submits a stream of data blocks to the network for the given duration. -func (e *EventAPIDockerTestFramework) SubmitDataBlockStream(account *mock.AccountData, duration time.Duration) { +func (e *EventAPIDockerTestFramework) SubmitDataBlockStream(wallet *mock.Wallet, duration time.Duration) { timer := time.NewTimer(duration) defer timer.Stop() @@ -63,7 +63,7 @@ func (e *EventAPIDockerTestFramework) SubmitDataBlockStream(account *mock.Accoun select { case <-ticker.C: for i := 0; i < 10; i++ { - blk := e.dockerFramework.CreateTaggedDataBlock(account.ID, []byte("tag")) + blk := e.dockerFramework.CreateTaggedDataBlock(wallet, []byte("tag")) e.dockerFramework.SubmitBlock(context.Background(), blk) } case <-timer.C: diff --git a/tools/docker-network/tests/mempool_invalid_signatures_test.go b/tools/docker-network/tests/mempool_invalid_signatures_test.go index 03422c358..a1801cf64 100644 --- a/tools/docker-network/tests/mempool_invalid_signatures_test.go +++ b/tools/docker-network/tests/mempool_invalid_signatures_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" + "github.com/iotaledger/iota-core/pkg/testsuite/mock" iotago "github.com/iotaledger/iota.go/v4" "github.com/iotaledger/iota.go/v4/api" ) @@ -35,12 +36,11 @@ func Test_MempoolInvalidSignatures(t *testing.T) { d.WaitUntilNetworkReady() - account := d.CreateAccount() + wallet, account := d.CreateAccount() ctx := context.Background() - fundsOutputID := d.RequestFaucetFunds(ctx, iotago.AddressEd25519) - input := d.wallet.Output(fundsOutputID) - validTX := d.wallet.CreateBasicOutputFromInput(input, account.ID) + fundsOutputData := d.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) + validTX := wallet.CreateBasicOutputFromInput(fundsOutputData, account.ID) invalidTX := validTX.Clone().(*iotago.SignedTransaction) // Make validTX invalid by replacing the first unlock with an empty signature unlock. @@ -51,19 +51,16 @@ func Test_MempoolInvalidSignatures(t *testing.T) { } fmt.Println("Submitting block with invalid TX") - issuerResp, congestionResp := d.PrepareBlockIssuance(ctx, d.wallet.Client, account.ID.ToAddress().(*iotago.AccountAddress)) - d.SubmitPayload(context.Background(), invalidTX, account.ID, congestionResp, issuerResp) + wallet.IssueBasicBlock(ctx, "", mock.WithPayload(invalidTX)) d.AwaitTransactionState(ctx, invalidTX.Transaction.MustID(), api.TransactionStateFailed) d.AwaitTransactionFailure(ctx, invalidTX.Transaction.MustID(), api.TxFailureUnlockSignatureInvalid) fmt.Println("Submitting block with valid TX") - issuerResp, congestionResp = d.PrepareBlockIssuance(ctx, d.wallet.Client, account.ID.ToAddress().(*iotago.AccountAddress)) - d.SubmitPayload(context.Background(), validTX, account.ID, congestionResp, issuerResp) + wallet.IssueBasicBlock(ctx, "", mock.WithPayload(validTX)) fmt.Println("Submitting block with invalid TX (again)") - issuerResp, congestionResp = d.PrepareBlockIssuance(ctx, d.wallet.Client, account.ID.ToAddress().(*iotago.AccountAddress)) - d.SubmitPayload(context.Background(), invalidTX, account.ID, congestionResp, issuerResp) + wallet.IssueBasicBlock(ctx, "", mock.WithPayload(invalidTX)) d.AwaitTransactionPayloadAccepted(ctx, validTX.Transaction.MustID()) } diff --git a/tools/docker-network/tests/utils.go b/tools/docker-network/tests/utils.go index fe1f7212e..cc50d4e42 100644 --- a/tools/docker-network/tests/utils.go +++ b/tools/docker-network/tests/utils.go @@ -27,7 +27,7 @@ import ( func (d *DockerTestFramework) CheckAccountStatus(ctx context.Context, blkID iotago.BlockID, txID iotago.TransactionID, creationOutputID iotago.OutputID, accountAddress *iotago.AccountAddress, checkIndexer ...bool) { // request by blockID if provided, otherwise use txID // we take the slot from the blockID in case the tx is created earlier than the block. - clt := d.wallet.Client + clt := d.defaultWallet.Client slot := blkID.Slot() if blkID == iotago.EmptyBlockID { @@ -45,7 +45,7 @@ func (d *DockerTestFramework) CheckAccountStatus(ctx context.Context, blkID iota // Check the indexer if len(checkIndexer) > 0 && checkIndexer[0] { - indexerClt, err := d.wallet.Client.Indexer(ctx) + indexerClt, err := d.defaultWallet.Client.Indexer(ctx) require.NoError(d.Testing, err) _, _, _, err = indexerClt.Account(ctx, accountAddress) @@ -60,7 +60,7 @@ func (d *DockerTestFramework) CheckAccountStatus(ctx context.Context, blkID iota func (d *DockerTestFramework) AssertIndexerAccount(account *mock.AccountData) { d.Eventually(func() error { ctx := context.TODO() - indexerClt, err := d.wallet.Client.Indexer(ctx) + indexerClt, err := d.defaultWallet.Client.Indexer(ctx) if err != nil { return err } @@ -80,7 +80,7 @@ func (d *DockerTestFramework) AssertIndexerAccount(account *mock.AccountData) { func (d *DockerTestFramework) AssertIndexerFoundry(foundryID iotago.FoundryID) { d.Eventually(func() error { ctx := context.TODO() - indexerClt, err := d.wallet.Client.Indexer(ctx) + indexerClt, err := d.defaultWallet.Client.Indexer(ctx) if err != nil { return err } @@ -114,7 +114,7 @@ func (d *DockerTestFramework) AssertCommittee(expectedEpoch iotago.EpochIndex, e sort.Strings(expectedCommitteeMember) status := d.NodeStatus("V1") - testAPI := d.wallet.Client.CommittedAPI() + testAPI := d.defaultWallet.Client.CommittedAPI() expectedSlotStart := testAPI.TimeProvider().EpochStart(expectedEpoch) require.Greater(d.Testing, expectedSlotStart, status.LatestAcceptedBlockSlot) @@ -195,7 +195,7 @@ func (d *DockerTestFramework) Eventually(condition func() error, waitForSync ... } func (d *DockerTestFramework) AwaitTransactionPayloadAccepted(ctx context.Context, txID iotago.TransactionID) { - clt := d.wallet.Client + clt := d.defaultWallet.Client d.Eventually(func() error { resp, err := clt.TransactionMetadata(ctx, txID) @@ -217,7 +217,7 @@ func (d *DockerTestFramework) AwaitTransactionPayloadAccepted(ctx context.Contex func (d *DockerTestFramework) AwaitTransactionState(ctx context.Context, txID iotago.TransactionID, expectedState api.TransactionState) { d.Eventually(func() error { - resp, err := d.wallet.Client.TransactionMetadata(ctx, txID) + resp, err := d.defaultWallet.Client.TransactionMetadata(ctx, txID) if err != nil { return err } @@ -232,7 +232,7 @@ func (d *DockerTestFramework) AwaitTransactionState(ctx context.Context, txID io func (d *DockerTestFramework) AwaitTransactionFailure(ctx context.Context, txID iotago.TransactionID, expectedReason api.TransactionFailureReason) { d.Eventually(func() error { - resp, err := d.wallet.Client.TransactionMetadata(ctx, txID) + resp, err := d.defaultWallet.Client.TransactionMetadata(ctx, txID) if err != nil { return err } @@ -270,10 +270,10 @@ func (d *DockerTestFramework) AwaitFinalization(targetSlot iotago.SlotIndex) { }) } -func (d *DockerTestFramework) AwaitAddressUnspentOutputAccepted(ctx context.Context, addr iotago.Address) (outputID iotago.OutputID, output iotago.Output, err error) { - indexerClt, err := d.wallet.Client.Indexer(ctx) +func (d *DockerTestFramework) AwaitAddressUnspentOutputAccepted(ctx context.Context, wallet *mock.Wallet, addr iotago.Address) (outputID iotago.OutputID, output iotago.Output, err error) { + indexerClt, err := wallet.Client.Indexer(ctx) require.NoError(d.Testing, err) - addrBech := addr.Bech32(d.wallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP()) + addrBech := addr.Bech32(d.defaultWallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP()) for t := time.Now(); time.Since(t) < d.optsWaitFor; time.Sleep(d.optsTick) { res, err := indexerClt.Outputs(ctx, &api.BasicOutputsQuery{ @@ -300,8 +300,8 @@ func (d *DockerTestFramework) AwaitAddressUnspentOutputAccepted(ctx context.Cont return iotago.EmptyOutputID, nil, ierrors.Errorf("no unspent outputs found for address %s due to timeout", addrBech) } -func (d *DockerTestFramework) SendFaucetRequest(ctx context.Context, receiveAddr iotago.Address) { - cltAPI := d.wallet.Client.CommittedAPI() +func (d *DockerTestFramework) SendFaucetRequest(ctx context.Context, wallet *mock.Wallet, receiveAddr iotago.Address) { + cltAPI := wallet.Client.CommittedAPI() addrBech := receiveAddr.Bech32(cltAPI.ProtocolParameters().Bech32HRP()) type EnqueueRequest struct { diff --git a/tools/docker-network/tests/wallet.go b/tools/docker-network/tests/wallet.go index da950ad71..3849ee0d4 100644 --- a/tools/docker-network/tests/wallet.go +++ b/tools/docker-network/tests/wallet.go @@ -8,7 +8,6 @@ import ( "sync" "sync/atomic" "testing" - "time" "github.com/stretchr/testify/require" @@ -308,72 +307,6 @@ func (w *DockerWallet) CreateDelegationFromInput(issuerID iotago.AccountID, vali return signedTx } -func (w *DockerWallet) CreateFoundryAndNativeTokensFromInput(issuerID iotago.AccountID, inputID iotago.OutputID, mintedAmount iotago.BaseToken, maxSupply iotago.BaseToken, issuerResp *api.IssuanceBlockHeaderResponse) *iotago.SignedTransaction { - input := w.Output(inputID) - - issuer := w.Account(issuerID) - currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.Client.APIForSlot(currentSlot) - - // increase foundry counter - accTransitionOutput := builder.NewAccountOutputBuilderFromPrevious(issuer.Output). - FoundriesToGenerate(1).MustBuild() - - // build foundry output - foundryID, err := iotago.FoundryIDFromAddressAndSerialNumberAndTokenScheme(issuer.Address, accTransitionOutput.FoundryCounter, iotago.TokenSchemeSimple) - require.NoError(w.Testing, err) - tokenScheme := &iotago.SimpleTokenScheme{ - MintedTokens: big.NewInt(int64(mintedAmount)), - MaximumSupply: big.NewInt(int64(maxSupply)), - MeltedTokens: big.NewInt(0), - } - - foundryOutput := builder.NewFoundryOutputBuilder(issuer.Address, input.Output.BaseTokenAmount(), accTransitionOutput.FoundryCounter, tokenScheme). - NativeToken(&iotago.NativeTokenFeature{ - ID: foundryID, - Amount: big.NewInt(int64(mintedAmount)), - }).MustBuild() - - signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex, issuer.AddressIndex)). - AddInput(&builder.TxInput{ - UnlockTarget: input.Address, - InputID: input.ID, - Input: input.Output, - }). - AddInput(&builder.TxInput{ - UnlockTarget: issuer.Output.UnlockConditionSet().Address().Address, - InputID: issuer.OutputID, - Input: issuer.Output, - }). - AddOutput(accTransitionOutput). - AddOutput(foundryOutput). - SetCreationSlot(currentSlot). - AddBlockIssuanceCreditInput(&iotago.BlockIssuanceCreditInput{AccountID: issuerID}). - AddCommitmentInput(&iotago.CommitmentInput{CommitmentID: lo.Return1(issuerResp.LatestCommitment.ID())}). - AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("foundry")}). - AllotAllMana(currentSlot, issuerID, 0). - Build() - require.NoError(w.Testing, err) - - foundryOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 1) - w.AddOutput(foundryOutputID, &mock.OutputData{ - ID: foundryOutputID, - Output: foundryOutput, - Address: issuer.Address, - }) - - //nolint:forcetypeassert - w.AddAccount(issuerID, &mock.AccountData{ - ID: issuerID, - Address: issuer.Address, - AddressIndex: issuer.AddressIndex, - Output: signedTx.Transaction.Outputs[0].(*iotago.AccountOutput), - OutputID: iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0), - }) - - return signedTx -} - // TransitionFoundry transitions a FoundryOutput by increasing the native token amount on the output by one. func (w *DockerWallet) TransitionFoundry(issuerID iotago.AccountID, inputID iotago.OutputID, issuerResp *api.IssuanceBlockHeaderResponse) *iotago.SignedTransaction { issuer := w.Account(issuerID) @@ -483,24 +416,3 @@ func (w *DockerWallet) CreateNFTFromInput(issuerID iotago.AccountID, inputID iot return signedTx } - -func (w *DockerWallet) CreateBasicOutputFromInput(input *mock.OutputData, issuerAccountID iotago.AccountID) *iotago.SignedTransaction { - currentSlot := w.Client.LatestAPI().TimeProvider().SlotFromTime(time.Now()) - apiForSlot := w.Client.APIForSlot(currentSlot) - _, ed25519Addr := w.Address() - basicOutput := builder.NewBasicOutputBuilder(ed25519Addr, input.Output.BaseTokenAmount()).MustBuild() - signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex)). - AddInput(&builder.TxInput{ - UnlockTarget: input.Address, - InputID: input.ID, - Input: input.Output, - }). - AddOutput(basicOutput). - SetCreationSlot(currentSlot). - AllotAllMana(currentSlot, issuerAccountID, 0). - AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("basic")}). - Build() - require.NoError(w.Testing, err) - - return signedTx -} From e7211aaf90493e252bca5f5368ee03aa4faec439 Mon Sep 17 00:00:00 2001 From: Andrew Date: Tue, 26 Mar 2024 17:03:47 +0000 Subject: [PATCH 04/23] delete docker wallet file --- tools/docker-network/tests/wallet.go | 418 --------------------------- 1 file changed, 418 deletions(-) delete mode 100644 tools/docker-network/tests/wallet.go diff --git a/tools/docker-network/tests/wallet.go b/tools/docker-network/tests/wallet.go deleted file mode 100644 index 3849ee0d4..000000000 --- a/tools/docker-network/tests/wallet.go +++ /dev/null @@ -1,418 +0,0 @@ -//go:build dockertests - -package tests - -import ( - "crypto/ed25519" - "math/big" - "sync" - "sync/atomic" - "testing" - - "github.com/stretchr/testify/require" - - hiveEd25519 "github.com/iotaledger/hive.go/crypto/ed25519" - "github.com/iotaledger/hive.go/ierrors" - "github.com/iotaledger/hive.go/lo" - "github.com/iotaledger/hive.go/runtime/options" - "github.com/iotaledger/iota-core/pkg/testsuite/mock" - iotago "github.com/iotaledger/iota.go/v4" - "github.com/iotaledger/iota.go/v4/api" - "github.com/iotaledger/iota.go/v4/builder" - "github.com/iotaledger/iota.go/v4/wallet" -) - -// DockerWallet holds a keyManager, created outputs and accounts details. -type DockerWallet struct { - Testing *testing.T - - Client mock.Client - - keyManager *wallet.KeyManager - - BlockIssuer *mock.BlockIssuer - - lastUsedIndex atomic.Uint32 - - outputs map[iotago.OutputID]*mock.OutputData - outputsLock sync.RWMutex - - accounts map[iotago.AccountID]*mock.AccountData - accountsLock sync.RWMutex -} - -func NewDockerWallet(t *testing.T) *DockerWallet { - return &DockerWallet{ - Testing: t, - outputs: make(map[iotago.OutputID]*mock.OutputData), - accounts: make(map[iotago.AccountID]*mock.AccountData), - keyManager: lo.PanicOnErr(wallet.NewKeyManagerFromRandom(wallet.DefaultIOTAPath)), - } -} - -func (w *DockerWallet) AddOutput(outputID iotago.OutputID, output *mock.OutputData) { - w.outputsLock.Lock() - defer w.outputsLock.Unlock() - - w.outputs[outputID] = output -} - -func (w *DockerWallet) AddAccount(accountID iotago.AccountID, data *mock.AccountData) { - w.accountsLock.Lock() - defer w.accountsLock.Unlock() - - w.accounts[accountID] = data -} - -func (w *DockerWallet) Output(outputName iotago.OutputID) *mock.OutputData { - w.outputsLock.RLock() - defer w.outputsLock.RUnlock() - - output, exists := w.outputs[outputName] - if !exists { - panic(ierrors.Errorf("output %s not registered in wallet", outputName)) - } - - return output -} - -func (w *DockerWallet) Account(accountID iotago.AccountID) *mock.AccountData { - w.accountsLock.RLock() - defer w.accountsLock.RUnlock() - - acc, exists := w.accounts[accountID] - if !exists { - panic(ierrors.Errorf("account %s not registered in wallet", accountID.ToHex())) - } - - return acc -} - -func (w *DockerWallet) Accounts(accountIds ...iotago.AccountID) []*mock.AccountData { - w.accountsLock.RLock() - defer w.accountsLock.RUnlock() - - accounts := make([]*mock.AccountData, 0) - if len(accountIds) == 0 { - for _, acc := range w.accounts { - accounts = append(accounts, acc) - } - } - - for _, id := range accountIds { - acc, exists := w.accounts[id] - if !exists { - panic(ierrors.Errorf("account %s not registered in wallet", id.ToHex())) - } - accounts = append(accounts, acc) - } - - return accounts -} - -func (w *DockerWallet) Address(index ...uint32) (uint32, *iotago.Ed25519Address) { - if len(index) == 0 { - index = append(index, w.lastUsedIndex.Add(1)) - } - - address := w.keyManager.Address(iotago.AddressEd25519, index...) - //nolint:forcetypeassert - return index[0], address.(*iotago.Ed25519Address) -} - -func (w *DockerWallet) ImplicitAccountCreationAddress(index ...uint32) (uint32, *iotago.ImplicitAccountCreationAddress) { - if len(index) == 0 { - index = append(index, w.lastUsedIndex.Add(1)) - } - - address := w.keyManager.Address(iotago.AddressImplicitAccountCreation, index...) - //nolint:forcetypeassert - return index[0], address.(*iotago.ImplicitAccountCreationAddress) -} - -func (w *DockerWallet) KeyPair(indexes ...uint32) (ed25519.PrivateKey, ed25519.PublicKey) { - return w.keyManager.KeyPair(indexes...) -} - -func (w *DockerWallet) AddressSigner(indexes ...uint32) iotago.AddressSigner { - return w.keyManager.AddressSigner(indexes...) -} - -func (w *DockerWallet) AllotManaFromAccount(fromID iotago.AccountID, toID iotago.AccountID, manaToAllot iotago.Mana, inputID iotago.OutputID) *iotago.SignedTransaction { - from := w.Account(fromID) - to := w.Account(toID) - input := w.Output(inputID) - - currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.Client.APIForSlot(currentSlot) - - basicOutput, ok := input.Output.(*iotago.BasicOutput) - require.True(w.Testing, ok) - - // Subtract stored mana from source outputs to fund Allotment. - outputBuilder := builder.NewBasicOutputBuilderFromPrevious(basicOutput) - actualAllottedMana := manaToAllot - if manaToAllot >= basicOutput.StoredMana() { - actualAllottedMana = basicOutput.StoredMana() - outputBuilder.Mana(0) - } else { - outputBuilder.Mana(basicOutput.StoredMana() - manaToAllot) - } - - signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex)). - AddInput(&builder.TxInput{ - UnlockTarget: input.Address, - InputID: input.ID, - Input: input.Output, - }). - IncreaseAllotment(to.ID, actualAllottedMana). - AddOutput(basicOutput). - SetCreationSlot(currentSlot). - AllotAllMana(currentSlot, from.ID, 0). - Build() - require.NoError(w.Testing, err) - - allotmentOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) - w.AddOutput(allotmentOutputID, &mock.OutputData{ - ID: allotmentOutputID, - Output: basicOutput, - Address: input.Address, - AddressIndex: input.AddressIndex, - }) - - return signedTx -} - -func (w *DockerWallet) AllotManaFromInput(toID iotago.AccountID, inputID iotago.OutputID) *iotago.SignedTransaction { - to := w.Account(toID) - input := w.Output(inputID) - - currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.Client.APIForSlot(currentSlot) - - basicOutput, err := builder.NewBasicOutputBuilder(input.Address, input.Output.BaseTokenAmount()).Build() - require.NoError(w.Testing, err) - - signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex)). - AddInput(&builder.TxInput{ - UnlockTarget: input.Address, - InputID: input.ID, - Input: input.Output, - }). - AddOutput(basicOutput). - AllotAllMana(currentSlot, to.ID, 0). - SetCreationSlot(currentSlot). - Build() - require.NoError(w.Testing, err) - - delegationOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) - w.AddOutput(delegationOutputID, &mock.OutputData{ - ID: delegationOutputID, - Output: basicOutput, - Address: input.Address, - AddressIndex: input.AddressIndex, - }) - - return signedTx -} - -func (w *DockerWallet) TransitionImplicitAccountToAccountOutput(inputID iotago.OutputID, issuerResp *api.IssuanceBlockHeaderResponse, opts ...options.Option[builder.AccountOutputBuilder]) (*mock.AccountData, *iotago.SignedTransaction) { - input := w.Output(inputID) - - accountID := iotago.AccountIDFromOutputID(input.ID) - accountAddress, ok := accountID.ToAddress().(*iotago.AccountAddress) - require.True(w.Testing, ok) - - currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.Client.APIForSlot(currentSlot) - - // transition to a full account with new Ed25519 address and staking feature - accEd25519AddrIndex, accEd25519Addr := w.Address() - accPrivateKey, _ := w.KeyPair(accEd25519AddrIndex) - //nolint:forcetypeassert - accBlockIssuerKey := iotago.Ed25519PublicKeyHashBlockIssuerKeyFromPublicKey(hiveEd25519.PublicKey(accPrivateKey.Public().(ed25519.PublicKey))) - accountOutput := options.Apply(builder.NewAccountOutputBuilder(accEd25519Addr, input.Output.BaseTokenAmount()), - opts, func(b *builder.AccountOutputBuilder) { - b.AccountID(accountID). - BlockIssuer(iotago.NewBlockIssuerKeys(accBlockIssuerKey), iotago.MaxSlotIndex) - }).MustBuild() - - signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex)). - AddInput(&builder.TxInput{ - UnlockTarget: input.Address, - InputID: input.ID, - Input: input.Output, - }). - AddOutput(accountOutput). - SetCreationSlot(currentSlot). - AddCommitmentInput(&iotago.CommitmentInput{CommitmentID: lo.Return1(issuerResp.LatestCommitment.ID())}). - AddBlockIssuanceCreditInput(&iotago.BlockIssuanceCreditInput{AccountID: accountID}). - AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("account")}). - AllotAllMana(currentSlot, accountID, 0). - Build() - require.NoError(w.Testing, err) - - accountOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) - w.AddOutput(accountOutputID, &mock.OutputData{ - ID: accountOutputID, - Output: accountOutput, - Address: accEd25519Addr, - AddressIndex: accEd25519AddrIndex, - }) - - accountInfo := &mock.AccountData{ - ID: accountID, - Address: accountAddress, - AddressIndex: accEd25519AddrIndex, - Output: accountOutput, - OutputID: accountOutputID, - } - - return accountInfo, signedTx -} - -func (w *DockerWallet) CreateDelegationFromInput(issuerID iotago.AccountID, validatorAccountAddr *iotago.AccountAddress, inputID iotago.OutputID, issuerResp *api.IssuanceBlockHeaderResponse) *iotago.SignedTransaction { - input := w.Output(inputID) - - currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.Client.APIForSlot(currentSlot) - - // construct delegation transaction - //nolint:forcetypeassert - delegationOutput := builder.NewDelegationOutputBuilder(validatorAccountAddr, input.Address, input.Output.BaseTokenAmount()). - StartEpoch(getDelegationStartEpoch(apiForSlot, issuerResp.LatestCommitment.Slot)). - DelegatedAmount(input.Output.BaseTokenAmount()).MustBuild() - signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex)). - AddInput(&builder.TxInput{ - UnlockTarget: input.Address, - InputID: input.ID, - Input: input.Output, - }). - AddOutput(delegationOutput). - SetCreationSlot(currentSlot). - AddCommitmentInput(&iotago.CommitmentInput{CommitmentID: lo.Return1(issuerResp.LatestCommitment.ID())}). - AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("delegation")}). - AllotAllMana(currentSlot, issuerID, 0). - Build() - require.NoError(w.Testing, err) - - delegationOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) - w.AddOutput(delegationOutputID, &mock.OutputData{ - ID: delegationOutputID, - Output: delegationOutput, - Address: input.Address, - AddressIndex: input.AddressIndex, - }) - - return signedTx -} - -// TransitionFoundry transitions a FoundryOutput by increasing the native token amount on the output by one. -func (w *DockerWallet) TransitionFoundry(issuerID iotago.AccountID, inputID iotago.OutputID, issuerResp *api.IssuanceBlockHeaderResponse) *iotago.SignedTransaction { - issuer := w.Account(issuerID) - input := w.Output(inputID) - inputFoundry, isFoundry := input.Output.(*iotago.FoundryOutput) - require.True(w.Testing, isFoundry) - - nativeTokenAmount := inputFoundry.FeatureSet().NativeToken().Amount - previousTokenScheme, isSimple := inputFoundry.TokenScheme.(*iotago.SimpleTokenScheme) - require.True(w.Testing, isSimple) - - tokenScheme := &iotago.SimpleTokenScheme{ - MaximumSupply: previousTokenScheme.MaximumSupply, - MeltedTokens: previousTokenScheme.MeltedTokens, - MintedTokens: previousTokenScheme.MintedTokens.Add(previousTokenScheme.MintedTokens, big.NewInt(1)), - } - - require.Greater(w.Testing, tokenScheme.MintedTokens.Cmp(tokenScheme.MaximumSupply), 0) - - outputFoundry := builder.NewFoundryOutputBuilderFromPrevious(inputFoundry). - NativeToken(&iotago.NativeTokenFeature{ - ID: inputFoundry.MustFoundryID(), - Amount: nativeTokenAmount.Add(nativeTokenAmount, big.NewInt(1)), - }). - TokenScheme(tokenScheme). - MustBuild() - - outputAccount := builder.NewAccountOutputBuilderFromPrevious(issuer.Output). - MustBuild() - - currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.Client.APIForSlot(currentSlot) - - signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex, issuer.AddressIndex)). - AddInput(&builder.TxInput{ - UnlockTarget: input.Address, - InputID: input.ID, - Input: input.Output, - }). - AddInput(&builder.TxInput{ - UnlockTarget: issuer.Output.UnlockConditionSet().Address().Address, - InputID: issuer.OutputID, - Input: issuer.Output, - }). - AddOutput(outputAccount). - AddOutput(outputFoundry). - SetCreationSlot(currentSlot). - AddBlockIssuanceCreditInput(&iotago.BlockIssuanceCreditInput{AccountID: issuer.ID}). - AddCommitmentInput(&iotago.CommitmentInput{CommitmentID: lo.Return1(issuerResp.LatestCommitment.ID())}). - AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("foundry")}). - AllotAllMana(currentSlot, issuerID, 0). - Build() - require.NoError(w.Testing, err) - - foundryOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 1) - w.AddOutput(foundryOutputID, &mock.OutputData{ - ID: foundryOutputID, - Output: outputFoundry, - Address: issuer.Address, - }) - - //nolint:forcetypeassert - w.AddAccount(issuerID, &mock.AccountData{ - ID: issuerID, - Address: issuer.Address, - AddressIndex: issuer.AddressIndex, - Output: signedTx.Transaction.Outputs[0].(*iotago.AccountOutput), - OutputID: iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0), - }) - - return signedTx -} - -func (w *DockerWallet) CreateNFTFromInput(issuerID iotago.AccountID, inputID iotago.OutputID, issuerResp *api.IssuanceBlockHeaderResponse, opts ...options.Option[builder.NFTOutputBuilder]) *iotago.SignedTransaction { - input := w.Output(inputID) - - currentSlot := w.Client.LatestAPI().TimeProvider().CurrentSlot() - apiForSlot := w.Client.APIForSlot(currentSlot) - - nftAddressIndex, nftAddress := w.Address() - nftOutputBuilder := builder.NewNFTOutputBuilder(nftAddress, input.Output.BaseTokenAmount()) - options.Apply(nftOutputBuilder, opts) - nftOutput := nftOutputBuilder.MustBuild() - - signedTx, err := builder.NewTransactionBuilder(apiForSlot, w.AddressSigner(input.AddressIndex)). - AddInput(&builder.TxInput{ - UnlockTarget: input.Address, - InputID: input.ID, - Input: input.Output, - }). - AddOutput(nftOutput). - SetCreationSlot(currentSlot). - AddBlockIssuanceCreditInput(&iotago.BlockIssuanceCreditInput{AccountID: issuerID}). - AddCommitmentInput(&iotago.CommitmentInput{CommitmentID: lo.Return1(issuerResp.LatestCommitment.ID())}). - AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("nft")}). - AllotAllMana(currentSlot, issuerID, 0). - Build() - require.NoError(w.Testing, err) - - nftOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) - w.AddOutput(nftOutputID, &mock.OutputData{ - ID: nftOutputID, - Output: nftOutput, - Address: nftAddress, - AddressIndex: nftAddressIndex, - }) - - return signedTx -} From 016f27a2a063b537abb31e3166105a340f1cbff2 Mon Sep 17 00:00:00 2001 From: Andrew Date: Tue, 26 Mar 2024 17:14:36 +0000 Subject: [PATCH 05/23] fix merge errors --- pkg/testsuite/mock/client.go | 5 +++++ tools/docker-network/tests/api_core_test.go | 2 +- tools/docker-network/tests/dockerframework.go | 5 ----- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pkg/testsuite/mock/client.go b/pkg/testsuite/mock/client.go index caa63f8e1..0ba3452ae 100644 --- a/pkg/testsuite/mock/client.go +++ b/pkg/testsuite/mock/client.go @@ -47,6 +47,7 @@ type Client interface { Rewards(ctx context.Context, outputID iotago.OutputID) (*api.ManaRewardsResponse, error) Routes(ctx context.Context) (*api.RoutesResponse, error) SubmitBlock(ctx context.Context, m *iotago.Block) (iotago.BlockID, error) + TransactionByID(ctx context.Context, txID iotago.TransactionID) (*iotago.Transaction, error) TransactionIncludedBlock(ctx context.Context, txID iotago.TransactionID) (*iotago.Block, error) TransactionIncludedBlockMetadata(ctx context.Context, txID iotago.TransactionID) (*api.BlockMetadataResponse, error) TransactionMetadata(ctx context.Context, txID iotago.TransactionID) (*api.TransactionMetadataResponse, error) @@ -243,6 +244,10 @@ func (c *TestSuiteClient) SubmitBlock(ctx context.Context, block *iotago.Block) return c.Node.RequestHandler.SubmitBlockAndAwaitRetainer(ctx, block) } +func (c *TestSuiteClient) TransactionByID(_ context.Context, txID iotago.TransactionID) (*iotago.Transaction, error) { + panic("not implemented") +} + func (c *TestSuiteClient) TransactionIncludedBlock(_ context.Context, txID iotago.TransactionID) (*iotago.Block, error) { return c.Node.RequestHandler.BlockFromTransactionID(txID) } diff --git a/tools/docker-network/tests/api_core_test.go b/tools/docker-network/tests/api_core_test.go index b529b3118..8565c1d9e 100644 --- a/tools/docker-network/tests/api_core_test.go +++ b/tools/docker-network/tests/api_core_test.go @@ -286,7 +286,7 @@ func Test_CoreAPI(t *testing.T) { testFunc: func(t *testing.T, nodeAlias string) { assetsPerSlot.forEachTransaction(t, func(t *testing.T, transaction *iotago.SignedTransaction, firstAttachmentID iotago.BlockID) { txID := transaction.Transaction.MustID() - resp, err := d.wallet.Clients[nodeAlias].TransactionByID(context.Background(), txID) + resp, err := d.Client(nodeAlias).TransactionByID(context.Background(), txID) require.NoError(t, err) require.NotNil(t, resp) require.EqualValues(t, txID, resp.MustID()) diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 94b74b4a3..40488c4b9 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -363,11 +363,6 @@ func (d *DockerTestFramework) NodeStatus(name string) *api.InfoResNodeStatus { return info.Status } -// Client returns the node client by the given node name. -func (d *DockerTestFramework) Client(name string) *nodeclient.Client { - return d.wallet.Clients[name] -} - func (d *DockerTestFramework) AccountsFromNodes(nodes ...*Node) []string { var accounts []string for _, node := range nodes { From 1ad981e4808fc3960163051d642cb67d1867dfbb Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 27 Mar 2024 15:30:54 +0000 Subject: [PATCH 06/23] fix accounts docker test --- pkg/testsuite/mock/blockissuer.go | 19 +++---- pkg/testsuite/mock/node.go | 4 +- pkg/testsuite/mock/wallet.go | 23 ++++++-- pkg/testsuite/mock/wallet_transactions.go | 27 +++++----- pkg/testsuite/testsuite.go | 2 +- pkg/testsuite/workscore_regression_test.go | 4 +- .../tests/accounttransition_test.go | 4 +- tools/docker-network/tests/dockerframework.go | 54 +++++++++++++++---- 8 files changed, 92 insertions(+), 45 deletions(-) diff --git a/pkg/testsuite/mock/blockissuer.go b/pkg/testsuite/mock/blockissuer.go index c3a085f11..abbb11487 100644 --- a/pkg/testsuite/mock/blockissuer.go +++ b/pkg/testsuite/mock/blockissuer.go @@ -54,18 +54,15 @@ type BlockIssuer struct { AccountData *AccountData } -func NewBlockIssuer(t *testing.T, name string, keyManager *wallet.KeyManager, client Client, addressIndex uint32, accountID iotago.AccountID, validator bool, opts ...options.Option[BlockIssuer]) *BlockIssuer { +func NewBlockIssuer(t *testing.T, name string, keyManager *wallet.KeyManager, client Client, accountData *AccountData, validator bool, opts ...options.Option[BlockIssuer]) *BlockIssuer { t.Helper() - _, pub := keyManager.KeyPair(addressIndex) + _, pub := keyManager.KeyPair(accountData.AddressIndex) - if accountID == iotago.EmptyAccountID { - accountID = blake2b.Sum256(pub) + if accountData.ID == iotago.EmptyAccountID { + accountData.ID = blake2b.Sum256(pub) } - accountID.RegisterAlias(name) - - accountAddress, ok := accountID.ToAddress().(*iotago.AccountAddress) - require.True(t, ok) + accountData.ID.RegisterAlias(name) return options.Apply(&BlockIssuer{ Testing: t, @@ -74,11 +71,7 @@ func NewBlockIssuer(t *testing.T, name string, keyManager *wallet.KeyManager, cl keyManager: keyManager, Client: client, blockIssuanceResponseUsed: true, - AccountData: &AccountData{ - ID: accountID, - AddressIndex: addressIndex, - Address: accountAddress, - }, + AccountData: accountData, }, opts) } diff --git a/pkg/testsuite/mock/node.go b/pkg/testsuite/mock/node.go index 9e77af54d..915533c9b 100644 --- a/pkg/testsuite/mock/node.go +++ b/pkg/testsuite/mock/node.go @@ -101,7 +101,7 @@ func NewNode(t *testing.T, parentLogger log.Logger, net *Network, partition stri var validator *BlockIssuer if isValidator { - validator = NewBlockIssuer(t, name, keyManager, nil, 0, accountID, isValidator) + validator = NewBlockIssuer(t, name, keyManager, nil, NewAccountDataFromAccountID(accountID), isValidator) } else { validator = nil } @@ -148,7 +148,7 @@ func (n *Node) Initialize(failOnBlockFiltered bool, opts ...options.Option[proto n.Client = NewTestSuiteClient(n) if n.isValidator { - n.Validator = NewBlockIssuer(n.Testing, n.Name, n.KeyManager, n.Client, 0, accountID, n.isValidator) + n.Validator = NewBlockIssuer(n.Testing, n.Name, n.KeyManager, n.Client, NewAccountDataFromAccountID(accountID), n.isValidator) } n.hookEvents() n.hookEngineEvents(failOnBlockFiltered) diff --git a/pkg/testsuite/mock/wallet.go b/pkg/testsuite/mock/wallet.go index 527910db9..5efd54305 100644 --- a/pkg/testsuite/mock/wallet.go +++ b/pkg/testsuite/mock/wallet.go @@ -45,6 +45,21 @@ type AccountData struct { OutputID iotago.OutputID } +func NewAccountDataFromAccountID(accountID iotago.AccountID, addressIndex ...uint32) *AccountData { + accountAddress, ok := accountID.ToAddress().(*iotago.AccountAddress) + if !ok { + panic(ierrors.Errorf("accountID %s is not an account address", accountID.ToHex())) + } + if len(addressIndex) == 0 { + addressIndex = []uint32{0} + } + return &AccountData{ + ID: accountID, + Address: accountAddress, + AddressIndex: addressIndex[0], + } +} + // WalletClock is an interface that provides the current slot. type WalletClock interface { SetCurrentSlot(slot iotago.SlotIndex) @@ -89,7 +104,7 @@ type Wallet struct { clock WalletClock } -func NewWallet(t *testing.T, name string, client Client, keyManager ...*wallet.KeyManager) *Wallet { +func NewWallet(t *testing.T, name string, client Client, clock WalletClock, keyManager ...*wallet.KeyManager) *Wallet { t.Helper() var km *wallet.KeyManager @@ -110,13 +125,13 @@ func NewWallet(t *testing.T, name string, client Client, keyManager ...*wallet.K accounts: make(map[iotago.AccountID]*AccountData), transactions: make(map[string]*iotago.Transaction), keyManager: km, - BlockIssuer: NewBlockIssuer(t, name, km, client, blockIssuerAddressIndex, blockIssuerID, false), - clock: &TestSuiteWalletClock{}, + BlockIssuer: NewBlockIssuer(t, name, km, client, NewAccountDataFromAccountID(blockIssuerID, blockIssuerAddressIndex), false), + clock: clock, } } func (w *Wallet) SetBlockIssuer(accountData *AccountData) { - w.BlockIssuer = NewBlockIssuer(w.Testing, w.Name, w.keyManager, w.Client, accountData.AddressIndex, accountData.ID, false) + w.BlockIssuer = NewBlockIssuer(w.Testing, w.Name, w.keyManager, w.Client, accountData, false) } func (w *Wallet) SetDefaultClient(client Client) { diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 332183028..64b0bc3c0 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -610,35 +610,38 @@ func (w *Wallet) TransitionFoundry(transactionName string, foundryInput *OutputD return signedTransaction } -func (w *Wallet) AllotManaFromBasicOutput(transactionName string, input *OutputData, accountIDs ...iotago.AccountID) *iotago.SignedTransaction { +func (w *Wallet) AllotManaFromBasicOutput(transactionName string, input *OutputData, manaToAllot iotago.Mana, accountIDs ...iotago.AccountID) *iotago.SignedTransaction { if _, isBasic := input.Output.(*iotago.BasicOutput); !isBasic { panic("input is not *iotago.BasicOutput") } + + apiForSlot := w.Client.APIForSlot(w.CurrentSlot()) + manaDecayProvider := apiForSlot.ManaDecayProvider() + storageScoreStructure := apiForSlot.StorageScoreStructure() + + totalInputMana := lo.PanicOnErr(vm.TotalManaIn(manaDecayProvider, storageScoreStructure, w.CurrentSlot(), vm.InputSet{input.ID: input.Output}, vm.RewardsInputSet{})) + if manaToAllot > totalInputMana { + panic("not enough mana to allot") + } + manaPerOutput := manaToAllot / iotago.Mana(len(accountIDs)) + remainderMana := manaToAllot - manaPerOutput*iotago.Mana(len(accountIDs)) output := &iotago.BasicOutput{ Amount: input.Output.BaseTokenAmount(), - Mana: 0, + Mana: totalInputMana - manaToAllot, UnlockConditions: iotago.BasicOutputUnlockConditions{ &iotago.AddressUnlockCondition{Address: w.Address()}, }, Features: iotago.BasicOutputFeatures{}, } - apiForSlot := w.Client.APIForSlot(w.CurrentSlot()) - manaDecayProvider := apiForSlot.ManaDecayProvider() - storageScoreStructure := apiForSlot.StorageScoreStructure() - - totalInputMana := lo.PanicOnErr(vm.TotalManaIn(manaDecayProvider, storageScoreStructure, w.CurrentSlot(), vm.InputSet{input.ID: input.Output}, vm.RewardsInputSet{})) - outputMana := totalInputMana / iotago.Mana(len(accountIDs)) - remainderMana := totalInputMana - outputMana*iotago.Mana(len(accountIDs)) - var allotments iotago.Allotments for i, accountID := range accountIDs { if i+1 == len(accountIDs) { - outputMana += remainderMana + manaPerOutput += remainderMana } allotments = append(allotments, &iotago.Allotment{ AccountID: accountID, - Mana: outputMana, + Mana: manaPerOutput, }) } diff --git a/pkg/testsuite/testsuite.go b/pkg/testsuite/testsuite.go index 6a7bb6e68..01013a393 100644 --- a/pkg/testsuite/testsuite.go +++ b/pkg/testsuite/testsuite.go @@ -461,7 +461,7 @@ func (t *TestSuite) DefaultWallet() *mock.Wallet { } func (t *TestSuite) AddWallet(name string, node *mock.Node, accountID iotago.AccountID, keyManager ...*wallet.KeyManager) *mock.Wallet { - newWallet := mock.NewWallet(t.Testing, name, &mock.TestSuiteClient{Node: node}, keyManager...) + newWallet := mock.NewWallet(t.Testing, name, &mock.TestSuiteClient{Node: node}, &mock.TestSuiteWalletClock{}, keyManager...) newWallet.SetBlockIssuer(&mock.AccountData{ID: accountID}) t.wallets.Set(name, newWallet) newWallet.SetCurrentSlot(t.currentSlot) diff --git a/pkg/testsuite/workscore_regression_test.go b/pkg/testsuite/workscore_regression_test.go index d57647427..d3480497d 100644 --- a/pkg/testsuite/workscore_regression_test.go +++ b/pkg/testsuite/workscore_regression_test.go @@ -414,9 +414,11 @@ func allotments(t *testing.T, numAllotments int) (float64, []float64) { accountOutput := ts.AccountOutput(fmt.Sprintf("Genesis:%d", i+3)).Output.(*iotago.AccountOutput) accountIDs = append(accountIDs, accountOutput.AccountID) } + basicOutputData := ts.DefaultWallet().OutputData("Genesis:0") tx1 := ts.DefaultWallet().AllotManaFromBasicOutput( "tx1", - ts.DefaultWallet().OutputData("Genesis:0"), + basicOutputData, + basicOutputData.Output.StoredMana(), accountIDs..., ) commitment := node.Protocol.Chains.Main.Get().LatestCommitment.Get().Commitment.Commitment() diff --git a/tools/docker-network/tests/accounttransition_test.go b/tools/docker-network/tests/accounttransition_test.go index d13ad2867..e6e002a3a 100644 --- a/tools/docker-network/tests/accounttransition_test.go +++ b/tools/docker-network/tests/accounttransition_test.go @@ -44,11 +44,11 @@ func Test_AccountTransitions(t *testing.T) { // create account2 fmt.Println("Creating account2") - _, account2 := d.CreateAccount() + wallet2, _ := d.CreateAccount() // allot 1000 mana from account1 to account2 fmt.Println("Allotting mana from account1 to account2") - d.AllotManaTo(wallet1, account2.ID, 1000) + d.AllotManaTo(wallet1, wallet2.BlockIssuer.AccountData, 1000) // create native token fmt.Println("Creating native token") diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 40488c4b9..bcbbfe6fa 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -66,6 +66,17 @@ func (n *Node) AccountAddress(t *testing.T) *iotago.AccountAddress { return accAddress } +type DockerWalletClock struct { + client mock.Client +} + +func (c *DockerWalletClock) SetCurrentSlot(slot iotago.SlotIndex) { +} + +func (c *DockerWalletClock) CurrentSlot() iotago.SlotIndex { + return c.client.LatestAPI().TimeProvider().CurrentSlot() +} + type DockerTestFramework struct { Testing *testing.T @@ -209,6 +220,7 @@ func (d *DockerTestFramework) waitForNodesAndGetClients() error { d.Testing, "default", d.clients["V1"], + &DockerWalletClock{client: d.clients["V1"]}, lo.PanicOnErr(wallet.NewKeyManagerFromRandom(wallet.DefaultIOTAPath)), ) @@ -513,7 +525,7 @@ func (d *DockerTestFramework) CreateAccountBlockFromInput(wallet *mock.Wallet, i // CreateImplicitAccount requests faucet funds and creates an implicit account. It already wait until the transaction is committed and the created account is useable. func (d *DockerTestFramework) CreateImplicitAccount(ctx context.Context) (*mock.Wallet, *mock.OutputData) { - newWallet := mock.NewWallet(d.Testing, "", d.defaultWallet.Client) + newWallet := mock.NewWallet(d.Testing, "", d.defaultWallet.Client, &DockerWalletClock{client: d.defaultWallet.Client}) implicitAccountOutputData := d.RequestFaucetFunds(ctx, newWallet, iotago.AddressImplicitAccountCreation) accountID := iotago.AccountIDFromOutputID(implicitAccountOutputData.ID) @@ -523,6 +535,14 @@ func (d *DockerTestFramework) CreateImplicitAccount(ctx context.Context) (*mock. // make sure an implicit account is committed d.CheckAccountStatus(ctx, iotago.EmptyBlockID, implicitAccountOutputData.ID.TransactionID(), implicitAccountOutputData.ID, accountAddress) + // update the wallet with the new account data + newWallet.SetBlockIssuer(&mock.AccountData{ + ID: accountID, + Address: accountAddress, + OutputID: implicitAccountOutputData.ID, + AddressIndex: implicitAccountOutputData.AddressIndex, + }) + return newWallet, implicitAccountOutputData } @@ -531,8 +551,13 @@ func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.Accou // create an implicit account by requesting faucet funds ctx := context.TODO() newWallet, implicitAccountOutputData := d.CreateImplicitAccount(ctx) - clt := d.defaultWallet.Client + clt := newWallet.Client + var implicitBlockIssuerKey iotago.BlockIssuerKey = iotago.Ed25519PublicKeyHashBlockIssuerKeyFromImplicitAccountCreationAddress(newWallet.ImplicitAccountCreationAddress()) + opts = append(opts, mock.WithBlockIssuerFeature( + iotago.NewBlockIssuerKeys(implicitBlockIssuerKey), + iotago.MaxSlotIndex, + )) signedTx := newWallet.TransitionImplicitAccountToAccountOutput("", []*mock.OutputData{implicitAccountOutputData}, opts...) // The account transition block should be issued by the implicit account block issuer key. @@ -545,6 +570,15 @@ func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.Accou accAddress := (accOutput.AccountID).ToAddress().(*iotago.AccountAddress) d.CheckAccountStatus(ctx, block.ID(), signedTx.Transaction.MustID(), accOutputID, accAddress, true) + // update the wallet with the new account data + newWallet.SetBlockIssuer(&mock.AccountData{ + ID: accOutput.AccountID, + Address: accAddress, + Output: accOutput, + OutputID: accOutputID, + AddressIndex: implicitAccountOutputData.AddressIndex, + }) + fmt.Printf("Account created, Bech addr: %s, in txID: %s, slot: %d\n", accAddress.Bech32(clt.CommittedAPI().ProtocolParameters().Bech32HRP()), signedTx.Transaction.MustID().ToHex(), block.ID().Slot()) return newWallet, newWallet.Account(accOutput.AccountID) @@ -586,8 +620,7 @@ func (d *DockerTestFramework) PrepareBlockIssuance(ctx context.Context, clt mock } // AllotManaTo requests faucet funds then uses it to allots mana from one account to another. -func (d *DockerTestFramework) AllotManaTo(fromWallet *mock.Wallet, toID iotago.AccountID, manaToAllot iotago.Mana) { - to := d.defaultWallet.Account(toID) +func (d *DockerTestFramework) AllotManaTo(fromWallet *mock.Wallet, to *mock.AccountData, manaToAllot iotago.Mana) { // requesting faucet funds for allotment ctx := context.TODO() fundsOutputID := d.RequestFaucetFunds(ctx, fromWallet, iotago.AddressEd25519) @@ -596,20 +629,21 @@ func (d *DockerTestFramework) AllotManaTo(fromWallet *mock.Wallet, toID iotago.A signedTx := fromWallet.AllotManaFromBasicOutput( "", fundsOutputID, - toID, + manaToAllot, + to.ID, ) - + preAllotmentCommitmentID := fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.MustID() block, err := fromWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) fmt.Println("Allot mana transaction sent, blkID:", block.ID().ToHex(), ", txID:", signedTx.Transaction.MustID().ToHex(), ", slot:", block.ID().Slot()) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) - // allotment is updated until the transaction is committed + // allotment is updated when the transaction is committed d.AwaitCommitment(block.ID().Slot()) // check if the mana is allotted - toCongestionResp, err := clt.Congestion(ctx, to.Address, 0, lo.PanicOnErr(fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.ID())) + toCongestionResp, err := clt.Congestion(ctx, to.Address, 0, preAllotmentCommitmentID) require.NoError(d.Testing, err) oldBIC := toCongestionResp.BlockIssuanceCredits @@ -626,9 +660,9 @@ func (d *DockerTestFramework) CreateNativeToken(fromWallet *mock.Wallet, mintedA ctx := context.TODO() // requesting faucet funds for native token creation - fundsOutputData := d.RequestFaucetFunds(ctx, d.defaultWallet, iotago.AddressEd25519) + fundsOutputData := d.RequestFaucetFunds(ctx, fromWallet, iotago.AddressEd25519) - signedTx := d.defaultWallet.CreateFoundryAndNativeTokensFromInput(fundsOutputData, mintedAmount, maxSupply) + signedTx := fromWallet.CreateFoundryAndNativeTokensFromInput(fundsOutputData, mintedAmount, maxSupply) block, err := fromWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) From 49f675ce17b46edff7793f48fa2889c03ad07388 Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 27 Mar 2024 16:23:31 +0000 Subject: [PATCH 07/23] fix validators and core api tests --- pkg/testsuite/mock/blockissuer.go | 2 +- pkg/testsuite/mock/wallet_blocks.go | 8 +++-- pkg/testsuite/mock/wallet_transactions.go | 4 +-- pkg/testsuite/testsuite_issue_blocks.go | 2 +- tools/docker-network/tests/api_core.go | 4 +-- tools/docker-network/tests/api_core_test.go | 9 ++---- tools/docker-network/tests/dockerframework.go | 32 +++++++++---------- .../tests/mempool_invalid_signatures_test.go | 10 +++--- 8 files changed, 36 insertions(+), 35 deletions(-) diff --git a/pkg/testsuite/mock/blockissuer.go b/pkg/testsuite/mock/blockissuer.go index abbb11487..653b79d55 100644 --- a/pkg/testsuite/mock/blockissuer.go +++ b/pkg/testsuite/mock/blockissuer.go @@ -259,7 +259,7 @@ func (i *BlockIssuer) CreateBasicBlock(ctx context.Context, alias string, opts . return blocks.NewBlock(modelBlock), err } -func (i *BlockIssuer) IssueBasicBlock(ctx context.Context, alias string, opts ...options.Option[BasicBlockParams]) (*blocks.Block, error) { +func (i *BlockIssuer) CreateAndSubmitBasicBlock(ctx context.Context, alias string, opts ...options.Option[BasicBlockParams]) (*blocks.Block, error) { block, err := i.CreateBasicBlock(ctx, alias, opts...) if err != nil { return nil, err diff --git a/pkg/testsuite/mock/wallet_blocks.go b/pkg/testsuite/mock/wallet_blocks.go index 526807fa9..c528a2ab8 100644 --- a/pkg/testsuite/mock/wallet_blocks.go +++ b/pkg/testsuite/mock/wallet_blocks.go @@ -7,6 +7,10 @@ import ( "github.com/iotaledger/iota-core/pkg/protocol/engine/blocks" ) -func (w *Wallet) IssueBasicBlock(ctx context.Context, blockName string, opts ...options.Option[BasicBlockParams]) (*blocks.Block, error) { - return w.BlockIssuer.IssueBasicBlock(ctx, blockName, opts...) +func (w *Wallet) CreateBasicBlock(ctx context.Context, blockName string, opts ...options.Option[BasicBlockParams]) (*blocks.Block, error) { + return w.BlockIssuer.CreateBasicBlock(ctx, blockName, opts...) +} + +func (w *Wallet) CreateAndSubmitBasicBlock(ctx context.Context, blockName string, opts ...options.Option[BasicBlockParams]) (*blocks.Block, error) { + return w.BlockIssuer.CreateAndSubmitBasicBlock(ctx, blockName, opts...) } diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 64b0bc3c0..a94252124 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -1222,7 +1222,7 @@ func (w *Wallet) registerOutputs(transactionName string, transaction *iotago.Tra } } -func (w *Wallet) CreateBasicOutputFromInput(input *OutputData, issuerAccountID iotago.AccountID) *iotago.SignedTransaction { +func (w *Wallet) CreateBasicOutputFromInput(input *OutputData) *iotago.SignedTransaction { currentSlot := w.CurrentSlot() apiForSlot := w.Client.APIForSlot(currentSlot) ed25519Addr := w.Address() @@ -1235,7 +1235,7 @@ func (w *Wallet) CreateBasicOutputFromInput(input *OutputData, issuerAccountID i }). AddOutput(basicOutput). SetCreationSlot(currentSlot). - AllotAllMana(currentSlot, issuerAccountID, 0). + AllotAllMana(currentSlot, w.BlockIssuer.AccountData.ID, 0). AddTaggedDataPayload(&iotago.TaggedData{Tag: []byte("basic")}). Build() require.NoError(w.Testing, err) diff --git a/pkg/testsuite/testsuite_issue_blocks.go b/pkg/testsuite/testsuite_issue_blocks.go index e86ee04c8..ee23538cd 100644 --- a/pkg/testsuite/testsuite_issue_blocks.go +++ b/pkg/testsuite/testsuite_issue_blocks.go @@ -117,7 +117,7 @@ func (t *TestSuite) IssueBasicBlockWithOptions(blockName string, wallet *mock.Wa //nolint:gocritic blockHeaderOptions := append(blockOpts, mock.WithIssuingTime(issuingTime)) - block, err := wallet.IssueBasicBlock(context.Background(), blockName, mock.WithBasicBlockHeader(blockHeaderOptions...), mock.WithPayload(payload)) + block, err := wallet.CreateAndSubmitBasicBlock(context.Background(), blockName, mock.WithBasicBlockHeader(blockHeaderOptions...), mock.WithPayload(payload)) t.registerBlock(blockName, block) diff --git a/tools/docker-network/tests/api_core.go b/tools/docker-network/tests/api_core.go index ccce973ec..cc2f8df84 100644 --- a/tools/docker-network/tests/api_core.go +++ b/tools/docker-network/tests/api_core.go @@ -214,7 +214,7 @@ func (d *DockerTestFramework) prepareAssets(totalAssetsNum int) (coreAPIAssets, d.SubmitBlock(ctx, block) // transaction - valueBlock, signedTx, faucetOutput := d.CreateBasicOutputBlock(account.ID) + valueBlock, signedTx, faucetOutput := d.CreateBasicOutputBlock(wallet) valueBlockSlot := valueBlock.MustID().Slot() assets.setupAssetsForSlot(valueBlockSlot) // transaction and outputs are stored with the earliest included block @@ -227,7 +227,7 @@ func (d *DockerTestFramework) prepareAssets(totalAssetsNum int) (coreAPIAssets, d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) // issue reattachment after the fisrt one is already included - secondAttachment, err := wallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + secondAttachment, err := wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) assets[valueBlockSlot].reattachments = append(assets[valueBlockSlot].reattachments, secondAttachment.ID()) diff --git a/tools/docker-network/tests/api_core_test.go b/tools/docker-network/tests/api_core_test.go index 8565c1d9e..e023847a7 100644 --- a/tools/docker-network/tests/api_core_test.go +++ b/tools/docker-network/tests/api_core_test.go @@ -51,14 +51,15 @@ func Test_ValidatorsAPI(t *testing.T) { clt := d.defaultWallet.Client status := d.NodeStatus("V1") currentEpoch := clt.CommittedAPI().TimeProvider().EpochFromSlot(status.LatestAcceptedBlockSlot) + expectedValidators := d.AccountsFromNodes(d.Nodes()...) for i := 0; i < 50; i++ { wg.Add(1) go func() { defer wg.Done() - wallet, _ := d.CreateAccount(WithStakingFeature(100, 1, 0)) - + wallet, accountData := d.CreateAccount(WithStakingFeature(100, 1, 0)) + expectedValidators = append(expectedValidators, accountData.Address.Bech32(hrp)) // issue candidacy payload in the next epoch (currentEpoch + 1), in order to issue it before epochNearingThreshold d.AwaitCommitment(clt.CommittedAPI().TimeProvider().EpochEnd(currentEpoch)) blkID := d.IssueCandidacyPayloadFromAccount(wallet) @@ -68,10 +69,6 @@ func Test_ValidatorsAPI(t *testing.T) { } wg.Wait() - expectedValidators := d.AccountsFromNodes(d.Nodes()...) - for _, v := range d.defaultWallet.Accounts() { - expectedValidators = append(expectedValidators, v.Address.Bech32(hrp)) - } // get all validators of currentEpoch+1 with pageSize 10 actualValidators := getAllValidatorsOnEpoch(t, clt, 0, 10) require.ElementsMatch(t, expectedValidators, actualValidators) diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index bcbbfe6fa..45b72075c 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -413,28 +413,28 @@ func (d *DockerTestFramework) StopIssueCandidacyPayload(nodes ...*Node) { } func (d *DockerTestFramework) IssueCandidacyPayloadFromAccount(wallet *mock.Wallet) iotago.BlockID { - block, err := wallet.IssueBasicBlock(context.TODO(), "", mock.WithPayload(&iotago.CandidacyAnnouncement{})) + block, err := wallet.CreateAndSubmitBasicBlock(context.TODO(), "", mock.WithPayload(&iotago.CandidacyAnnouncement{})) require.NoError(d.Testing, err) return block.ID() } -// CreateTaggedDataBlock creates a block of a tagged data payload. +// CreateTaggedDataBlock creates and submits a block of a tagged data payload. func (d *DockerTestFramework) CreateTaggedDataBlock(wallet *mock.Wallet, tag []byte) *iotago.Block { ctx := context.TODO() - return lo.PanicOnErr(wallet.IssueBasicBlock(ctx, "", mock.WithPayload(&iotago.TaggedData{ + return lo.PanicOnErr(wallet.CreateBasicBlock(ctx, "", mock.WithPayload(&iotago.TaggedData{ Tag: tag, }))).ProtocolBlock() } -func (d *DockerTestFramework) CreateBasicOutputBlock(issuerAccountID iotago.AccountID) (*iotago.Block, *iotago.SignedTransaction, *mock.OutputData) { +func (d *DockerTestFramework) CreateBasicOutputBlock(wallet *mock.Wallet) (*iotago.Block, *iotago.SignedTransaction, *mock.OutputData) { ctx := context.Background() - fundsOutputData := d.RequestFaucetFunds(ctx, d.defaultWallet, iotago.AddressEd25519) + fundsOutputData := d.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) - signedTx := d.defaultWallet.CreateBasicOutputFromInput(fundsOutputData, issuerAccountID) - block := lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() + signedTx := wallet.CreateBasicOutputFromInput(fundsOutputData) + block := lo.PanicOnErr(d.defaultWallet.CreateBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() return block, signedTx, fundsOutputData } @@ -454,7 +454,7 @@ func (d *DockerTestFramework) CreateDelegationBlockFromInput(issuerID iotago.Acc return iotago.DelegationIDFromOutputID(outputID), outputID, - lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateFoundryBlockFromInput consumes the given basic output, then build a block of a transaction that includes a foundry output with the given mintedAmount and maxSupply. @@ -467,7 +467,7 @@ func (d *DockerTestFramework) CreateFoundryBlockFromInput(wallet *mock.Wallet, i //nolint:forcetypeassert return signedTx.Transaction.Outputs[1].(*iotago.FoundryOutput).MustFoundryID(), iotago.OutputIDFromTransactionIDAndIndex(txID, 1), - lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateNFTBlockFromInput consumes the given basic output, then build a block of a transaction that includes a NFT output with the given NFT output options. @@ -477,7 +477,7 @@ func (d *DockerTestFramework) CreateNFTBlockFromInput(wallet *mock.Wallet, input return iotago.NFTIDFromOutputID(outputID), outputID, - lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateFoundryTransitionBlockFromInput consumes the given foundry output, then build block by increasing the minted amount by 1. @@ -489,7 +489,7 @@ func (d *DockerTestFramework) CreateFoundryTransitionBlockFromInput(issuerID iot //nolint:forcetypeassert return signedTx.Transaction.Outputs[1].(*iotago.FoundryOutput).MustFoundryID(), iotago.OutputIDFromTransactionIDAndIndex(txID, 1), - lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateAccountBlockFromInput consumes the given output, which should be either an basic output with implicit address, then build block with the given account output options. Note that after the returned transaction is issued, remember to update the account information in the wallet with AddAccount(). @@ -520,7 +520,7 @@ func (d *DockerTestFramework) CreateAccountBlockFromInput(wallet *mock.Wallet, i return fullAccount, iotago.OutputIDFromTransactionIDAndIndex(txID, 0), - lo.PanicOnErr(d.defaultWallet.IssueBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateImplicitAccount requests faucet funds and creates an implicit account. It already wait until the transaction is committed and the created account is useable. @@ -561,7 +561,7 @@ func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.Accou signedTx := newWallet.TransitionImplicitAccountToAccountOutput("", []*mock.OutputData{implicitAccountOutputData}, opts...) // The account transition block should be issued by the implicit account block issuer key. - block, err := newWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + block, err := newWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) // check if the account is committed @@ -597,7 +597,7 @@ func (d *DockerTestFramework) DelegateToValidator(fromWallet *mock.Wallet, accou mock.WithDelegationStartEpoch(getDelegationStartEpoch(fromWallet.Client.LatestAPI(), fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot)), ) - d.defaultWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + d.defaultWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) delegationOutput, ok := signedTx.Transaction.Outputs[0].(*iotago.DelegationOutput) @@ -633,7 +633,7 @@ func (d *DockerTestFramework) AllotManaTo(fromWallet *mock.Wallet, to *mock.Acco to.ID, ) preAllotmentCommitmentID := fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.MustID() - block, err := fromWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + block, err := fromWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) fmt.Println("Allot mana transaction sent, blkID:", block.ID().ToHex(), ", txID:", signedTx.Transaction.MustID().ToHex(), ", slot:", block.ID().Slot()) @@ -664,7 +664,7 @@ func (d *DockerTestFramework) CreateNativeToken(fromWallet *mock.Wallet, mintedA signedTx := fromWallet.CreateFoundryAndNativeTokensFromInput(fundsOutputData, mintedAmount, maxSupply) - block, err := fromWallet.IssueBasicBlock(ctx, "", mock.WithPayload(signedTx)) + block, err := fromWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) txID := signedTx.Transaction.MustID() diff --git a/tools/docker-network/tests/mempool_invalid_signatures_test.go b/tools/docker-network/tests/mempool_invalid_signatures_test.go index a1801cf64..dd5cb3d07 100644 --- a/tools/docker-network/tests/mempool_invalid_signatures_test.go +++ b/tools/docker-network/tests/mempool_invalid_signatures_test.go @@ -36,11 +36,11 @@ func Test_MempoolInvalidSignatures(t *testing.T) { d.WaitUntilNetworkReady() - wallet, account := d.CreateAccount() + wallet, _ := d.CreateAccount() ctx := context.Background() fundsOutputData := d.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) - validTX := wallet.CreateBasicOutputFromInput(fundsOutputData, account.ID) + validTX := wallet.CreateBasicOutputFromInput(fundsOutputData) invalidTX := validTX.Clone().(*iotago.SignedTransaction) // Make validTX invalid by replacing the first unlock with an empty signature unlock. @@ -51,16 +51,16 @@ func Test_MempoolInvalidSignatures(t *testing.T) { } fmt.Println("Submitting block with invalid TX") - wallet.IssueBasicBlock(ctx, "", mock.WithPayload(invalidTX)) + wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(invalidTX)) d.AwaitTransactionState(ctx, invalidTX.Transaction.MustID(), api.TransactionStateFailed) d.AwaitTransactionFailure(ctx, invalidTX.Transaction.MustID(), api.TxFailureUnlockSignatureInvalid) fmt.Println("Submitting block with valid TX") - wallet.IssueBasicBlock(ctx, "", mock.WithPayload(validTX)) + wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(validTX)) fmt.Println("Submitting block with invalid TX (again)") - wallet.IssueBasicBlock(ctx, "", mock.WithPayload(invalidTX)) + wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(invalidTX)) d.AwaitTransactionPayloadAccepted(ctx, validTX.Transaction.MustID()) } From 19ba849aedb16bff09edb762407a0d5e720f08a0 Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 27 Mar 2024 18:08:12 +0000 Subject: [PATCH 08/23] fix linter errors --- pkg/testsuite/mock/client.go | 2 +- pkg/testsuite/mock/wallet.go | 1 + pkg/testsuite/mock/wallet_transactions.go | 1 - 3 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/testsuite/mock/client.go b/pkg/testsuite/mock/client.go index 0ba3452ae..ffc9fef35 100644 --- a/pkg/testsuite/mock/client.go +++ b/pkg/testsuite/mock/client.go @@ -244,7 +244,7 @@ func (c *TestSuiteClient) SubmitBlock(ctx context.Context, block *iotago.Block) return c.Node.RequestHandler.SubmitBlockAndAwaitRetainer(ctx, block) } -func (c *TestSuiteClient) TransactionByID(_ context.Context, txID iotago.TransactionID) (*iotago.Transaction, error) { +func (c *TestSuiteClient) TransactionByID(_ context.Context, _ iotago.TransactionID) (*iotago.Transaction, error) { panic("not implemented") } diff --git a/pkg/testsuite/mock/wallet.go b/pkg/testsuite/mock/wallet.go index 5efd54305..a8dce11cf 100644 --- a/pkg/testsuite/mock/wallet.go +++ b/pkg/testsuite/mock/wallet.go @@ -53,6 +53,7 @@ func NewAccountDataFromAccountID(accountID iotago.AccountID, addressIndex ...uin if len(addressIndex) == 0 { addressIndex = []uint32{0} } + return &AccountData{ ID: accountID, Address: accountAddress, diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index a94252124..238e56dea 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -560,7 +560,6 @@ func (w *Wallet) CreateFoundryAndNativeTokensOnOutputsFromInput(transactionName // TransitionFoundry transitions a FoundryOutput by increasing the native token amount on the output by one. func (w *Wallet) TransitionFoundry(transactionName string, foundryInput *OutputData, accountInput *OutputData) *iotago.SignedTransaction { - inputFoundry, isFoundry := foundryInput.Output.(*iotago.FoundryOutput) if !isFoundry { panic("foundry input is not *iotago.FoundryOutput") From da400f0ea5848d822a73d05c8be4c74cf5b83781 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 28 Mar 2024 15:41:07 +0000 Subject: [PATCH 09/23] fix most of mqtt problems --- pkg/testsuite/mock/blockissuer.go | 12 +++-- pkg/testsuite/mock/wallet_transactions.go | 13 +++-- tools/docker-network/tests/dockerframework.go | 52 ++++--------------- tools/docker-network/tests/eventapi_test.go | 40 ++++++++------ 4 files changed, 50 insertions(+), 67 deletions(-) diff --git a/pkg/testsuite/mock/blockissuer.go b/pkg/testsuite/mock/blockissuer.go index 653b79d55..eab6982e8 100644 --- a/pkg/testsuite/mock/blockissuer.go +++ b/pkg/testsuite/mock/blockissuer.go @@ -208,10 +208,6 @@ func (i *BlockIssuer) IssueValidationBlock(ctx context.Context, alias string, no func (i *BlockIssuer) CreateBasicBlock(ctx context.Context, alias string, opts ...options.Option[BasicBlockParams]) (*blocks.Block, error) { blockParams := options.Apply(&BasicBlockParams{BlockHeader: &BlockHeaderParams{}}, opts) - if blockParams.BlockHeader.IssuingTime == nil { - issuingTime := time.Now().UTC() - blockParams.BlockHeader.IssuingTime = &issuingTime - } blockIssuanceInfo := i.latestBlockIssuanceResponse(ctx) if blockParams.BlockHeader.References == nil { @@ -226,7 +222,6 @@ func (i *BlockIssuer) CreateBasicBlock(ctx context.Context, alias string, opts . blockBuilder.SlotCommitmentID(blockParams.BlockHeader.SlotCommitment.MustID()) blockBuilder.LatestFinalizedSlot(*blockParams.BlockHeader.LatestFinalizedSlot) - blockBuilder.IssuingTime(*blockParams.BlockHeader.IssuingTime) strongParents, exists := blockParams.BlockHeader.References[iotago.StrongParentType] require.True(i.Testing, exists && len(strongParents) > 0, "block should have strong parents (exists: %t, parents: %s)", exists, strongParents) blockBuilder.StrongParents(strongParents) @@ -244,6 +239,13 @@ func (i *BlockIssuer) CreateBasicBlock(ctx context.Context, alias string, opts . // use the rmc corresponding to the commitment used in the block blockBuilder.CalculateAndSetMaxBurnedMana(blockIssuanceInfo.LatestCommitment.ReferenceManaCost) + // set the issuing time last to ensure the timestamp is greater than that of the parents selected. + if blockParams.BlockHeader.IssuingTime == nil { + issuingTime := time.Now().UTC() + blockParams.BlockHeader.IssuingTime = &issuingTime + } + blockBuilder.IssuingTime(*blockParams.BlockHeader.IssuingTime) + priv, _ := i.keyManager.KeyPair(i.AccountData.AddressIndex) blockBuilder.Sign(i.AccountData.ID, priv) diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 238e56dea..18a9a91f5 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -130,6 +130,7 @@ func (w *Wallet) CreateDelegationFromInput(transactionName string, input *Output WithInputs(input), WithOutputs(outputStates...), WithAllotAllManaToAccount(w.CurrentSlot(), w.BlockIssuer.AccountData.ID), + WithTaggedDataPayload(&iotago.TaggedData{Tag: []byte("delegation")}), ) return signedTransaction @@ -420,6 +421,7 @@ func (w *Wallet) TransitionImplicitAccountToAccountOutput(transactionName string WithInputs(inputs...), WithOutputs(accountOutput), WithAllotAllManaToAccount(w.CurrentSlot(), implicitAccountID), + WithTaggedDataPayload(&iotago.TaggedData{Tag: []byte("account")}), ) return signedTransaction @@ -1080,6 +1082,7 @@ func (w *Wallet) CreateNFTFromInput(transactionName string, input *OutputData, o WithInputs(input), WithOutputs(nftOutput), WithAllotAllManaToAccount(w.CurrentSlot(), w.BlockIssuer.AccountData.ID), + WithTaggedDataPayload(&iotago.TaggedData{Tag: []byte("nft")}), ) } @@ -1207,12 +1210,14 @@ func (w *Wallet) registerOutputs(transactionName string, transaction *iotago.Tra } // register the output by both name and ID w.outputs[fmt.Sprintf("%s:%d", transactionName, outputID.Index())] = &OutputData{ - ID: actualOutputID, - Output: clonedOutput, + ID: actualOutputID, + Output: clonedOutput, + Address: addressUC.Address, } w.outputsByID[actualOutputID] = &OutputData{ - ID: actualOutputID, - Output: clonedOutput, + ID: actualOutputID, + Output: clonedOutput, + Address: addressUC.Address, } break diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 45b72075c..016000b9c 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -434,27 +434,28 @@ func (d *DockerTestFramework) CreateBasicOutputBlock(wallet *mock.Wallet) (*iota fundsOutputData := d.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) signedTx := wallet.CreateBasicOutputFromInput(fundsOutputData) - block := lo.PanicOnErr(d.defaultWallet.CreateBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() + block, err := wallet.CreateBasicBlock(ctx, "", mock.WithPayload(signedTx)) + require.NoError(d.Testing, err) - return block, signedTx, fundsOutputData + return block.ProtocolBlock(), signedTx, fundsOutputData } // CreateDelegationBlockFromInput consumes the given basic output, then build a block of a transaction that includes a delegation output, in order to delegate the given validator. -func (d *DockerTestFramework) CreateDelegationBlockFromInput(issuerID iotago.AccountID, accountAdddress *iotago.AccountAddress, input *mock.OutputData) (iotago.DelegationID, iotago.OutputID, *iotago.Block) { +func (d *DockerTestFramework) CreateDelegationBlockFromInput(wallet *mock.Wallet, accountAdddress *iotago.AccountAddress, input *mock.OutputData) (iotago.DelegationID, iotago.OutputID, *iotago.Block) { ctx := context.TODO() - clt := d.defaultWallet.Client + clt := wallet.Client - signedTx := d.defaultWallet.CreateDelegationFromInput( + signedTx := wallet.CreateDelegationFromInput( "", input, mock.WithDelegatedValidatorAddress(accountAdddress), - mock.WithDelegationStartEpoch(getDelegationStartEpoch(clt.LatestAPI(), d.defaultWallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot)), + mock.WithDelegationStartEpoch(getDelegationStartEpoch(clt.LatestAPI(), wallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot)), ) outputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) return iotago.DelegationIDFromOutputID(outputID), outputID, - lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(wallet.CreateBasicBlock(ctx, "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateFoundryBlockFromInput consumes the given basic output, then build a block of a transaction that includes a foundry output with the given mintedAmount and maxSupply. @@ -467,7 +468,7 @@ func (d *DockerTestFramework) CreateFoundryBlockFromInput(wallet *mock.Wallet, i //nolint:forcetypeassert return signedTx.Transaction.Outputs[1].(*iotago.FoundryOutput).MustFoundryID(), iotago.OutputIDFromTransactionIDAndIndex(txID, 1), - lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(wallet.CreateBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateNFTBlockFromInput consumes the given basic output, then build a block of a transaction that includes a NFT output with the given NFT output options. @@ -477,7 +478,7 @@ func (d *DockerTestFramework) CreateNFTBlockFromInput(wallet *mock.Wallet, input return iotago.NFTIDFromOutputID(outputID), outputID, - lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(wallet.CreateBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } // CreateFoundryTransitionBlockFromInput consumes the given foundry output, then build block by increasing the minted amount by 1. @@ -492,37 +493,6 @@ func (d *DockerTestFramework) CreateFoundryTransitionBlockFromInput(issuerID iot lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } -// CreateAccountBlockFromInput consumes the given output, which should be either an basic output with implicit address, then build block with the given account output options. Note that after the returned transaction is issued, remember to update the account information in the wallet with AddAccount(). -func (d *DockerTestFramework) CreateAccountBlockFromInput(wallet *mock.Wallet, inputID iotago.OutputID) (*mock.AccountData, iotago.OutputID, *iotago.Block) { - input := wallet.Output(inputID) - - // check if the given input is an BasicOutput with implicit address - implicitOutput, ok := input.Output.(*iotago.BasicOutput) - require.True(d.Testing, ok) - require.Equal(d.Testing, iotago.AddressImplicitAccountCreation, implicitOutput.UnlockConditionSet().Address().Address.Type()) - accAddress := iotago.AccountAddressFromOutputID(inputID) - - signedTx := wallet.TransitionImplicitAccountToAccountOutput( - "", - []*mock.OutputData{input}, - ) - txID, err := signedTx.Transaction.ID() - require.NoError(d.Testing, err) - - accountOutput := signedTx.Transaction.Outputs[0].(*iotago.AccountOutput) - fullAccount := &mock.AccountData{ - ID: accountOutput.AccountID, - Address: accAddress, - AddressIndex: wallet.Output(inputID).AddressIndex, - Output: accountOutput, - OutputID: iotago.OutputIDFromTransactionIDAndIndex(txID, 0), - } - - return fullAccount, - iotago.OutputIDFromTransactionIDAndIndex(txID, 0), - lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() -} - // CreateImplicitAccount requests faucet funds and creates an implicit account. It already wait until the transaction is committed and the created account is useable. func (d *DockerTestFramework) CreateImplicitAccount(ctx context.Context) (*mock.Wallet, *mock.OutputData) { newWallet := mock.NewWallet(d.Testing, "", d.defaultWallet.Client, &DockerWalletClock{client: d.defaultWallet.Client}) @@ -597,7 +567,7 @@ func (d *DockerTestFramework) DelegateToValidator(fromWallet *mock.Wallet, accou mock.WithDelegationStartEpoch(getDelegationStartEpoch(fromWallet.Client.LatestAPI(), fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot)), ) - d.defaultWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) + fromWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) delegationOutput, ok := signedTx.Transaction.Outputs[0].(*iotago.DelegationOutput) diff --git a/tools/docker-network/tests/eventapi_test.go b/tools/docker-network/tests/eventapi_test.go index 553ca1e2d..a4fb98d06 100644 --- a/tools/docker-network/tests/eventapi_test.go +++ b/tools/docker-network/tests/eventapi_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" + "github.com/iotaledger/iota-core/pkg/testsuite/mock" iotago "github.com/iotaledger/iota.go/v4" "github.com/iotaledger/iota.go/v4/api" ) @@ -173,15 +174,15 @@ func test_DelegationTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramewo defer eventClt.Close() // create an account to issue blocks - wallet, account := e.dockerFramework.CreateAccount() + wallet, _ := e.dockerFramework.CreateAccount() fundsOutputData := e.dockerFramework.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) // prepare data blocks to send - delegationId, outputId, blk := e.dockerFramework.CreateDelegationBlockFromInput(account.ID, e.dockerFramework.Node("V2").AccountAddress(t), fundsOutputData) + delegationId, outputId, blk := e.dockerFramework.CreateDelegationBlockFromInput(wallet, e.dockerFramework.Node("V2").AccountAddress(t), fundsOutputData) expectedBlocks := map[string]*iotago.Block{ blk.MustID().ToHex(): blk, } - delegationOutput := e.dockerFramework.defaultWallet.Output(outputId) + delegationOutput := wallet.Output(outputId) asserts := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, @@ -234,11 +235,16 @@ func test_AccountTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) wallet, implicitAccount := e.dockerFramework.CreateImplicitAccount(ctx) // prepare fullAccount transaction block to send - fullAccount, outputId, blk := e.dockerFramework.CreateAccountBlockFromInput(wallet, implicitAccount.ID) + signedTx := wallet.TransitionImplicitAccountToAccountOutput("", []*mock.OutputData{implicitAccount}) + // The account transition block should be issued by the implicit account block issuer key. + blk, err := wallet.CreateBasicBlock(ctx, "", mock.WithPayload(signedTx)) + require.NoError(e.Testing, err) expectedBlocks := map[string]*iotago.Block{ - blk.MustID().ToHex(): blk, + blk.ProtocolBlock().MustID().ToHex(): blk.ProtocolBlock(), } - accountOutput := e.dockerFramework.defaultWallet.Output(outputId) + accountOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) + accountOutput := signedTx.Transaction.Outputs[0].(*iotago.AccountOutput) + accountAddress := (accountOutput.AccountID).ToAddress().(*iotago.AccountAddress) assertions := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, @@ -246,15 +252,15 @@ func test_AccountTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) func() { e.AssertBlockMetadataAcceptedBlocks(ctx, eventClt, expectedBlocks) }, func() { e.AssertBlockMetadataConfirmedBlocks(ctx, eventClt, expectedBlocks) }, func() { e.AssertTransactionBlocksByTag(ctx, eventClt, expectedBlocks, []byte("account")) }, - func() { e.AssertTransactionMetadataByTransactionID(ctx, eventClt, outputId.TransactionID()) }, - func() { e.AssertTransactionMetadataIncludedBlocks(ctx, eventClt, outputId.TransactionID()) }, - func() { e.AssertAccountOutput(ctx, eventClt, fullAccount.ID) }, - func() { e.AssertOutput(ctx, eventClt, outputId) }, + func() { e.AssertTransactionMetadataByTransactionID(ctx, eventClt, signedTx.Transaction.MustID()) }, + func() { e.AssertTransactionMetadataIncludedBlocks(ctx, eventClt, signedTx.Transaction.MustID()) }, + func() { e.AssertAccountOutput(ctx, eventClt, accountOutput.AccountID) }, + func() { e.AssertOutput(ctx, eventClt, accountOutputID) }, func() { - e.AssertOutputsWithMetadataByUnlockConditionAndAddress(ctx, eventClt, api.EventAPIUnlockConditionAny, accountOutput.Address) + e.AssertOutputsWithMetadataByUnlockConditionAndAddress(ctx, eventClt, api.EventAPIUnlockConditionAny, accountAddress) }, func() { - e.AssertOutputsWithMetadataByUnlockConditionAndAddress(ctx, eventClt, api.EventAPIUnlockConditionAddress, accountOutput.Address) + e.AssertOutputsWithMetadataByUnlockConditionAndAddress(ctx, eventClt, api.EventAPIUnlockConditionAddress, accountAddress) }, } @@ -264,7 +270,7 @@ func test_AccountTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) } // wait until all topics starts listening - err := e.AwaitEventAPITopics(t, cancel, totalTopics) + err = e.AwaitEventAPITopics(t, cancel, totalTopics) require.NoError(t, err) // issue blocks @@ -296,7 +302,7 @@ func test_FoundryTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) expectedBlocks := map[string]*iotago.Block{ blk.MustID().ToHex(): blk, } - foundryOutput := e.dockerFramework.defaultWallet.Output(outputId) + foundryOutput := wallet.Output(outputId) assertions := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, @@ -349,14 +355,14 @@ func test_NFTTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) { { wallet, _ := e.dockerFramework.CreateAccount() - fundsOutputID := e.dockerFramework.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) + fundsOutputData := e.dockerFramework.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) // prepare foundry output block - nftId, outputId, blk := e.dockerFramework.CreateNFTBlockFromInput(wallet, fundsOutputID) + nftId, outputId, blk := e.dockerFramework.CreateNFTBlockFromInput(wallet, fundsOutputData) expectedBlocks := map[string]*iotago.Block{ blk.MustID().ToHex(): blk, } - nftOutput := e.dockerFramework.defaultWallet.Output(outputId) + nftOutput := wallet.Output(outputId) assertions := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, From 17c1b8d851dd41e1550cf998b3b7d89fc3a7a057 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 28 Mar 2024 20:14:10 +0000 Subject: [PATCH 10/23] fix mqtt tests but with peering issue --- tools/docker-network/tests/dockerframework.go | 66 +++++++++++-------- tools/docker-network/tests/eventapi_test.go | 31 ++++----- 2 files changed, 49 insertions(+), 48 deletions(-) diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 75af4e553..d20d22a60 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -502,6 +502,37 @@ func (d *DockerTestFramework) CreateFoundryTransitionBlockFromInput(issuerID iot lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() } +// CreateAccountBlockFromInput consumes the given output, which should be either an basic output with implicit address, then build block with the given account output options. Note that after the returned transaction is issued, remember to update the account information in the wallet with AddAccount(). +func (d *DockerTestFramework) CreateAccountBlock(opts ...options.Option[builder.AccountOutputBuilder]) (*mock.AccountData, *mock.Wallet, *iotago.SignedTransaction, *iotago.Block) { + // create an implicit account by requesting faucet funds + ctx := context.TODO() + newWallet, implicitAccountOutputData := d.CreateImplicitAccount(ctx) + + var implicitBlockIssuerKey iotago.BlockIssuerKey = iotago.Ed25519PublicKeyHashBlockIssuerKeyFromImplicitAccountCreationAddress(newWallet.ImplicitAccountCreationAddress()) + opts = append(opts, mock.WithBlockIssuerFeature( + iotago.NewBlockIssuerKeys(implicitBlockIssuerKey), + iotago.MaxSlotIndex, + )) + signedTx := newWallet.TransitionImplicitAccountToAccountOutput("", []*mock.OutputData{implicitAccountOutputData}, opts...) + + // The account transition block should be issued by the implicit account block issuer key. + block, err := newWallet.CreateBasicBlock(ctx, "", mock.WithPayload(signedTx)) + require.NoError(d.Testing, err) + accOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) + accOutput := signedTx.Transaction.Outputs[0].(*iotago.AccountOutput) + accAddress := (accOutput.AccountID).ToAddress().(*iotago.AccountAddress) + + accountOutputData := &mock.AccountData{ + ID: accOutput.AccountID, + Address: accAddress, + Output: accOutput, + OutputID: accOutputID, + AddressIndex: implicitAccountOutputData.AddressIndex, + } + + return accountOutputData, newWallet, signedTx, block.ProtocolBlock() +} + // CreateImplicitAccount requests faucet funds and creates an implicit account. It already wait until the transaction is committed and the created account is useable. func (d *DockerTestFramework) CreateImplicitAccount(ctx context.Context) (*mock.Wallet, *mock.OutputData) { newWallet := mock.NewWallet(d.Testing, "", d.defaultWallet.Client, &DockerWalletClock{client: d.defaultWallet.Client}) @@ -527,40 +558,17 @@ func (d *DockerTestFramework) CreateImplicitAccount(ctx context.Context) (*mock. // CreateAccount creates an new account from implicit one to full one, it already wait until the transaction is committed and the created account is useable. func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.AccountOutputBuilder]) (*mock.Wallet, *mock.AccountData) { - // create an implicit account by requesting faucet funds ctx := context.TODO() - newWallet, implicitAccountOutputData := d.CreateImplicitAccount(ctx) - clt := newWallet.Client - - var implicitBlockIssuerKey iotago.BlockIssuerKey = iotago.Ed25519PublicKeyHashBlockIssuerKeyFromImplicitAccountCreationAddress(newWallet.ImplicitAccountCreationAddress()) - opts = append(opts, mock.WithBlockIssuerFeature( - iotago.NewBlockIssuerKeys(implicitBlockIssuerKey), - iotago.MaxSlotIndex, - )) - signedTx := newWallet.TransitionImplicitAccountToAccountOutput("", []*mock.OutputData{implicitAccountOutputData}, opts...) - - // The account transition block should be issued by the implicit account block issuer key. - block, err := newWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) - require.NoError(d.Testing, err) - - // check if the account is committed - accOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) - accOutput := signedTx.Transaction.Outputs[0].(*iotago.AccountOutput) - accAddress := (accOutput.AccountID).ToAddress().(*iotago.AccountAddress) - d.CheckAccountStatus(ctx, block.ID(), signedTx.Transaction.MustID(), accOutputID, accAddress, true) + accountData, newWallet, signedTx, block := d.CreateAccountBlock(opts...) + d.SubmitBlock(ctx, block) + d.CheckAccountStatus(ctx, block.MustID(), signedTx.Transaction.MustID(), accountData.OutputID, accountData.Address, true) // update the wallet with the new account data - newWallet.SetBlockIssuer(&mock.AccountData{ - ID: accOutput.AccountID, - Address: accAddress, - Output: accOutput, - OutputID: accOutputID, - AddressIndex: implicitAccountOutputData.AddressIndex, - }) + newWallet.SetBlockIssuer(accountData) - fmt.Printf("Account created, Bech addr: %s, in txID: %s, slot: %d\n", accAddress.Bech32(clt.CommittedAPI().ProtocolParameters().Bech32HRP()), signedTx.Transaction.MustID().ToHex(), block.ID().Slot()) + fmt.Printf("Account created, Bech addr: %s", accountData.Address.Bech32(newWallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP())) - return newWallet, newWallet.Account(accOutput.AccountID) + return newWallet, newWallet.Account(accountData.ID) } // DelegateToValidator requests faucet funds and delegate the UTXO output to the validator. diff --git a/tools/docker-network/tests/eventapi_test.go b/tools/docker-network/tests/eventapi_test.go index a4fb98d06..ca57e7a88 100644 --- a/tools/docker-network/tests/eventapi_test.go +++ b/tools/docker-network/tests/eventapi_test.go @@ -10,7 +10,6 @@ import ( "github.com/stretchr/testify/require" - "github.com/iotaledger/iota-core/pkg/testsuite/mock" iotago "github.com/iotaledger/iota.go/v4" "github.com/iotaledger/iota.go/v4/api" ) @@ -232,19 +231,11 @@ func test_AccountTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) // implicit account transition { - wallet, implicitAccount := e.dockerFramework.CreateImplicitAccount(ctx) - - // prepare fullAccount transaction block to send - signedTx := wallet.TransitionImplicitAccountToAccountOutput("", []*mock.OutputData{implicitAccount}) - // The account transition block should be issued by the implicit account block issuer key. - blk, err := wallet.CreateBasicBlock(ctx, "", mock.WithPayload(signedTx)) - require.NoError(e.Testing, err) + accountData, wallet, _, blk := e.dockerFramework.CreateAccountBlock() expectedBlocks := map[string]*iotago.Block{ - blk.ProtocolBlock().MustID().ToHex(): blk.ProtocolBlock(), + blk.MustID().ToHex(): blk, } - accountOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) - accountOutput := signedTx.Transaction.Outputs[0].(*iotago.AccountOutput) - accountAddress := (accountOutput.AccountID).ToAddress().(*iotago.AccountAddress) + accountOutputData := wallet.Output(accountData.OutputID) assertions := []func(){ func() { e.AssertTransactionBlocks(ctx, eventClt, expectedBlocks) }, @@ -252,15 +243,17 @@ func test_AccountTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) func() { e.AssertBlockMetadataAcceptedBlocks(ctx, eventClt, expectedBlocks) }, func() { e.AssertBlockMetadataConfirmedBlocks(ctx, eventClt, expectedBlocks) }, func() { e.AssertTransactionBlocksByTag(ctx, eventClt, expectedBlocks, []byte("account")) }, - func() { e.AssertTransactionMetadataByTransactionID(ctx, eventClt, signedTx.Transaction.MustID()) }, - func() { e.AssertTransactionMetadataIncludedBlocks(ctx, eventClt, signedTx.Transaction.MustID()) }, - func() { e.AssertAccountOutput(ctx, eventClt, accountOutput.AccountID) }, - func() { e.AssertOutput(ctx, eventClt, accountOutputID) }, func() { - e.AssertOutputsWithMetadataByUnlockConditionAndAddress(ctx, eventClt, api.EventAPIUnlockConditionAny, accountAddress) + e.AssertTransactionMetadataByTransactionID(ctx, eventClt, accountData.OutputID.TransactionID()) + }, + func() { e.AssertTransactionMetadataIncludedBlocks(ctx, eventClt, accountData.OutputID.TransactionID()) }, + func() { e.AssertAccountOutput(ctx, eventClt, accountData.ID) }, + func() { e.AssertOutput(ctx, eventClt, accountData.OutputID) }, + func() { + e.AssertOutputsWithMetadataByUnlockConditionAndAddress(ctx, eventClt, api.EventAPIUnlockConditionAny, accountOutputData.Address) }, func() { - e.AssertOutputsWithMetadataByUnlockConditionAndAddress(ctx, eventClt, api.EventAPIUnlockConditionAddress, accountAddress) + e.AssertOutputsWithMetadataByUnlockConditionAndAddress(ctx, eventClt, api.EventAPIUnlockConditionAddress, accountOutputData.Address) }, } @@ -270,7 +263,7 @@ func test_AccountTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) } // wait until all topics starts listening - err = e.AwaitEventAPITopics(t, cancel, totalTopics) + err := e.AwaitEventAPITopics(t, cancel, totalTopics) require.NoError(t, err) // issue blocks From e13267786c098f6d8d3effe1d986065e94a11829 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 28 Mar 2024 20:32:33 +0000 Subject: [PATCH 11/23] fix nil pointer address --- pkg/testsuite/mock/wallet_transactions.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 18a9a91f5..46ac40e69 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -1209,15 +1209,19 @@ func (w *Wallet) registerOutputs(transactionName string, transaction *iotago.Tra } } // register the output by both name and ID + var address iotago.Address + if addressUC != nil { + address = addressUC.Address + } w.outputs[fmt.Sprintf("%s:%d", transactionName, outputID.Index())] = &OutputData{ ID: actualOutputID, Output: clonedOutput, - Address: addressUC.Address, + Address: address, } w.outputsByID[actualOutputID] = &OutputData{ ID: actualOutputID, Output: clonedOutput, - Address: addressUC.Address, + Address: address, } break From a596ff5b6906d3e0571db265ae1a36d5d9cdd1af Mon Sep 17 00:00:00 2001 From: Andrew Date: Fri, 29 Mar 2024 22:23:20 +0000 Subject: [PATCH 12/23] Daria comments --- pkg/testsuite/mock/node.go | 4 +- pkg/testsuite/mock/wallet.go | 57 ++++++++++++++----- pkg/testsuite/mock/wallet_transactions.go | 5 +- pkg/testsuite/testsuite.go | 2 +- tools/docker-network/tests/dockerframework.go | 5 +- 5 files changed, 49 insertions(+), 24 deletions(-) diff --git a/pkg/testsuite/mock/node.go b/pkg/testsuite/mock/node.go index fe1940357..5053947b4 100644 --- a/pkg/testsuite/mock/node.go +++ b/pkg/testsuite/mock/node.go @@ -101,7 +101,7 @@ func NewNode(t *testing.T, parentLogger log.Logger, net *Network, partition stri var validator *BlockIssuer if isValidator { - validator = NewBlockIssuer(t, name, keyManager, nil, NewAccountDataFromAccountID(accountID), isValidator) + validator = NewBlockIssuer(t, name, keyManager, nil, NewAccountData(accountID), isValidator) } else { validator = nil } @@ -148,7 +148,7 @@ func (n *Node) Initialize(failOnBlockFiltered bool, opts ...options.Option[proto n.Client = NewTestSuiteClient(n) if n.isValidator { - n.Validator = NewBlockIssuer(n.Testing, n.Name, n.KeyManager, n.Client, NewAccountDataFromAccountID(accountID), n.isValidator) + n.Validator = NewBlockIssuer(n.Testing, n.Name, n.KeyManager, n.Client, NewAccountData(accountID), n.isValidator) } n.hookEvents() n.hookEngineEvents(failOnBlockFiltered) diff --git a/pkg/testsuite/mock/wallet.go b/pkg/testsuite/mock/wallet.go index a8dce11cf..4a4c0918e 100644 --- a/pkg/testsuite/mock/wallet.go +++ b/pkg/testsuite/mock/wallet.go @@ -45,19 +45,20 @@ type AccountData struct { OutputID iotago.OutputID } -func NewAccountDataFromAccountID(accountID iotago.AccountID, addressIndex ...uint32) *AccountData { +func NewAccountData(accountID iotago.AccountID, optAddressIndex ...uint32) *AccountData { accountAddress, ok := accountID.ToAddress().(*iotago.AccountAddress) if !ok { panic(ierrors.Errorf("accountID %s is not an account address", accountID.ToHex())) } - if len(addressIndex) == 0 { - addressIndex = []uint32{0} + var addressIndex uint32 + if len(optAddressIndex) == 0 { + addressIndex = 0 } return &AccountData{ ID: accountID, Address: accountAddress, - AddressIndex: addressIndex[0], + AddressIndex: addressIndex, } } @@ -71,6 +72,10 @@ type TestSuiteWalletClock struct { currentSlot iotago.SlotIndex } +func NewTestSuiteWalletClock() *TestSuiteWalletClock { + return &TestSuiteWalletClock{} +} + func (c *TestSuiteWalletClock) SetCurrentSlot(slot iotago.SlotIndex) { c.currentSlot = slot } @@ -99,8 +104,8 @@ type Wallet struct { outputsByID map[iotago.OutputID]*OutputData transactions map[string]*iotago.Transaction - accounts map[iotago.AccountID]*AccountData - accountsLock sync.RWMutex + accounts map[iotago.AccountID]*AccountData + mutex sync.RWMutex clock WalletClock } @@ -126,7 +131,7 @@ func NewWallet(t *testing.T, name string, client Client, clock WalletClock, keyM accounts: make(map[iotago.AccountID]*AccountData), transactions: make(map[string]*iotago.Transaction), keyManager: km, - BlockIssuer: NewBlockIssuer(t, name, km, client, NewAccountDataFromAccountID(blockIssuerID, blockIssuerAddressIndex), false), + BlockIssuer: NewBlockIssuer(t, name, km, client, NewAccountData(blockIssuerID, blockIssuerAddressIndex), false), clock: clock, } } @@ -149,11 +154,17 @@ func (w *Wallet) CurrentSlot() iotago.SlotIndex { } func (w *Wallet) AddOutput(outputName string, output *OutputData) { + w.mutex.Lock() + defer w.mutex.Unlock() + w.outputs[outputName] = output w.outputsByID[output.ID] = output } func (w *Wallet) Balance() iotago.BaseToken { + w.mutex.RLock() + defer w.mutex.RUnlock() + var balance iotago.BaseToken for _, outputData := range w.outputs { balance += outputData.Output.BaseTokenAmount() @@ -162,7 +173,24 @@ func (w *Wallet) Balance() iotago.BaseToken { return balance } +func (w *Wallet) Outputs() []*OutputData { + w.mutex.RLock() + defer w.mutex.RUnlock() + + return lo.Values(w.outputs) +} + +func (w *Wallet) OutputNames() []string { + w.mutex.RLock() + defer w.mutex.RUnlock() + + return lo.Keys(w.outputs) +} + func (w *Wallet) OutputData(outputName string) *OutputData { + w.mutex.RLock() + defer w.mutex.RUnlock() + output, exists := w.outputs[outputName] if !exists { panic(ierrors.Errorf("output %s not registered in wallet %s", outputName, w.Name)) @@ -172,6 +200,9 @@ func (w *Wallet) OutputData(outputName string) *OutputData { } func (w *Wallet) Output(outputID iotago.OutputID) *OutputData { + w.mutex.RLock() + defer w.mutex.RUnlock() + output, exists := w.outputsByID[outputID] if !exists { panic(ierrors.Errorf("output %s not registered in wallet %s", outputID.ToHex(), w.Name)) @@ -207,8 +238,8 @@ func (w *Wallet) TransactionID(alias string) iotago.TransactionID { } func (w *Wallet) Account(accountID iotago.AccountID) *AccountData { - w.accountsLock.RLock() - defer w.accountsLock.RUnlock() + w.mutex.RLock() + defer w.mutex.RUnlock() acc, exists := w.accounts[accountID] if !exists { @@ -219,14 +250,12 @@ func (w *Wallet) Account(accountID iotago.AccountID) *AccountData { } func (w *Wallet) Accounts(accountIDs ...iotago.AccountID) []*AccountData { - w.accountsLock.RLock() - defer w.accountsLock.RUnlock() + w.mutex.RLock() + defer w.mutex.RUnlock() accounts := make([]*AccountData, 0) if len(accountIDs) == 0 { - for _, acc := range w.accounts { - accounts = append(accounts, acc) - } + return lo.Values(w.accounts) } for _, id := range accountIDs { diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 46ac40e69..3952d9a32 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -207,10 +207,7 @@ func (w *Wallet) DelayedClaimingTransition(transactionName string, inputName str } func (w *Wallet) TransitionAccount(transactionName string, inputName string, opts ...options.Option[builder.AccountOutputBuilder]) *iotago.SignedTransaction { - input, exists := w.outputs[inputName] - if !exists { - panic(fmt.Sprintf("account with alias %s does not exist", inputName)) - } + input := w.OutputData(inputName) accountOutput, ok := input.Output.Clone().(*iotago.AccountOutput) if !ok { diff --git a/pkg/testsuite/testsuite.go b/pkg/testsuite/testsuite.go index ab08581b5..12e0b5839 100644 --- a/pkg/testsuite/testsuite.go +++ b/pkg/testsuite/testsuite.go @@ -462,7 +462,7 @@ func (t *TestSuite) DefaultWallet() *mock.Wallet { } func (t *TestSuite) AddWallet(name string, node *mock.Node, accountID iotago.AccountID, keyManager ...*wallet.KeyManager) *mock.Wallet { - newWallet := mock.NewWallet(t.Testing, name, &mock.TestSuiteClient{Node: node}, &mock.TestSuiteWalletClock{}, keyManager...) + newWallet := mock.NewWallet(t.Testing, name, mock.NewTestSuiteClient(node), mock.NewTestSuiteWalletClock(), keyManager...) newWallet.SetBlockIssuer(&mock.AccountData{ID: accountID}) t.wallets.Set(name, newWallet) newWallet.SetCurrentSlot(t.currentSlot) diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index d20d22a60..cedab093e 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -71,6 +71,7 @@ type DockerWalletClock struct { } func (c *DockerWalletClock) SetCurrentSlot(slot iotago.SlotIndex) { + panic("Cannot set current slot in DockerWalletClock, the slot is set by time.Now()") } func (c *DockerWalletClock) CurrentSlot() iotago.SlotIndex { @@ -438,12 +439,10 @@ func (d *DockerTestFramework) CreateTaggedDataBlock(wallet *mock.Wallet, tag []b } func (d *DockerTestFramework) CreateBasicOutputBlock(wallet *mock.Wallet) (*iotago.Block, *iotago.SignedTransaction, *mock.OutputData) { - ctx := context.Background() - fundsOutputData := d.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) signedTx := wallet.CreateBasicOutputFromInput(fundsOutputData) - block, err := wallet.CreateBasicBlock(ctx, "", mock.WithPayload(signedTx)) + block, err := wallet.CreateBasicBlock(context.Background(), "", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) return block.ProtocolBlock(), signedTx, fundsOutputData From f17f25cca54663ffaad7f29d144eb560826afe37 Mon Sep 17 00:00:00 2001 From: Andrew Date: Fri, 29 Mar 2024 22:24:10 +0000 Subject: [PATCH 13/23] missing context --- tools/docker-network/tests/dockerframework.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index cedab093e..522e0f974 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -439,7 +439,7 @@ func (d *DockerTestFramework) CreateTaggedDataBlock(wallet *mock.Wallet, tag []b } func (d *DockerTestFramework) CreateBasicOutputBlock(wallet *mock.Wallet) (*iotago.Block, *iotago.SignedTransaction, *mock.OutputData) { - fundsOutputData := d.RequestFaucetFunds(ctx, wallet, iotago.AddressEd25519) + fundsOutputData := d.RequestFaucetFunds(context.Background(), wallet, iotago.AddressEd25519) signedTx := wallet.CreateBasicOutputFromInput(fundsOutputData) block, err := wallet.CreateBasicBlock(context.Background(), "", mock.WithPayload(signedTx)) From ac51ff99a114c972bea3c1cf4dea74565f05727e Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 17 Apr 2024 12:48:37 +0100 Subject: [PATCH 14/23] fix some merge errors --- pkg/tests/accounts_test.go | 2 +- pkg/tests/reward_test.go | 20 ++-- pkg/testsuite/mock/wallet_transactions.go | 52 ++++++++--- tools/docker-network/tests/api_core.go | 11 ++- .../tests/committeerotation_test.go | 9 +- tools/docker-network/tests/dockerframework.go | 2 +- tools/docker-network/tests/rewards_test.go | 93 +++++++++---------- 7 files changed, 107 insertions(+), 82 deletions(-) diff --git a/pkg/tests/accounts_test.go b/pkg/tests/accounts_test.go index 3a7dc116e..ac4505fa0 100644 --- a/pkg/tests/accounts_test.go +++ b/pkg/tests/accounts_test.go @@ -304,7 +304,7 @@ func Test_StakeDelegateAndDelayedClaim(t *testing.T) { // transition a delegation output to a delayed claiming state block3Slot := ts.CurrentSlot() - tx3 := ts.DefaultWallet().DelayedClaimingTransition("TX3", "TX2:0", 0) + tx3 := ts.DefaultWallet().DelayedClaimingTransition("TX3", ts.DefaultWallet().OutputData("TX2:0"), 0) block3 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block3", ts.DefaultWallet(), tx3, mock.WithStrongParents(latestParents...))) latestParents = ts.CommitUntilSlot(block3Slot, block3.ID()) diff --git a/pkg/tests/reward_test.go b/pkg/tests/reward_test.go index 9a7bb8f93..321bffd05 100644 --- a/pkg/tests/reward_test.go +++ b/pkg/tests/reward_test.go @@ -84,7 +84,7 @@ func Test_Delegation_DestroyOutputWithoutRewards(t *testing.T) { latestParents := ts.CommitUntilSlot(block1Slot, block1.ID()) block2Slot := ts.CurrentSlot() - tx2 := ts.DefaultWallet().ClaimDelegatorRewards("TX2", "TX1:0") + tx2 := ts.DefaultWallet().ClaimDelegatorRewards("TX2", ts.DefaultWallet().OutputData("TX1:0")) block2 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block2", ts.DefaultWallet(), tx2, mock.WithStrongParents(latestParents...))) ts.CommitUntilSlot(block2Slot, block2.ID()) @@ -124,13 +124,13 @@ func Test_Delegation_DelayedClaimingDestroyOutputWithoutRewards(t *testing.T) { delegationEndEpoch = futureBoundedEpochIndex + 1 } - tx2 := ts.DefaultWallet().DelayedClaimingTransition("TX2", "TX1:0", delegationEndEpoch) + tx2 := ts.DefaultWallet().DelayedClaimingTransition("TX2", ts.DefaultWallet().OutputData("TX1:0"), delegationEndEpoch) block2 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block2", ts.DefaultWallet(), tx2, mock.WithStrongParents(block1.ID()))) latestParents := ts.CommitUntilSlot(block1_2Slot, block2.ID()) // CLAIM ZERO REWARDS block3Slot := ts.CurrentSlot() - tx3 := ts.DefaultWallet().ClaimDelegatorRewards("TX3", "TX2:0") + tx3 := ts.DefaultWallet().ClaimDelegatorRewards("TX3", ts.DefaultWallet().OutputData("TX2:0")) block3 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block3", ts.DefaultWallet(), tx3, mock.WithStrongParents(latestParents...))) ts.CommitUntilSlot(block3Slot, block3.ID()) @@ -183,7 +183,7 @@ func Test_Account_RemoveStakingFeatureWithoutRewards(t *testing.T) { // REMOVE STAKING FEATURE AND CLAIM ZERO REWARDS block2Slot := ts.CurrentSlot() - tx2 := ts.DefaultWallet().ClaimValidatorRewards("TX2", "TX1:0") + tx2 := ts.DefaultWallet().ClaimValidatorRewards("TX2", ts.DefaultWallet().OutputData("TX1:0")) block2 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block2", ts.DefaultWallet(), tx2, mock.WithStrongParents(latestParents...))) ts.CommitUntilSlot(block2Slot, block2.ID()) @@ -351,7 +351,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { ) block5 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block5", ts.DefaultWallet(), tx5, mock.WithStrongParents(latestParents...))) blockIssuanceResp = ts.DefaultWallet().GetNewBlockIssuanceResponse() - tx6 := ts.DefaultWallet().DelayedClaimingTransition("TX6", "TX5:0", ts.DefaultWallet().DelegationEndFromSlot(block5_6Slot, blockIssuanceResp.LatestCommitment.Slot)) + tx6 := ts.DefaultWallet().DelayedClaimingTransition("TX6", ts.DefaultWallet().OutputData("TX5:0"), ts.DefaultWallet().DelegationEndFromSlot(block5_6Slot, blockIssuanceResp.LatestCommitment.Slot)) block6 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block6", ts.DefaultWallet(), tx6, mock.WithStrongParents(block5.ID()))) latestParents = ts.CommitUntilSlot(block5_6Slot, block6.ID()) @@ -375,7 +375,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { latestParents = ts.CommitUntilSlot(block7_8Slot, block7.ID()) - tx8 := ts.DefaultWallet().ClaimDelegatorRewards("TX8", "TX7:0") + tx8 := ts.DefaultWallet().ClaimDelegatorRewards("TX8", ts.DefaultWallet().OutputData("TX7:0")) block8 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block8", ts.DefaultWallet(), tx8, mock.WithStrongParents(latestParents...))) block8Slot := ts.CurrentSlot() @@ -387,7 +387,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { // STEP 6: REMOVE A DELEGATION BY TRANSITIONING TO DELAYED CLAIMING. block9Slot := ts.CurrentSlot() blockIssuanceResp = ts.DefaultWallet().GetNewBlockIssuanceResponse() - tx9 := ts.DefaultWallet().DelayedClaimingTransition("TX9", "TX4:0", ts.DefaultWallet().DelegationEndFromSlot(block9Slot, blockIssuanceResp.LatestCommitment.Slot)) + tx9 := ts.DefaultWallet().DelayedClaimingTransition("TX9", ts.DefaultWallet().OutputData("TX4:0"), ts.DefaultWallet().DelegationEndFromSlot(block9Slot, blockIssuanceResp.LatestCommitment.Slot)) block9 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block9", ts.DefaultWallet(), tx9, mock.WithStrongParents(latestParents...))) // Commit until the claiming epoch so we can remove the staking feature from the account in the next step. latestParents = ts.CommitUntilSlot(block9Slot, block9.ID()) @@ -396,7 +396,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { // STEP 7: DESTROY THE DELEGATION IN DELAYED CLAIMING STATE // This is to ensure the delegated stake is not subtracted twice from the account. - tx10 := ts.DefaultWallet().ClaimDelegatorRewards("TX19", "TX9:0") + tx10 := ts.DefaultWallet().ClaimDelegatorRewards("TX19", ts.DefaultWallet().OutputData("TX9:0")) block10 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block10", ts.DefaultWallet(), tx10, mock.WithStrongParents(latestParents...))) // Commit until the claiming epoch so we can remove the staking feature from the account in the next step. @@ -406,7 +406,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { // STEP 8: DESTROY ACCOUNT. block11Slot := ts.CurrentSlot() - tx11 := ts.DefaultWallet().ClaimValidatorRewards("TX11", "TX3:0") + tx11 := ts.DefaultWallet().ClaimValidatorRewards("TX11", ts.DefaultWallet().OutputData("TX3:0")) block11 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block11", ts.DefaultWallet(), tx11, mock.WithStrongParents(latestParents...))) latestParents = ts.CommitUntilSlot(block11Slot, block11.ID()) @@ -418,7 +418,7 @@ func Test_Account_StakeAmountCalculation(t *testing.T) { block12Slot := ts.CurrentSlot() blockIssuanceResp = ts.DefaultWallet().GetNewBlockIssuanceResponse() - tx12 := ts.DefaultWallet().DelayedClaimingTransition("TX12", "TX2:0", ts.DefaultWallet().DelegationEndFromSlot(block12Slot, blockIssuanceResp.LatestCommitment.Slot)) + tx12 := ts.DefaultWallet().DelayedClaimingTransition("TX12", ts.DefaultWallet().OutputData("TX2:0"), ts.DefaultWallet().DelegationEndFromSlot(block12Slot, blockIssuanceResp.LatestCommitment.Slot)) block12 := lo.PanicOnErr(ts.IssueBasicBlockWithOptions("block12", ts.DefaultWallet(), tx12, mock.WithStrongParents(latestParents...))) ts.CommitUntilSlot(block12Slot, block12.ID()) diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 9c5e1675f..c74c8f6da 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -175,15 +175,28 @@ func (w *Wallet) registrationSlot(slot iotago.SlotIndex) iotago.SlotIndex { } // DelayedClaimingTransition transitions DelegationOutput into delayed claiming state by setting DelegationID and EndEpoch. -func (w *Wallet) DelayedClaimingTransition(transactionName string, inputName string, delegationEndEpoch iotago.EpochIndex) *iotago.SignedTransaction { - input := w.OutputData(inputName) - if input.Output.Type() != iotago.OutputDelegation { - panic(ierrors.Errorf("%s is not a delegation output, cannot transition to delayed claiming state", inputName)) - } - +func (w *Wallet) DelayedClaimingTransition(transactionName string, input *OutputData, optDelegationEndEpoch ...iotago.EpochIndex) *iotago.SignedTransaction { prevOutput, ok := input.Output.Clone().(*iotago.DelegationOutput) if !ok { - panic(ierrors.Errorf("cloned output %s is not a delegation output, cannot transition to delayed claiming state", inputName)) + panic(ierrors.New("cloned output is not a delegation output, cannot transition to delayed claiming state")) + } + + var delegationEndEpoch iotago.EpochIndex + if len(optDelegationEndEpoch) == 0 { + api := w.Client.LatestAPI() + latestCommitmentSlot := w.GetNewBlockIssuanceResponse().LatestCommitment.Slot + futureBoundedSlotIndex := latestCommitmentSlot + api.ProtocolParameters().MinCommittableAge() + futureBoundedEpochIndex := api.TimeProvider().EpochFromSlot(futureBoundedSlotIndex) + + registrationSlot := api.TimeProvider().EpochEnd(api.TimeProvider().EpochFromSlot(w.CurrentSlot())) - api.ProtocolParameters().EpochNearingThreshold() + + if futureBoundedSlotIndex <= registrationSlot { + delegationEndEpoch = futureBoundedEpochIndex + } else { + delegationEndEpoch = futureBoundedEpochIndex + 1 + } + } else { + delegationEndEpoch = optDelegationEndEpoch[0] } delegationBuilder := builder.NewDelegationOutputBuilderFromPrevious(prevOutput).EndEpoch(delegationEndEpoch) @@ -927,11 +940,10 @@ func (w *Wallet) SendFundsFromAccount(transactionName string, accountOutputName return signedTransaction } -func (w *Wallet) ClaimValidatorRewards(transactionName string, inputName string) *iotago.SignedTransaction { - input := w.OutputData(inputName) +func (w *Wallet) ClaimValidatorRewards(transactionName string, input *OutputData) *iotago.SignedTransaction { inputAccount, ok := input.Output.(*iotago.AccountOutput) if !ok { - panic(fmt.Sprintf("output with alias %s is not *iotago.AccountOutput", inputName)) + panic(fmt.Sprintf("output is not *iotago.AccountOutput")) } apiForSlot := w.Client.APIForSlot(w.CurrentSlot()) @@ -1009,9 +1021,7 @@ func (w *Wallet) AllotManaFromInputs(transactionName string, allotments iotago.A return signedTransaction } -func (w *Wallet) ClaimDelegatorRewards(transactionName string, inputName string) *iotago.SignedTransaction { - input := w.OutputData(inputName) - +func (w *Wallet) ClaimDelegatorRewards(transactionName string, input *OutputData) *iotago.SignedTransaction { apiForSlot := w.Client.APIForSlot(w.CurrentSlot()) potentialMana := w.PotentialMana(apiForSlot, input) @@ -1068,7 +1078,7 @@ func (w *Wallet) AllotManaToWallet(transactionName string, inputName string, rec return signedTransaction } -func (w *Wallet) CreateNFTFromInput(transactionName string, input *OutputData, opts ...options.Option[builder.NFTOutputBuilder]) *iotago.SignedTransaction { +func (w *Wallet) CreateTaggedNFTFromInput(transactionName string, input *OutputData, opts ...options.Option[builder.NFTOutputBuilder]) *iotago.SignedTransaction { nftOutputBuilder := builder.NewNFTOutputBuilder(w.Address(), input.Output.BaseTokenAmount()) options.Apply(nftOutputBuilder, opts) nftOutput := nftOutputBuilder.MustBuild() @@ -1083,6 +1093,20 @@ func (w *Wallet) CreateNFTFromInput(transactionName string, input *OutputData, o ) } +func (w *Wallet) CreateNFTFromInput(transactionName string, input *OutputData, opts ...options.Option[builder.NFTOutputBuilder]) *iotago.SignedTransaction { + nftOutputBuilder := builder.NewNFTOutputBuilder(w.Address(), input.Output.BaseTokenAmount()) + options.Apply(nftOutputBuilder, opts) + nftOutput := nftOutputBuilder.MustBuild() + + return w.createSignedTransactionWithOptions( + transactionName, + []uint32{0}, + WithInputs(input), + WithOutputs(nftOutput), + WithAllotAllManaToAccount(w.CurrentSlot(), w.BlockIssuer.AccountData.ID), + ) +} + //nolint:forcetypeassert func (w *Wallet) CreateNativeTokenFromInput(transactionName string, inputName string, accountOutputName string, mintedAmount iotago.BaseToken, maxSupply iotago.BaseToken) *iotago.SignedTransaction { if mintedAmount > maxSupply { diff --git a/tools/docker-network/tests/api_core.go b/tools/docker-network/tests/api_core.go index cc2f8df84..d60a63c9c 100644 --- a/tools/docker-network/tests/api_core.go +++ b/tools/docker-network/tests/api_core.go @@ -232,15 +232,16 @@ func (d *DockerTestFramework) prepareAssets(totalAssetsNum int) (coreAPIAssets, assets[valueBlockSlot].reattachments = append(assets[valueBlockSlot].reattachments, secondAttachment.ID()) // delegation - delegationOutputID, delegationOutput := d.DelegateToValidator(wallet, d.Node("V1").AccountAddress(d.Testing)) - assets.setupAssetsForSlot(delegationOutputID.CreationSlot()) - assets[delegationOutputID.CreationSlot()].delegationOutputs[delegationOutputID] = delegationOutput + //nolint:forcetypeassert + delegationOutputData:= d.DelegateToValidator(wallet, d.Node("V1").AccountAddress(d.Testing)) + assets.setupAssetsForSlot(delegationOutputData.ID.CreationSlot()) + assets[delegationOutputData.ID.CreationSlot()].delegationOutputs[delegationOutputData.ID] = delegationOutputData.Output.(*iotago.DelegationOutput) - latestSlot = lo.Max[iotago.SlotIndex](latestSlot, blockSlot, valueBlockSlot, delegationOutputID.CreationSlot(), secondAttachment.ID().Slot()) + latestSlot = lo.Max[iotago.SlotIndex](latestSlot, blockSlot, valueBlockSlot, delegationOutputData.ID.CreationSlot(), secondAttachment.ID().Slot()) fmt.Printf("Assets for slot %d\n: dataBlock: %s block: %s\ntx: %s\nbasic output: %s, faucet output: %s\n delegation output: %s\n", valueBlockSlot, block.MustID().String(), valueBlock.MustID().String(), signedTx.MustID().String(), - basicOutputID.String(), faucetOutput.ID.String(), delegationOutputID.String()) + basicOutputID.String(), faucetOutput.ID.String(), delegationOutputData.ID.String()) } return assets, latestSlot diff --git a/tools/docker-network/tests/committeerotation_test.go b/tools/docker-network/tests/committeerotation_test.go index 6fa812138..7e689766e 100644 --- a/tools/docker-network/tests/committeerotation_test.go +++ b/tools/docker-network/tests/committeerotation_test.go @@ -245,10 +245,11 @@ func Test_Delegation(t *testing.T) { wallet, _ := d.CreateAccount() // delegate all faucet funds to V2, V2 should replace V3 - _, delegationOutput := d.DelegateToValidator(wallet, d.Node("V2").AccountAddress(t)) - d.AssertCommittee(delegationOutput.StartEpoch+1, d.AccountsFromNodes(d.Nodes("V1", "V2", "V4")...)) + //nolint:forcetypeassert + delegationOutputData := d.DelegateToValidator(wallet, d.Node("V2").AccountAddress(t)) + d.AssertCommittee(delegationOutputData.Output.(*iotago.DelegationOutput).StartEpoch+1, d.AccountsFromNodes(d.Nodes("V1", "V2", "V4")...)) // delegate all faucet funds to V3, V3 should replace V1 - _, delegationOutput = d.DelegateToValidator(wallet, d.Node("V3").AccountAddress(t)) - d.AssertCommittee(delegationOutput.StartEpoch+1, d.AccountsFromNodes(d.Nodes("V2", "V3", "V4")...)) + delegationOutputData = d.DelegateToValidator(wallet, d.Node("V3").AccountAddress(t)) + d.AssertCommittee(delegationOutputData.Output.(*iotago.DelegationOutput).StartEpoch+1, d.AccountsFromNodes(d.Nodes("V2", "V3", "V4")...)) } diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 626c2ded7..00af941a8 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -519,7 +519,7 @@ func (d *DockerTestFramework) CreateFoundryBlockFromInput(wallet *mock.Wallet, i // CreateNFTBlockFromInput consumes the given basic output, then build a block of a transaction that includes a NFT output with the given NFT output options. func (d *DockerTestFramework) CreateNFTBlockFromInput(wallet *mock.Wallet, input *mock.OutputData, opts ...options.Option[builder.NFTOutputBuilder]) (iotago.NFTID, iotago.OutputID, *iotago.Block) { - signedTx := wallet.CreateNFTFromInput("", input, opts...) + signedTx := wallet.CreateTaggedNFTFromInput("", input, opts...) outputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) return iotago.NFTIDFromOutputID(outputID), diff --git a/tools/docker-network/tests/rewards_test.go b/tools/docker-network/tests/rewards_test.go index 103c9293c..c66dc7193 100644 --- a/tools/docker-network/tests/rewards_test.go +++ b/tools/docker-network/tests/rewards_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" + "github.com/iotaledger/iota-core/pkg/testsuite/mock" iotago "github.com/iotaledger/iota.go/v4" ) @@ -40,7 +41,7 @@ func Test_ValidatorRewards(t *testing.T) { d.WaitUntilNetworkReady() ctx := context.Background() - clt := d.wallet.DefaultClient() + clt := d.defaultWallet.Client status := d.NodeStatus("V1") currentEpoch := clt.CommittedAPI().TimeProvider().EpochFromSlot(status.LatestAcceptedBlockSlot) slotsDuration := clt.CommittedAPI().ProtocolParameters().SlotDurationInSeconds() @@ -51,20 +52,20 @@ func Test_ValidatorRewards(t *testing.T) { claimingSlot := clt.CommittedAPI().TimeProvider().EpochStart(endEpoch + 1) // create accounts and continue issuing candidacy payload for account in the background - account := d.CreateAccount(WithStakingFeature(100, 1, currentEpoch, endEpoch)) - initialMana := account.Output.StoredMana() - issueCandidacyPayloadInBackground(d, account.ID, clt.CommittedAPI().TimeProvider().CurrentSlot(), claimingSlot, + goodWallet, goodAccountData := d.CreateAccount(WithStakingFeature(100, 1, currentEpoch, endEpoch)) + initialMana := goodAccountData.Output.StoredMana() + issueCandidacyPayloadInBackground(d, goodWallet, clt.CommittedAPI().TimeProvider().CurrentSlot(), claimingSlot, slotsDuration) - lazyAccount := d.CreateAccount(WithStakingFeature(100, 1, currentEpoch, endEpoch)) - lazyInitialMana := lazyAccount.Output.StoredMana() - issueCandidacyPayloadInBackground(d, lazyAccount.ID, clt.CommittedAPI().TimeProvider().CurrentSlot(), claimingSlot, + lazyWallet, lazyAccountData := d.CreateAccount(WithStakingFeature(100, 1, currentEpoch, endEpoch)) + lazyInitialMana := lazyAccountData.Output.StoredMana() + issueCandidacyPayloadInBackground(d, lazyWallet, clt.CommittedAPI().TimeProvider().CurrentSlot(), claimingSlot, slotsDuration) // make sure the account is in the committee, so it can issue validation blocks - accountAddrBech32 := account.Address.Bech32(clt.CommittedAPI().ProtocolParameters().Bech32HRP()) - lazyAccountAddrBech32 := lazyAccount.Address.Bech32(clt.CommittedAPI().ProtocolParameters().Bech32HRP()) - d.AssertCommittee(currentEpoch+2, append(d.AccountsFromNodes(d.Nodes("V1", "V3", "V2", "V4")...), accountAddrBech32, lazyAccountAddrBech32)) + goodAccountAddrBech32 := goodAccountData.Address.Bech32(clt.CommittedAPI().ProtocolParameters().Bech32HRP()) + lazyAccountAddrBech32 := lazyAccountData.Address.Bech32(clt.CommittedAPI().ProtocolParameters().Bech32HRP()) + d.AssertCommittee(currentEpoch+2, append(d.AccountsFromNodes(d.Nodes("V1", "V3", "V2", "V4")...), goodAccountAddrBech32, lazyAccountAddrBech32)) // issue validation blocks to have performance currentSlot := clt.CommittedAPI().TimeProvider().CurrentSlot() @@ -73,29 +74,25 @@ func Test_ValidatorRewards(t *testing.T) { fmt.Println("Wait for ", secToWait, "until expected slot: ", claimingSlot) var wg sync.WaitGroup - issueValidationBlockInBackground(&wg, d, account.ID, currentSlot, claimingSlot, 3, slotsDuration) - issueValidationBlockInBackground(&wg, d, lazyAccount.ID, currentSlot, claimingSlot, 1, slotsDuration) + issueValidationBlockInBackground(&wg, d, goodAccountData.ID, currentSlot, claimingSlot, 3, slotsDuration) + issueValidationBlockInBackground(&wg, d, lazyAccountData.ID, currentSlot, claimingSlot, 1, slotsDuration) wg.Wait() // claim rewards that put to the account output d.AwaitCommitment(claimingSlot) - account = d.ClaimRewardsForValidator(ctx, account) - lazyAccount = d.ClaimRewardsForValidator(ctx, lazyAccount) + d.ClaimRewardsForValidator(ctx, goodWallet) + d.ClaimRewardsForValidator(ctx, lazyWallet) // check if the mana increased as expected - outputFromAPI, err := clt.OutputByID(ctx, account.OutputID) - require.NoError(t, err) - require.Greater(t, outputFromAPI.StoredMana(), initialMana) - require.Equal(t, account.Output.StoredMana(), outputFromAPI.StoredMana()) + goodWalletAccountOutput := goodWallet.BlockIssuer.AccountData.Output + require.Greater(t, goodWalletAccountOutput.StoredMana(), initialMana) - lazyOutputFromAPI, err := clt.OutputByID(ctx, lazyAccount.OutputID) - require.NoError(t, err) - require.Greater(t, lazyOutputFromAPI.StoredMana(), lazyInitialMana) - require.Equal(t, lazyAccount.Output.StoredMana(), lazyOutputFromAPI.StoredMana()) + lazyWalletAccountOutput := lazyWallet.BlockIssuer.AccountData.Output + require.Greater(t, lazyWalletAccountOutput.StoredMana(), lazyInitialMana) // account that issued more validation blocks should have more mana - require.Greater(t, account.Output.StoredMana(), lazyAccount.Output.StoredMana()) + require.Greater(t, goodWalletAccountOutput.StoredMana(), lazyWalletAccountOutput.StoredMana()) } // Test_DelegatorRewards tests the rewards for a delegator. @@ -123,13 +120,12 @@ func Test_DelegatorRewards(t *testing.T) { d.WaitUntilNetworkReady() ctx := context.Background() - clt := d.wallet.DefaultClient() - - account := d.CreateAccount() + delegatorWallet, _ := d.CreateAccount() + clt := delegatorWallet.Client // delegate funds to V2 - delegationOutputID, delegationOutput := d.DelegateToValidator(account.ID, d.Node("V2").AccountAddress(t)) - d.AwaitCommitment(delegationOutputID.CreationSlot()) + delegationOutputData := d.DelegateToValidator(delegatorWallet, d.Node("V2").AccountAddress(t)) + d.AwaitCommitment(delegationOutputData.ID.CreationSlot()) // check if V2 received the delegator stake v2Resp, err := clt.Validator(ctx, d.Node("V2").AccountAddress(t)) @@ -137,20 +133,21 @@ func Test_DelegatorRewards(t *testing.T) { require.Greater(t, v2Resp.PoolStake, v2Resp.ValidatorStake) // wait until next epoch so the rewards can be claimed - expectedSlot := clt.CommittedAPI().TimeProvider().EpochStart(delegationOutput.StartEpoch + 2) + //nolint:forcetypeassert + expectedSlot := clt.CommittedAPI().TimeProvider().EpochStart(delegationOutputData.Output.(*iotago.DelegationOutput).StartEpoch + 2) slotToWait := expectedSlot - clt.CommittedAPI().TimeProvider().CurrentSlot() secToWait := time.Duration(slotToWait) * time.Duration(clt.CommittedAPI().ProtocolParameters().SlotDurationInSeconds()) * time.Second fmt.Println("Wait for ", secToWait, "until expected slot: ", expectedSlot) time.Sleep(secToWait) // claim rewards that put to an basic output - rewardsOutputID := d.ClaimRewardsForDelegator(ctx, account, delegationOutputID) + rewardsOutputID := d.ClaimRewardsForDelegator(ctx, delegatorWallet, delegationOutputData) // check if the mana increased as expected outputFromAPI, err := clt.OutputByID(ctx, rewardsOutputID) require.NoError(t, err) - rewardsOutput := d.wallet.Output(rewardsOutputID) + rewardsOutput := delegatorWallet.Output(rewardsOutputID) require.Equal(t, rewardsOutput.Output.StoredMana(), outputFromAPI.StoredMana()) } @@ -179,14 +176,13 @@ func Test_DelayedClaimingRewards(t *testing.T) { d.WaitUntilNetworkReady() ctx := context.Background() - clt := d.wallet.DefaultClient() - - account := d.CreateAccount() + delegatorWallet, _ := d.CreateAccount() + clt := delegatorWallet.Client { // delegate funds to V2 - delegationOutputID, _ := d.DelegateToValidator(account.ID, d.Node("V2").AccountAddress(t)) - d.AwaitCommitment(delegationOutputID.CreationSlot()) + delegationOutputData := d.DelegateToValidator(delegatorWallet, d.Node("V2").AccountAddress(t)) + d.AwaitCommitment(delegationOutputData.ID.CreationSlot()) // check if V2 received the delegator stake v2Resp, err := clt.Validator(ctx, d.Node("V2").AccountAddress(t)) @@ -194,8 +190,11 @@ func Test_DelayedClaimingRewards(t *testing.T) { require.Greater(t, v2Resp.PoolStake, v2Resp.ValidatorStake) // delay claiming rewards - delegationOutputID1, delegationEndEpoch := d.DelayedClaimingTransition(ctx, account, delegationOutputID) - d.AwaitCommitment(delegationOutputID1.CreationSlot()) + currentSlot := delegatorWallet.CurrentSlot() + apiForSlot := clt.APIForSlot(currentSlot) + latestCommitmentSlot := delegatorWallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot + delegationEndEpoch := getDelegationEndEpoch(apiForSlot, currentSlot, latestCommitmentSlot) + d.AwaitCommitment(delegationOutputData.ID.CreationSlot()) // the delegated stake should be removed from the validator, so the pool stake should equal to the validator stake v2Resp, err = clt.Validator(ctx, d.Node("V2").AccountAddress(t)) @@ -208,16 +207,16 @@ func Test_DelayedClaimingRewards(t *testing.T) { secToWait := time.Duration(slotToWait) * time.Duration(clt.CommittedAPI().ProtocolParameters().SlotDurationInSeconds()) * time.Second fmt.Println("Wait for ", secToWait, "until expected slot: ", expectedSlot) time.Sleep(secToWait) - d.ClaimRewardsForDelegator(ctx, account, delegationOutputID1) + d.ClaimRewardsForDelegator(ctx, delegatorWallet, delegationOutputData) } { // delegate funds to V2 - delegationOutputID, _ := d.DelegateToValidator(account.ID, d.Node("V2").AccountAddress(t)) + delegationOutputData := d.DelegateToValidator(delegatorWallet, d.Node("V2").AccountAddress(t)) // delay claiming rewards in the same slot of delegation - delegationOutputID1, _ := d.DelayedClaimingTransition(ctx, account, delegationOutputID) - d.AwaitCommitment(delegationOutputID1.CreationSlot()) + delegationOutputData = d.DelayedClaimingTransition(ctx, delegatorWallet, delegationOutputData) + d.AwaitCommitment(delegationOutputData.ID.CreationSlot()) // the delegated stake should be 0, thus poolStake should be equal to validatorStake v2Resp, err := clt.Validator(ctx, d.Node("V2").AccountAddress(t)) @@ -225,17 +224,17 @@ func Test_DelayedClaimingRewards(t *testing.T) { require.Equal(t, v2Resp.PoolStake, v2Resp.ValidatorStake) // wait until next epoch to destroy the delegation - d.ClaimRewardsForDelegator(ctx, account, delegationOutputID1) + d.ClaimRewardsForDelegator(ctx, delegatorWallet, delegationOutputData) } } -func issueCandidacyPayloadInBackground(d *DockerTestFramework, accountID iotago.AccountID, startSlot, endSlot iotago.SlotIndex, slotDuration uint8) { +func issueCandidacyPayloadInBackground(d *DockerTestFramework, wallet *mock.Wallet, startSlot, endSlot iotago.SlotIndex, slotDuration uint8) { go func() { - fmt.Println("Issuing candidacy payloads for account", accountID, "in the background...") - defer fmt.Println("Issuing candidacy payloads for account", accountID, "in the background......done") + fmt.Println("Issuing candidacy payloads for account", wallet.BlockIssuer.AccountData.ID, "in the background...") + defer fmt.Println("Issuing candidacy payloads for account", wallet.BlockIssuer.AccountData.ID, "in the background......done") for i := startSlot; i < endSlot; i++ { - d.IssueCandidacyPayloadFromAccount(accountID) + d.IssueCandidacyPayloadFromAccount(wallet) time.Sleep(time.Duration(slotDuration) * time.Second) } }() From 15a40c1b5d81bb675f288b652b7bfbe0b454ec47 Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 17 Apr 2024 14:32:12 +0100 Subject: [PATCH 15/23] fix validator api test --- pkg/testsuite/mock/wallet_transactions.go | 2 +- tools/docker-network/tests/api_core_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index c74c8f6da..623b98f4a 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -943,7 +943,7 @@ func (w *Wallet) SendFundsFromAccount(transactionName string, accountOutputName func (w *Wallet) ClaimValidatorRewards(transactionName string, input *OutputData) *iotago.SignedTransaction { inputAccount, ok := input.Output.(*iotago.AccountOutput) if !ok { - panic(fmt.Sprintf("output is not *iotago.AccountOutput")) + panic("output is not *iotago.AccountOutput") } apiForSlot := w.Client.APIForSlot(w.CurrentSlot()) diff --git a/tools/docker-network/tests/api_core_test.go b/tools/docker-network/tests/api_core_test.go index e023847a7..c3290ad6e 100644 --- a/tools/docker-network/tests/api_core_test.go +++ b/tools/docker-network/tests/api_core_test.go @@ -58,7 +58,7 @@ func Test_ValidatorsAPI(t *testing.T) { go func() { defer wg.Done() - wallet, accountData := d.CreateAccount(WithStakingFeature(100, 1, 0)) + wallet, accountData := d.CreateAccount(WithStakingFeature(100, 1, currentEpoch)) expectedValidators = append(expectedValidators, accountData.Address.Bech32(hrp)) // issue candidacy payload in the next epoch (currentEpoch + 1), in order to issue it before epochNearingThreshold d.AwaitCommitment(clt.CommittedAPI().TimeProvider().EpochEnd(currentEpoch)) From 9fb136817f1fdb2161d17d6258c30a3c8ca0c6a8 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 18 Apr 2024 14:08:36 +0100 Subject: [PATCH 16/23] fix mqtt tests --- pkg/testsuite/mock/blockissuer.go | 6 +++--- tools/docker-network/tests/eventapi_test.go | 1 - tools/docker-network/tests/eventapiframework.go | 4 ++-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/pkg/testsuite/mock/blockissuer.go b/pkg/testsuite/mock/blockissuer.go index eab6982e8..a9aec82b4 100644 --- a/pkg/testsuite/mock/blockissuer.go +++ b/pkg/testsuite/mock/blockissuer.go @@ -258,6 +258,9 @@ func (i *BlockIssuer) CreateBasicBlock(ctx context.Context, alias string, opts . modelBlock.ID().RegisterAlias(alias) + // mark the response as used so that the next time we query the node for the latest block issuance. + i.blockIssuanceResponseUsed = true + return blocks.NewBlock(modelBlock), err } @@ -356,9 +359,6 @@ func (i *BlockIssuer) SubmitBlock(ctx context.Context, block *model.Block) error i.mutex.Lock() defer i.mutex.Unlock() - // mark the response as used so that the next time we query the node for the latest block issuance. - i.blockIssuanceResponseUsed = true - return lo.Return2(i.Client.SubmitBlock(ctx, block.ProtocolBlock())) } diff --git a/tools/docker-network/tests/eventapi_test.go b/tools/docker-network/tests/eventapi_test.go index ca57e7a88..1a337943a 100644 --- a/tools/docker-network/tests/eventapi_test.go +++ b/tools/docker-network/tests/eventapi_test.go @@ -387,7 +387,6 @@ func test_NFTTransactionBlocks(t *testing.T, e *EventAPIDockerTestFramework) { // issue blocks go func() { for _, blk := range expectedBlocks { - fmt.Println("submitting a block ", blk.MustID().ToHex()) e.dockerFramework.SubmitBlock(context.Background(), blk) } }() diff --git a/tools/docker-network/tests/eventapiframework.go b/tools/docker-network/tests/eventapiframework.go index 1a3f2c626..4d0ec1545 100644 --- a/tools/docker-network/tests/eventapiframework.go +++ b/tools/docker-network/tests/eventapiframework.go @@ -17,6 +17,7 @@ import ( iotago "github.com/iotaledger/iota.go/v4" "github.com/iotaledger/iota.go/v4/api" "github.com/iotaledger/iota.go/v4/nodeclient" + "github.com/iotaledger/iota.go/v4/tpkg" ) type EventAPIDockerTestFramework struct { @@ -63,8 +64,7 @@ func (e *EventAPIDockerTestFramework) SubmitDataBlockStream(wallet *mock.Wallet, select { case <-ticker.C: for i := 0; i < 10; i++ { - blk := e.dockerFramework.CreateTaggedDataBlock(wallet, []byte("tag")) - e.dockerFramework.SubmitBlock(context.Background(), blk) + e.dockerFramework.defaultWallet.CreateAndSubmitBasicBlock(context.TODO(), "", mock.WithPayload(tpkg.RandTaggedData([]byte("tag")))) } case <-timer.C: return From c3edf61c8bde63446b6dcdac10a9c1cc12a206f7 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 18 Apr 2024 14:18:52 +0100 Subject: [PATCH 17/23] merge fix --- tools/docker-network/tests/rewards_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/docker-network/tests/rewards_test.go b/tools/docker-network/tests/rewards_test.go index 4d5630357..6fae8dd80 100644 --- a/tools/docker-network/tests/rewards_test.go +++ b/tools/docker-network/tests/rewards_test.go @@ -247,7 +247,7 @@ func issueValidationBlockInBackground(wg *sync.WaitGroup, d *DockerTestFramework defer wg.Done() fmt.Println("Issuing validation block for account", accountID, "in the background...") defer fmt.Println("Issuing validation block for account", accountID, "in the background......done") - clt := d.wallet.DefaultClient() + clt := d.defaultWallet.Client for i := startSlot; i < endSlot; i++ { // wait until the slot is reached From a8bf1c0f8a106d24821ca2a4adb60a2c627ff23a Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 18 Apr 2024 18:38:46 +0100 Subject: [PATCH 18/23] Fix validator rewards test --- pkg/testsuite/mock/block_params.go | 6 +++ pkg/testsuite/mock/blockissuer.go | 10 +++-- pkg/testsuite/mock/node.go | 2 +- pkg/testsuite/mock/wallet_blocks.go | 8 ++++ .../tests/api_management_test.go | 4 +- tools/docker-network/tests/dockerframework.go | 43 +------------------ tools/docker-network/tests/rewards_test.go | 15 +++---- 7 files changed, 30 insertions(+), 58 deletions(-) diff --git a/pkg/testsuite/mock/block_params.go b/pkg/testsuite/mock/block_params.go index f9ea62b9f..8d1e1c052 100644 --- a/pkg/testsuite/mock/block_params.go +++ b/pkg/testsuite/mock/block_params.go @@ -29,6 +29,12 @@ type ValidationBlockParams struct { ProtocolParametersHash *iotago.Identifier } +func NewValidationBlockParams() *ValidationBlockParams { + return &ValidationBlockParams{ + BlockHeader: &BlockHeaderParams{}, + } +} + func WithParentsCount(parentsCount int) func(builder *BlockHeaderParams) { return func(builder *BlockHeaderParams) { builder.ParentsCount = parentsCount diff --git a/pkg/testsuite/mock/blockissuer.go b/pkg/testsuite/mock/blockissuer.go index a9aec82b4..d8e1498f0 100644 --- a/pkg/testsuite/mock/blockissuer.go +++ b/pkg/testsuite/mock/blockissuer.go @@ -89,8 +89,10 @@ func (i *BlockIssuer) Address() iotago.Address { return iotago.Ed25519AddressFromPubKey(pub) } +// CreateValidationBlock creates a new validation block with the options provided. If a node is specified, it will try to +// revive the chain if the block is too far behind the latest commitment. func (i *BlockIssuer) CreateValidationBlock(ctx context.Context, alias string, node *Node, opts ...options.Option[ValidationBlockParams]) (*blocks.Block, error) { - blockParams := options.Apply(&ValidationBlockParams{}, opts) + blockParams := options.Apply(NewValidationBlockParams(), opts) if blockParams.BlockHeader.IssuingTime == nil { issuingTime := time.Now().UTC() @@ -104,7 +106,7 @@ func (i *BlockIssuer) CreateValidationBlock(ctx context.Context, alias string, n if blockParams.BlockHeader.SlotCommitment == nil { commitment := blockIssuanceInfo.LatestCommitment blockSlot := apiForBlock.TimeProvider().SlotFromTime(*blockParams.BlockHeader.IssuingTime) - if blockSlot > commitment.Slot+protoParams.MaxCommittableAge() { + if blockSlot > commitment.Slot+protoParams.MaxCommittableAge() && node != nil { var parentID iotago.BlockID var err error commitment, parentID, err = i.reviveChain(*blockParams.BlockHeader.IssuingTime, node) @@ -195,7 +197,7 @@ func referencesFromBlockIssuanceResponse(response *api.IssuanceBlockHeaderRespon return references } -func (i *BlockIssuer) IssueValidationBlock(ctx context.Context, alias string, node *Node, opts ...options.Option[ValidationBlockParams]) (*blocks.Block, error) { +func (i *BlockIssuer) CreateAndSubmitValidationBlock(ctx context.Context, alias string, node *Node, opts ...options.Option[ValidationBlockParams]) (*blocks.Block, error) { block, err := i.CreateValidationBlock(ctx, alias, node, opts...) require.NoError(i.Testing, err) @@ -293,7 +295,7 @@ func (i *BlockIssuer) IssueActivity(ctx context.Context, wg *sync.WaitGroup, sta blockAlias := fmt.Sprintf("%s-activity.%d", i.Name, counter) timeOffset := time.Since(start) - lo.PanicOnErr(i.IssueValidationBlock(ctx, blockAlias, node, + lo.PanicOnErr(i.CreateAndSubmitValidationBlock(ctx, blockAlias, node, WithValidationBlockHeaderOptions( WithIssuingTime(issuingTime.Add(timeOffset)), ), diff --git a/pkg/testsuite/mock/node.go b/pkg/testsuite/mock/node.go index 5053947b4..9c2964add 100644 --- a/pkg/testsuite/mock/node.go +++ b/pkg/testsuite/mock/node.go @@ -361,5 +361,5 @@ func (n *Node) IssueValidationBlock(ctx context.Context, alias string, opts ...o panic("node is not a validator") } - return n.Validator.IssueValidationBlock(ctx, alias, n, opts...) + return n.Validator.CreateAndSubmitValidationBlock(ctx, alias, n, opts...) } diff --git a/pkg/testsuite/mock/wallet_blocks.go b/pkg/testsuite/mock/wallet_blocks.go index c528a2ab8..909f24858 100644 --- a/pkg/testsuite/mock/wallet_blocks.go +++ b/pkg/testsuite/mock/wallet_blocks.go @@ -14,3 +14,11 @@ func (w *Wallet) CreateBasicBlock(ctx context.Context, blockName string, opts .. func (w *Wallet) CreateAndSubmitBasicBlock(ctx context.Context, blockName string, opts ...options.Option[BasicBlockParams]) (*blocks.Block, error) { return w.BlockIssuer.CreateAndSubmitBasicBlock(ctx, blockName, opts...) } + +func (w *Wallet) CreateValidationBlock(ctx context.Context, blockName string, node *Node, opts ...options.Option[ValidationBlockParams]) (*blocks.Block, error) { + return w.BlockIssuer.CreateValidationBlock(ctx, blockName, node, opts...) +} + +func (w *Wallet) CreateAndSubmitValidationBlock(ctx context.Context, blockName string, node *Node, opts ...options.Option[ValidationBlockParams]) (*blocks.Block, error) { + return w.BlockIssuer.CreateAndSubmitValidationBlock(ctx, blockName, node, opts...) +} diff --git a/tools/docker-network/tests/api_management_test.go b/tools/docker-network/tests/api_management_test.go index 837ccae43..742a5e2b2 100644 --- a/tools/docker-network/tests/api_management_test.go +++ b/tools/docker-network/tests/api_management_test.go @@ -184,7 +184,6 @@ func Test_ManagementAPI_Peers_BadRequests(t *testing.T) { func Test_ManagementAPI_Pruning(t *testing.T) { d := NewDockerTestFramework(t, WithProtocolParametersOptions( - iotago.WithSupplyOptions(1813620509061365, 63, 1, 4, 0, 0, 0), iotago.WithTimeProviderOptions(0, time.Now().Unix(), 3, 4), iotago.WithLivenessOptions(3, 4, 2, 4, 8), iotago.WithCongestionControlOptions(1, 1, 1, 400_000, 250_000, 50_000_000, 1000, 100), @@ -214,7 +213,7 @@ func Test_ManagementAPI_Pruning(t *testing.T) { info, err := nodeClientV1.Info(getContextWithTimeout(5 * time.Second)) require.NoError(t, err) - currentEpoch := nodeClientV1.CommittedAPI().TimeProvider().EpochFromSlot(info.Status.LatestFinalizedSlot) + currentEpoch := nodeClientV1.CommittedAPI().TimeProvider().EpochFromSlot(info.Status.LatestCommitmentID.Slot()) // await the start slot of the next epoch d.AwaitCommitment(nodeClientV1.CommittedAPI().TimeProvider().EpochStart(currentEpoch + 1)) @@ -274,7 +273,6 @@ func Test_ManagementAPI_Pruning(t *testing.T) { func Test_ManagementAPI_Snapshots(t *testing.T) { d := NewDockerTestFramework(t, WithProtocolParametersOptions( - iotago.WithSupplyOptions(1813620509061365, 63, 1, 4, 0, 0, 0), iotago.WithTimeProviderOptions(0, time.Now().Unix(), 3, 4), iotago.WithLivenessOptions(3, 4, 2, 4, 8), iotago.WithCongestionControlOptions(1, 1, 1, 400_000, 250_000, 50_000_000, 1000, 100), diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 57ba7d639..96e156a54 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -20,8 +20,6 @@ import ( "github.com/iotaledger/hive.go/lo" "github.com/iotaledger/hive.go/runtime/options" "github.com/iotaledger/hive.go/runtime/syncutils" - "github.com/iotaledger/hive.go/serializer/v2/serix" - "github.com/iotaledger/iota-core/pkg/model" "github.com/iotaledger/iota-core/pkg/protocol" "github.com/iotaledger/iota-core/pkg/testsuite/mock" "github.com/iotaledger/iota-core/pkg/testsuite/snapshotcreator" @@ -440,45 +438,6 @@ func (d *DockerTestFramework) CreateTaggedDataBlock(wallet *mock.Wallet, tag []b }))).ProtocolBlock() } -func (d *DockerTestFramework) SubmitValidationBlock(issuerID iotago.AccountID, issueNode ...string) *iotago.Block { - issuer := d.defaultWallet.Account(issuerID) - ctx := context.TODO() - issuingTime := time.Now() - clt := d.defaultWallet.Client - if issueNode != nil { - clt = d.Client(issueNode[0]) - } - currentSlot := d.defaultWallet.Client.LatestAPI().TimeProvider().SlotFromTime(issuingTime) - apiForSlot := d.defaultWallet.Client.APIForSlot(currentSlot) - - issuerResp, _ := d.PrepareBlockIssuance(ctx, clt, issuer.Address) - - protocolParametersHash, err := apiForSlot.ProtocolParameters().Hash() - require.NoError(d.Testing, err) - - blockBuilder := builder.NewValidationBlockBuilder(apiForSlot). - IssuingTime(issuingTime). - SlotCommitmentID(issuerResp.LatestCommitment.MustID()). - LatestFinalizedSlot(issuerResp.LatestFinalizedSlot). - StrongParents(issuerResp.StrongParents). - WeakParents(issuerResp.WeakParents). - ShallowLikeParents(issuerResp.ShallowLikeParents). - HighestSupportedVersion(clt.LatestAPI().Version()). - ProtocolParametersHash(protocolParametersHash). - Sign(issuerID, lo.Return1(d.defaultWallet.KeyPair())) - - block, err := blockBuilder.Build() - require.NoError(d.Testing, err) - - // Make sure we only create syntactically valid blocks. - _, err = model.BlockFromBlock(block, serix.WithValidation()) - require.NoError(d.Testing, err) - - d.SubmitBlock(ctx, block) - - return block -} - func (d *DockerTestFramework) CreateBasicOutputBlock(wallet *mock.Wallet) (*iotago.Block, *iotago.SignedTransaction, *mock.OutputData) { fundsOutputData := d.RequestFaucetFunds(context.Background(), wallet, iotago.AddressEd25519) @@ -606,7 +565,7 @@ func (d *DockerTestFramework) CreateAccount(opts ...options.Option[builder.Accou // update the wallet with the new account data newWallet.SetBlockIssuer(accountData) - fmt.Printf("Account created, Bech addr: %s", accountData.Address.Bech32(newWallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP())) + fmt.Printf("Account created, Bech addr: %s\n", accountData.Address.Bech32(newWallet.Client.CommittedAPI().ProtocolParameters().Bech32HRP())) return newWallet, newWallet.Account(accountData.ID) } diff --git a/tools/docker-network/tests/rewards_test.go b/tools/docker-network/tests/rewards_test.go index 6fae8dd80..0fe1673c8 100644 --- a/tools/docker-network/tests/rewards_test.go +++ b/tools/docker-network/tests/rewards_test.go @@ -74,8 +74,8 @@ func Test_ValidatorRewards(t *testing.T) { fmt.Println("Wait for ", secToWait, "until expected slot: ", claimingSlot) var wg sync.WaitGroup - issueValidationBlockInBackground(&wg, d, goodAccountData.ID, currentSlot, claimingSlot, 5) - issueValidationBlockInBackground(&wg, d, lazyAccountData.ID, currentSlot, claimingSlot, 1) + issueValidationBlockInBackground(&wg, goodWallet, currentSlot, claimingSlot, 5) + issueValidationBlockInBackground(&wg, lazyWallet, currentSlot, claimingSlot, 1) wg.Wait() @@ -240,26 +240,25 @@ func issueCandidacyPayloadInBackground(d *DockerTestFramework, wallet *mock.Wall }() } -func issueValidationBlockInBackground(wg *sync.WaitGroup, d *DockerTestFramework, accountID iotago.AccountID, startSlot, endSlot iotago.SlotIndex, blocksPerSlot int) { +func issueValidationBlockInBackground(wg *sync.WaitGroup, wallet *mock.Wallet, startSlot, endSlot iotago.SlotIndex, blocksPerSlot int) { wg.Add(1) go func() { defer wg.Done() - fmt.Println("Issuing validation block for account", accountID, "in the background...") - defer fmt.Println("Issuing validation block for account", accountID, "in the background......done") - clt := d.defaultWallet.Client + fmt.Println("Issuing validation block for account", wallet.Name, "in the background...") + defer fmt.Println("Issuing validation block for account", wallet.Name, "in the background......done") for i := startSlot; i < endSlot; i++ { // wait until the slot is reached for { - if clt.CommittedAPI().TimeProvider().CurrentSlot() == i { + if wallet.CurrentSlot() == i { break } time.Sleep(2 * time.Second) } for range blocksPerSlot { - d.SubmitValidationBlock(accountID) + wallet.CreateAndSubmitValidationBlock(context.Background(), "", nil) time.Sleep(1 * time.Second) } } From aacb493b5701ab331a9fd190a8079825ca838eb4 Mon Sep 17 00:00:00 2001 From: Andrew Date: Fri, 19 Apr 2024 12:09:44 +0100 Subject: [PATCH 19/23] fix delegation tests --- tools/docker-network/tests/rewards_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/docker-network/tests/rewards_test.go b/tools/docker-network/tests/rewards_test.go index 0fe1673c8..02feb47fc 100644 --- a/tools/docker-network/tests/rewards_test.go +++ b/tools/docker-network/tests/rewards_test.go @@ -187,6 +187,7 @@ func Test_DelayedClaimingRewards(t *testing.T) { // check if V2 received the delegator stake v2Resp, err := clt.Validator(ctx, d.Node("V2").AccountAddress(t)) require.NoError(t, err) + fmt.Printf("Pool stake: %d, Validator stake: %d\n", v2Resp.PoolStake, v2Resp.ValidatorStake) require.Greater(t, v2Resp.PoolStake, v2Resp.ValidatorStake) // delay claiming rewards @@ -194,11 +195,13 @@ func Test_DelayedClaimingRewards(t *testing.T) { apiForSlot := clt.APIForSlot(currentSlot) latestCommitmentSlot := delegatorWallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot delegationEndEpoch := getDelegationEndEpoch(apiForSlot, currentSlot, latestCommitmentSlot) + delegationOutputData = d.DelayedClaimingTransition(ctx, delegatorWallet, delegationOutputData) d.AwaitCommitment(delegationOutputData.ID.CreationSlot()) // the delegated stake should be removed from the validator, so the pool stake should equal to the validator stake v2Resp, err = clt.Validator(ctx, d.Node("V2").AccountAddress(t)) require.NoError(t, err) + fmt.Printf("Pool stake: %d, Validator stake: %d\n", v2Resp.PoolStake, v2Resp.ValidatorStake) require.Equal(t, v2Resp.PoolStake, v2Resp.ValidatorStake) // wait until next epoch to destroy the delegation From 3ec41410cb6c447a0b15752497c65c09ba4d3726 Mon Sep 17 00:00:00 2001 From: Andrew Cullen <45826600+cyberphysic4l@users.noreply.github.com> Date: Tue, 23 Apr 2024 10:30:35 +0100 Subject: [PATCH 20/23] Update pkg/testsuite/mock/wallet.go Co-authored-by: Philipp Gackstatter --- pkg/testsuite/mock/wallet.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/testsuite/mock/wallet.go b/pkg/testsuite/mock/wallet.go index 4a4c0918e..8c629cbe7 100644 --- a/pkg/testsuite/mock/wallet.go +++ b/pkg/testsuite/mock/wallet.go @@ -243,7 +243,7 @@ func (w *Wallet) Account(accountID iotago.AccountID) *AccountData { acc, exists := w.accounts[accountID] if !exists { - panic(ierrors.Errorf("account %s not registered in wallet", accountID.ToHex())) + panic(ierrors.Errorf("account %s not registered in wallet", accountID)) } return acc From 8f651bede7e3bc1c4ed036601ca5f26612d00e5e Mon Sep 17 00:00:00 2001 From: Andrew Cullen <45826600+cyberphysic4l@users.noreply.github.com> Date: Tue, 23 Apr 2024 10:30:51 +0100 Subject: [PATCH 21/23] Update pkg/testsuite/mock/wallet.go Co-authored-by: Philipp Gackstatter --- pkg/testsuite/mock/wallet.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pkg/testsuite/mock/wallet.go b/pkg/testsuite/mock/wallet.go index 8c629cbe7..ce21e6541 100644 --- a/pkg/testsuite/mock/wallet.go +++ b/pkg/testsuite/mock/wallet.go @@ -261,7 +261,7 @@ func (w *Wallet) Accounts(accountIDs ...iotago.AccountID) []*AccountData { for _, id := range accountIDs { acc, exists := w.accounts[id] if !exists { - panic(ierrors.Errorf("account %s not registered in wallet", id.ToHex())) + panic(ierrors.Errorf("account %s not registered in wallet", id)) } accounts = append(accounts, acc) } From 8081e161891ae3a81589a4c0453120a2836e0ee2 Mon Sep 17 00:00:00 2001 From: Andrew Date: Tue, 23 Apr 2024 10:38:29 +0100 Subject: [PATCH 22/23] review comments --- pkg/testsuite/mock/client.go | 4 ++++ pkg/testsuite/mock/wallet_transactions.go | 3 ++- tools/docker-network/tests/api_core.go | 2 +- tools/docker-network/tests/rewards_test.go | 6 ++---- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/pkg/testsuite/mock/client.go b/pkg/testsuite/mock/client.go index ffc9fef35..b83b2455f 100644 --- a/pkg/testsuite/mock/client.go +++ b/pkg/testsuite/mock/client.go @@ -237,6 +237,7 @@ func (c *TestSuiteClient) Rewards(_ context.Context, outputID iotago.OutputID) ( } func (c *TestSuiteClient) Routes(_ context.Context) (*api.RoutesResponse, error) { + // Not currently used in the tests: implement if needed. panic("not implemented") } @@ -245,6 +246,7 @@ func (c *TestSuiteClient) SubmitBlock(ctx context.Context, block *iotago.Block) } func (c *TestSuiteClient) TransactionByID(_ context.Context, _ iotago.TransactionID) (*iotago.Transaction, error) { + // Not currently used in the tests: implement if needed. panic("not implemented") } @@ -265,9 +267,11 @@ func (c *TestSuiteClient) Validator(_ context.Context, accountAddress *iotago.Ac } func (c *TestSuiteClient) Validators(_ context.Context, _ uint64, _ ...string) (*api.ValidatorsResponse, error) { + // Not currently used in the tests: implement if needed. panic("not implemented") } func (c *TestSuiteClient) ValidatorsAll(_ context.Context, _ ...int) (*api.ValidatorsResponse, bool, error) { + // Not currently used in the tests: implement if needed. panic("not implemented") } diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 623b98f4a..6f96aebce 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -483,7 +483,8 @@ func (w *Wallet) CreateFoundryAndNativeTokensFromInput(input *OutputData, minted require.NoError(w.Testing, err) foundryOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 1) - w.AddOutput("", &OutputData{ + // register the output in the wallet + w.AddOutput("foundry", &OutputData{ ID: foundryOutputID, Output: foundryOutput, Address: issuer.Address, diff --git a/tools/docker-network/tests/api_core.go b/tools/docker-network/tests/api_core.go index d60a63c9c..aa2cc9a1e 100644 --- a/tools/docker-network/tests/api_core.go +++ b/tools/docker-network/tests/api_core.go @@ -226,7 +226,7 @@ func (d *DockerTestFramework) prepareAssets(totalAssetsNum int) (coreAPIAssets, d.SubmitBlock(ctx, valueBlock) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) - // issue reattachment after the fisrt one is already included + // issue reattachment after the first one is already included secondAttachment, err := wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) assets[valueBlockSlot].reattachments = append(assets[valueBlockSlot].reattachments, secondAttachment.ID()) diff --git a/tools/docker-network/tests/rewards_test.go b/tools/docker-network/tests/rewards_test.go index 02feb47fc..10a4303a1 100644 --- a/tools/docker-network/tests/rewards_test.go +++ b/tools/docker-network/tests/rewards_test.go @@ -187,7 +187,6 @@ func Test_DelayedClaimingRewards(t *testing.T) { // check if V2 received the delegator stake v2Resp, err := clt.Validator(ctx, d.Node("V2").AccountAddress(t)) require.NoError(t, err) - fmt.Printf("Pool stake: %d, Validator stake: %d\n", v2Resp.PoolStake, v2Resp.ValidatorStake) require.Greater(t, v2Resp.PoolStake, v2Resp.ValidatorStake) // delay claiming rewards @@ -201,7 +200,6 @@ func Test_DelayedClaimingRewards(t *testing.T) { // the delegated stake should be removed from the validator, so the pool stake should equal to the validator stake v2Resp, err = clt.Validator(ctx, d.Node("V2").AccountAddress(t)) require.NoError(t, err) - fmt.Printf("Pool stake: %d, Validator stake: %d\n", v2Resp.PoolStake, v2Resp.ValidatorStake) require.Equal(t, v2Resp.PoolStake, v2Resp.ValidatorStake) // wait until next epoch to destroy the delegation @@ -248,8 +246,8 @@ func issueValidationBlockInBackground(wg *sync.WaitGroup, wallet *mock.Wallet, s go func() { defer wg.Done() - fmt.Println("Issuing validation block for account", wallet.Name, "in the background...") - defer fmt.Println("Issuing validation block for account", wallet.Name, "in the background......done") + fmt.Println("Issuing validation block for wallet", wallet.Name, "in the background...") + defer fmt.Println("Issuing validation block for wallet", wallet.Name, "in the background......done") for i := startSlot; i < endSlot; i++ { // wait until the slot is reached From cf3bc20c6b3b2daeba1e8800c1537c53bdd6f569 Mon Sep 17 00:00:00 2001 From: Andrew Date: Tue, 23 Apr 2024 11:00:57 +0100 Subject: [PATCH 23/23] Add some descriptive names to blocks --- pkg/testsuite/mock/wallet_transactions.go | 2 +- tools/docker-network/tests/api_core.go | 2 +- tools/docker-network/tests/dockerframework.go | 26 +++++++++---------- .../docker-network/tests/eventapiframework.go | 2 +- .../tests/mempool_invalid_signatures_test.go | 6 ++--- 5 files changed, 19 insertions(+), 19 deletions(-) diff --git a/pkg/testsuite/mock/wallet_transactions.go b/pkg/testsuite/mock/wallet_transactions.go index 6f96aebce..8c82224e9 100644 --- a/pkg/testsuite/mock/wallet_transactions.go +++ b/pkg/testsuite/mock/wallet_transactions.go @@ -483,7 +483,7 @@ func (w *Wallet) CreateFoundryAndNativeTokensFromInput(input *OutputData, minted require.NoError(w.Testing, err) foundryOutputID := iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 1) - // register the output in the wallet + // register the output in the wallet so it can be retrieved by ID by that wallet later w.AddOutput("foundry", &OutputData{ ID: foundryOutputID, Output: foundryOutput, diff --git a/tools/docker-network/tests/api_core.go b/tools/docker-network/tests/api_core.go index aa2cc9a1e..7aa93897e 100644 --- a/tools/docker-network/tests/api_core.go +++ b/tools/docker-network/tests/api_core.go @@ -227,7 +227,7 @@ func (d *DockerTestFramework) prepareAssets(totalAssetsNum int) (coreAPIAssets, d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) // issue reattachment after the first one is already included - secondAttachment, err := wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) + secondAttachment, err := wallet.CreateAndSubmitBasicBlock(ctx, "second_attachment", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) assets[valueBlockSlot].reattachments = append(assets[valueBlockSlot].reattachments, secondAttachment.ID()) diff --git a/tools/docker-network/tests/dockerframework.go b/tools/docker-network/tests/dockerframework.go index 96e156a54..4715b5420 100644 --- a/tools/docker-network/tests/dockerframework.go +++ b/tools/docker-network/tests/dockerframework.go @@ -423,7 +423,7 @@ func (d *DockerTestFramework) StopIssueCandidacyPayload(nodes ...*Node) { } func (d *DockerTestFramework) IssueCandidacyPayloadFromAccount(wallet *mock.Wallet) iotago.BlockID { - block, err := wallet.CreateAndSubmitBasicBlock(context.TODO(), "", mock.WithPayload(&iotago.CandidacyAnnouncement{})) + block, err := wallet.CreateAndSubmitBasicBlock(context.TODO(), "candidacy_payload", mock.WithPayload(&iotago.CandidacyAnnouncement{})) require.NoError(d.Testing, err) return block.ID() @@ -498,10 +498,10 @@ func (d *DockerTestFramework) CreateFoundryTransitionBlockFromInput(issuerID iot //nolint:forcetypeassert return signedTx.Transaction.Outputs[1].(*iotago.FoundryOutput).MustFoundryID(), iotago.OutputIDFromTransactionIDAndIndex(txID, 1), - lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "", mock.WithPayload(signedTx))).ProtocolBlock() + lo.PanicOnErr(d.defaultWallet.CreateAndSubmitBasicBlock(context.Background(), "foundry_transition", mock.WithPayload(signedTx))).ProtocolBlock() } -// CreateAccountBlockFromInput consumes the given output, which should be either an basic output with implicit address, then build block with the given account output options. Note that after the returned transaction is issued, remember to update the account information in the wallet with AddAccount(). +// CreateAccountBlockFromInput consumes the given output, which should be either an basic output with implicit address, then build block with the given account output options. func (d *DockerTestFramework) CreateAccountBlock(opts ...options.Option[builder.AccountOutputBuilder]) (*mock.AccountData, *mock.Wallet, *iotago.SignedTransaction, *iotago.Block) { // create an implicit account by requesting faucet funds ctx := context.TODO() @@ -580,7 +580,7 @@ func (d *DockerTestFramework) ClaimRewardsForValidator(ctx context.Context, vali } signedTx := validatorWallet.ClaimValidatorRewards("", outputData) - validatorWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) + validatorWallet.CreateAndSubmitBasicBlock(ctx, "claim_rewards_validator", mock.WithPayload(signedTx)) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) // update account data of validator @@ -596,16 +596,16 @@ func (d *DockerTestFramework) ClaimRewardsForValidator(ctx context.Context, vali func (d *DockerTestFramework) ClaimRewardsForDelegator(ctx context.Context, wallet *mock.Wallet, delegationOutputData *mock.OutputData) iotago.OutputID { signedTx := wallet.ClaimDelegatorRewards("", delegationOutputData) - wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) + wallet.CreateAndSubmitBasicBlock(ctx, "claim_rewards_delegator", mock.WithPayload(signedTx)) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) return iotago.OutputIDFromTransactionIDAndIndex(signedTx.Transaction.MustID(), 0) } func (d *DockerTestFramework) DelayedClaimingTransition(ctx context.Context, wallet *mock.Wallet, delegationOutputData *mock.OutputData) *mock.OutputData { - signedTx := wallet.DelayedClaimingTransition("", delegationOutputData) + signedTx := wallet.DelayedClaimingTransition("delayed_claim_tx", delegationOutputData) - wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) + wallet.CreateAndSubmitBasicBlock(ctx, "delayed_claim", mock.WithPayload(signedTx)) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) return &mock.OutputData{ @@ -623,13 +623,13 @@ func (d *DockerTestFramework) DelegateToValidator(fromWallet *mock.Wallet, accou fundsOutputData := d.RequestFaucetFunds(ctx, fromWallet, iotago.AddressEd25519) signedTx := fromWallet.CreateDelegationFromInput( - "", + "delegation_tx", fundsOutputData, mock.WithDelegatedValidatorAddress(accountAddress), mock.WithDelegationStartEpoch(getDelegationStartEpoch(fromWallet.Client.LatestAPI(), fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.Slot)), ) - fromWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) + fromWallet.CreateAndSubmitBasicBlock(ctx, "delegation", mock.WithPayload(signedTx)) d.AwaitTransactionPayloadAccepted(ctx, signedTx.Transaction.MustID()) delegationOutput, ok := signedTx.Transaction.Outputs[0].(*iotago.DelegationOutput) @@ -663,13 +663,13 @@ func (d *DockerTestFramework) AllotManaTo(fromWallet *mock.Wallet, to *mock.Acco clt := fromWallet.Client signedTx := fromWallet.AllotManaFromBasicOutput( - "", + "allotment_tx", fundsOutputID, manaToAllot, to.ID, ) preAllotmentCommitmentID := fromWallet.GetNewBlockIssuanceResponse().LatestCommitment.MustID() - block, err := fromWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) + block, err := fromWallet.CreateAndSubmitBasicBlock(ctx, "allotment", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) fmt.Println("Allot mana transaction sent, blkID:", block.ID().ToHex(), ", txID:", signedTx.Transaction.MustID().ToHex(), ", slot:", block.ID().Slot()) @@ -700,7 +700,7 @@ func (d *DockerTestFramework) CreateNativeToken(fromWallet *mock.Wallet, mintedA signedTx := fromWallet.CreateFoundryAndNativeTokensFromInput(fundsOutputData, mintedAmount, maxSupply) - block, err := fromWallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(signedTx)) + block, err := fromWallet.CreateAndSubmitBasicBlock(ctx, "native_token", mock.WithPayload(signedTx)) require.NoError(d.Testing, err) txID := signedTx.Transaction.MustID() @@ -736,7 +736,7 @@ func (d *DockerTestFramework) RequestFaucetFunds(ctx context.Context, wallet *mo AddressIndex: wallet.BlockIssuer.AccountData.AddressIndex, Output: output, } - wallet.AddOutput("", outputData) + wallet.AddOutput("faucet funds", outputData) fmt.Printf("Faucet funds received, txID: %s, amount: %d, mana: %d\n", outputID.TransactionID().ToHex(), output.BaseTokenAmount(), output.StoredMana()) diff --git a/tools/docker-network/tests/eventapiframework.go b/tools/docker-network/tests/eventapiframework.go index 4d0ec1545..c02f93d65 100644 --- a/tools/docker-network/tests/eventapiframework.go +++ b/tools/docker-network/tests/eventapiframework.go @@ -64,7 +64,7 @@ func (e *EventAPIDockerTestFramework) SubmitDataBlockStream(wallet *mock.Wallet, select { case <-ticker.C: for i := 0; i < 10; i++ { - e.dockerFramework.defaultWallet.CreateAndSubmitBasicBlock(context.TODO(), "", mock.WithPayload(tpkg.RandTaggedData([]byte("tag")))) + e.dockerFramework.defaultWallet.CreateAndSubmitBasicBlock(context.TODO(), "tagged_data_block", mock.WithPayload(tpkg.RandTaggedData([]byte("tag")))) } case <-timer.C: return diff --git a/tools/docker-network/tests/mempool_invalid_signatures_test.go b/tools/docker-network/tests/mempool_invalid_signatures_test.go index dd5cb3d07..4a9fc18da 100644 --- a/tools/docker-network/tests/mempool_invalid_signatures_test.go +++ b/tools/docker-network/tests/mempool_invalid_signatures_test.go @@ -51,16 +51,16 @@ func Test_MempoolInvalidSignatures(t *testing.T) { } fmt.Println("Submitting block with invalid TX") - wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(invalidTX)) + wallet.CreateAndSubmitBasicBlock(ctx, "invalid_tx_block", mock.WithPayload(invalidTX)) d.AwaitTransactionState(ctx, invalidTX.Transaction.MustID(), api.TransactionStateFailed) d.AwaitTransactionFailure(ctx, invalidTX.Transaction.MustID(), api.TxFailureUnlockSignatureInvalid) fmt.Println("Submitting block with valid TX") - wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(validTX)) + wallet.CreateAndSubmitBasicBlock(ctx, "valid_tx_block", mock.WithPayload(validTX)) fmt.Println("Submitting block with invalid TX (again)") - wallet.CreateAndSubmitBasicBlock(ctx, "", mock.WithPayload(invalidTX)) + wallet.CreateAndSubmitBasicBlock(ctx, "invalid_tx_block_2", mock.WithPayload(invalidTX)) d.AwaitTransactionPayloadAccepted(ctx, validTX.Transaction.MustID()) }