From b7bb3823191a7ea81447fa23bb454e4dd641d5da Mon Sep 17 00:00:00 2001 From: acud <12988138+acud@users.noreply.github.com> Date: Wed, 14 Aug 2024 08:37:57 -0600 Subject: [PATCH] build(golangci): add unparam linter --- .golangci.yml | 2 +- activation/activation_test.go | 14 +- activation/builder_v2_test.go | 6 +- activation/post_supervisor_test.go | 10 +- api/grpcserver/grpcserver_test.go | 4 +- api/grpcserver/post_service_test.go | 18 +- api/grpcserver/v2alpha1/layer.go | 16 +- atxsdata/warmup_test.go | 19 +- beacon/handlers.go | 4 +- beacon/handlers_test.go | 86 +++++---- blocks/utils.go | 3 +- cmd/merge-nodes/internal/merge_action.go | 6 +- fetch/cache_test.go | 17 +- fetch/fetch.go | 3 +- fetch/handler_test.go | 8 +- fetch/p2p_test.go | 27 ++- genvm/vm_test.go | 55 +++--- hare3/eligibility/oracle.go | 4 +- hare3/eligibility/oracle_test.go | 12 +- hare3/hare_test.go | 39 +++-- hare3/protocol_test.go | 88 +++++----- hare4/eligibility/oracle.go | 4 +- hare4/eligibility/oracle_test.go | 12 +- hare4/hare.go | 10 +- hare4/hare_test.go | 36 ++-- hare4/protocol_test.go | 88 +++++----- mesh/mesh_test.go | 8 +- miner/active_set_generator_test.go | 58 +++---- miner/proposal_builder.go | 7 +- miner/proposal_builder_test.go | 101 +++++------ node/node.go | 4 +- node/node_test.go | 10 +- proposals/eligibility_validator_test.go | 69 ++++---- proposals/handler_test.go | 6 +- sql/atxs/atxs.go | 6 +- sql/atxs/atxs_test.go | 212 +++++++++++------------ sql/transactions/transactions_test.go | 36 ++-- syncer/state_syncer.go | 6 +- systest/cluster/cluster.go | 3 +- systest/tests/smeshing_test.go | 15 +- tortoise/algorithm.go | 2 +- tortoise/algorithm_test.go | 8 +- tortoise/fixture_test.go | 101 ++++++----- tortoise/state.go | 2 +- tortoise/state_test.go | 16 +- tortoise/tortoise.go | 6 +- tortoise/tortoise_test.go | 64 +++---- txs/cache.go | 4 +- txs/cache_test.go | 47 ++--- 49 files changed, 701 insertions(+), 681 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index a25911486b..a800970971 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -224,7 +224,7 @@ linters: # - tparallel - typecheck # - unconvert - # - unparam + - unparam - unused # - usestdlibvars # - varnamelen diff --git a/activation/activation_test.go b/activation/activation_test.go index e073d2a334..acaa2201c1 100644 --- a/activation/activation_test.go +++ b/activation/activation_test.go @@ -128,11 +128,10 @@ func publishAtxV1( nodeID types.NodeID, posEpoch types.EpochID, currLayer *types.LayerID, - buildNIPostLayerDuration uint32, ) *wire.ActivationTxV1 { tb.Helper() var watx wire.ActivationTxV1 - publishAtx(tb, tab, nodeID, posEpoch, currLayer, buildNIPostLayerDuration, + publishAtx(tb, tab, nodeID, posEpoch, currLayer, func(_ context.Context, _ string, got []byte) error { return codec.Decode(got, &watx) }) @@ -148,7 +147,6 @@ func publishAtx( nodeID types.NodeID, posEpoch types.EpochID, currLayer *types.LayerID, // pointer to keep current layer consistent across calls - buildNIPostLayerDuration uint32, onPublish func(context.Context, string, []byte) error, ) { tb.Helper() @@ -175,7 +173,7 @@ func publishAtx( tab.mnipost.EXPECT().BuildNIPost(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).DoAndReturn( func(_ context.Context, _ *signing.EdSigner, _ types.Hash32, _ *types.NIPostChallenge, ) (*nipost.NIPostState, error) { - *currLayer = currLayer.Add(buildNIPostLayerDuration) + *currLayer = currLayer.Add(layersPerEpoch) return newNIPostWithPoet(tb, types.RandomHash().Bytes()), nil }) ch := make(chan struct{}) @@ -358,7 +356,7 @@ func TestBuilder_PublishActivationTx_HappyFlow(t *testing.T) { // create and publish ATX tab.mclock.EXPECT().CurrentLayer().Return(currLayer).Times(4) tab.mValidator.EXPECT().VerifyChain(gomock.Any(), prevAtx.ID(), tab.goldenATXID, gomock.Any()) - atx1 := publishAtxV1(t, tab, sig.NodeID(), posEpoch, &currLayer, layersPerEpoch) + atx1 := publishAtxV1(t, tab, sig.NodeID(), posEpoch, &currLayer) require.NotNil(t, atx1) require.Equal(t, prevAtx.ID(), atx1.PositioningATXID) @@ -366,7 +364,7 @@ func TestBuilder_PublishActivationTx_HappyFlow(t *testing.T) { currLayer = (posEpoch + 1).FirstLayer() tab.mclock.EXPECT().CurrentLayer().Return(currLayer).Times(4) tab.mValidator.EXPECT().VerifyChain(gomock.Any(), atx1.ID(), tab.goldenATXID, gomock.Any()) - atx2 := publishAtxV1(t, tab, sig.NodeID(), atx1.PublishEpoch, &currLayer, layersPerEpoch) + atx2 := publishAtxV1(t, tab, sig.NodeID(), atx1.PublishEpoch, &currLayer) require.NotNil(t, atx2) require.NotEqual(t, atx1, atx2) require.Equal(t, atx1.PublishEpoch+1, atx2.PublishEpoch) @@ -655,7 +653,7 @@ func TestBuilder_PublishActivationTx_RebuildNIPostWhenTargetEpochPassed(t *testi tab.mclock.EXPECT().CurrentLayer().DoAndReturn(func() types.LayerID { return currLayer }).AnyTimes() tab.mnipost.EXPECT().ResetState(sig.NodeID()).Return(nil) tab.mValidator.EXPECT().VerifyChain(gomock.Any(), posAtx.ID(), tab.goldenATXID, gomock.Any()) - built2 := publishAtxV1(t, tab, sig.NodeID(), posEpoch, &currLayer, layersPerEpoch) + built2 := publishAtxV1(t, tab, sig.NodeID(), posEpoch, &currLayer) require.NotNil(t, built2) require.NotEqual(t, built.NIPostChallengeV1, built2.NIPostChallengeV1) require.Equal(t, posEpoch+1, built2.PublishEpoch) @@ -694,7 +692,7 @@ func TestBuilder_PublishActivationTx_NoPrevATX(t *testing.T) { // create and publish ATX tab.mclock.EXPECT().CurrentLayer().Return(currLayer).AnyTimes() - atx := publishAtxV1(t, tab, sig.NodeID(), posEpoch, &currLayer, layersPerEpoch) + atx := publishAtxV1(t, tab, sig.NodeID(), posEpoch, &currLayer) require.NotNil(t, atx) // state is cleaned up diff --git a/activation/builder_v2_test.go b/activation/builder_v2_test.go index 0054147f4e..e4b34bfaaa 100644 --- a/activation/builder_v2_test.go +++ b/activation/builder_v2_test.go @@ -49,7 +49,7 @@ func TestBuilder_BuildsInitialAtxV2(t *testing.T) { tab.mValidator.EXPECT().PostV2(gomock.Any(), sig.NodeID(), commitment, &initialPost, post.Challenge, post.NumUnits) var atx wire.ActivationTxV2 - publishAtx(t, tab, sig.NodeID(), posEpoch, &layer, layersPerEpoch, + publishAtx(t, tab, sig.NodeID(), posEpoch, &layer, func(_ context.Context, _ string, got []byte) error { require.NoError(t, codec.Decode(got, &atx)) @@ -86,7 +86,7 @@ func TestBuilder_SwitchesToBuildV2(t *testing.T) { // create and publish ATX V1 tab.mclock.EXPECT().CurrentLayer().Return(layer).Times(4) - atx1 := publishAtxV1(t, tab, sig.NodeID(), posEpoch, &layer, layersPerEpoch) + atx1 := publishAtxV1(t, tab, sig.NodeID(), posEpoch, &layer) require.NotNil(t, atx1) // create and publish ATX V2 @@ -95,7 +95,7 @@ func TestBuilder_SwitchesToBuildV2(t *testing.T) { tab.mclock.EXPECT().CurrentLayer().Return(layer).Times(4) tab.mValidator.EXPECT().VerifyChain(gomock.Any(), atx1.ID(), tab.goldenATXID, gomock.Any()) var atx2 wire.ActivationTxV2 - publishAtx(t, tab, sig.NodeID(), posEpoch, &layer, layersPerEpoch, + publishAtx(t, tab, sig.NodeID(), posEpoch, &layer, func(_ context.Context, _ string, got []byte) error { return codec.Decode(got, &atx2) }) diff --git a/activation/post_supervisor_test.go b/activation/post_supervisor_test.go index f26021a364..5918c9bcb6 100644 --- a/activation/post_supervisor_test.go +++ b/activation/post_supervisor_test.go @@ -42,7 +42,7 @@ func testSetupOpts(t *testing.T) PostSetupOpts { return opts } -func newPostManager(t *testing.T, cfg PostConfig, opts PostSetupOpts) *PostSetupManager { +func newPostManager(t *testing.T, cfg PostConfig) *PostSetupManager { t.Helper() ctrl := gomock.NewController(t) validator := NewMocknipostValidator(ctrl) @@ -159,7 +159,7 @@ func Test_PostSupervisor_StartsServiceCmd(t *testing.T) { require.NoError(t, err) ctrl := gomock.NewController(t) - mgr := newPostManager(t, postCfg, postOpts) + mgr := newPostManager(t, postCfg) builder := NewMockAtxBuilder(ctrl) builder.EXPECT().Register(sig) ps := NewPostSupervisor(log.Named("supervisor"), postCfg, provingOpts, mgr, builder) @@ -196,7 +196,7 @@ func Test_PostSupervisor_Restart_Possible(t *testing.T) { require.NoError(t, err) ctrl := gomock.NewController(t) - mgr := newPostManager(t, postCfg, postOpts) + mgr := newPostManager(t, postCfg) builder := NewMockAtxBuilder(ctrl) builder.EXPECT().Register(sig) ps := NewPostSupervisor(log.Named("supervisor"), postCfg, provingOpts, mgr, builder) @@ -227,7 +227,7 @@ func Test_PostSupervisor_LogFatalOnCrash(t *testing.T) { require.NoError(t, err) ctrl := gomock.NewController(t) - mgr := newPostManager(t, postCfg, postOpts) + mgr := newPostManager(t, postCfg) builder := NewMockAtxBuilder(ctrl) builder.EXPECT().Register(sig) ps := NewPostSupervisor(log.Named("supervisor"), postCfg, provingOpts, mgr, builder) @@ -260,7 +260,7 @@ func Test_PostSupervisor_LogFatalOnInvalidConfig(t *testing.T) { require.NoError(t, err) ctrl := gomock.NewController(t) - mgr := newPostManager(t, postCfg, postOpts) + mgr := newPostManager(t, postCfg) builder := NewMockAtxBuilder(ctrl) builder.EXPECT().Register(sig) ps := NewPostSupervisor(log.Named("supervisor"), postCfg, provingOpts, mgr, builder) diff --git a/api/grpcserver/grpcserver_test.go b/api/grpcserver/grpcserver_test.go index 811fa5a41b..8faafc4f06 100644 --- a/api/grpcserver/grpcserver_test.go +++ b/api/grpcserver/grpcserver_test.go @@ -2451,7 +2451,7 @@ func TestVMAccountUpdates(t *testing.T) { require.Equal(t, len(accounts), i) } -func createAtxs(tb testing.TB, epoch types.EpochID, atxids []types.ATXID) []*types.ActivationTx { +func createAtxs(epoch types.EpochID, atxids []types.ATXID) []*types.ActivationTx { all := make([]*types.ActivationTx, 0, len(atxids)) for _, id := range atxids { atx := &types.ActivationTx{ @@ -2487,7 +2487,7 @@ func TestMeshService_EpochStream(t *testing.T) { epoch := types.EpochID(3) atxids := types.RandomActiveSet(100) - all := createAtxs(t, epoch, atxids) + all := createAtxs(epoch, atxids) var expected, got []types.ATXID for i, vatx := range all { require.NoError(t, atxs.Add(db, vatx, types.AtxBlob{})) diff --git a/api/grpcserver/post_service_test.go b/api/grpcserver/post_service_test.go index f3fddd506b..db573cf10b 100644 --- a/api/grpcserver/post_service_test.go +++ b/api/grpcserver/post_service_test.go @@ -29,7 +29,6 @@ import ( func launchPostSupervisor( tb testing.TB, log *zap.Logger, - cfg Config, serviceCfg activation.PostSupervisorConfig, postOpts activation.PostSetupOpts, ) (types.NodeID, func()) { @@ -74,7 +73,6 @@ func launchPostSupervisor( func launchPostSupervisorTLS( tb testing.TB, log *zap.Logger, - cfg Config, serviceCfg activation.PostSupervisorConfig, postOpts activation.PostSetupOpts, ) (types.NodeID, func()) { @@ -102,7 +100,7 @@ func launchPostSupervisorTLS( close(ch) return ch }) - db := sql.InMemory() + db := sql.InMemoryTest(tb) logger := log.Named("post supervisor") mgr, err := activation.NewPostSetupManager(postCfg, logger, db, atxsdata.New(), goldenATXID, syncer, validator) require.NoError(tb, err) @@ -130,7 +128,7 @@ func Test_GenerateProof(t *testing.T) { serviceCfg := activation.DefaultTestPostServiceConfig() serviceCfg.NodeAddress = fmt.Sprintf("http://%s", cfg.PublicListener) - id, postCleanup := launchPostSupervisor(t, log.Named("supervisor"), cfg, serviceCfg, opts) + id, postCleanup := launchPostSupervisor(t, log.Named("supervisor"), serviceCfg, opts) t.Cleanup(postCleanup) var client activation.PostClient @@ -181,7 +179,7 @@ func Test_GenerateProof_TLS(t *testing.T) { serviceCfg.Cert = filepath.Join(certDir, clientCertName) serviceCfg.Key = filepath.Join(certDir, clientKeyName) - id, postCleanup := launchPostSupervisorTLS(t, log.Named("supervisor"), cfg, serviceCfg, opts) + id, postCleanup := launchPostSupervisorTLS(t, log.Named("supervisor"), serviceCfg, opts) t.Cleanup(postCleanup) var client activation.PostClient @@ -228,7 +226,7 @@ func Test_GenerateProof_Cancel(t *testing.T) { serviceCfg := activation.DefaultTestPostServiceConfig() serviceCfg.NodeAddress = fmt.Sprintf("http://%s", cfg.PublicListener) - id, postCleanup := launchPostSupervisor(t, log.Named("supervisor"), cfg, serviceCfg, opts) + id, postCleanup := launchPostSupervisor(t, log.Named("supervisor"), serviceCfg, opts) t.Cleanup(postCleanup) var client activation.PostClient @@ -268,7 +266,7 @@ func Test_Metadata(t *testing.T) { serviceCfg := activation.DefaultTestPostServiceConfig() serviceCfg.NodeAddress = fmt.Sprintf("http://%s", cfg.PublicListener) - id, postCleanup := launchPostSupervisor(t, log.Named("supervisor"), cfg, serviceCfg, opts) + id, postCleanup := launchPostSupervisor(t, log.Named("supervisor"), serviceCfg, opts) t.Cleanup(postCleanup) var client activation.PostClient @@ -313,15 +311,15 @@ func Test_GenerateProof_MultipleServices(t *testing.T) { serviceCfg.NodeAddress = fmt.Sprintf("http://%s", cfg.PublicListener) // all but one should not be able to register to the node (i.e. open a stream to it). - id, postCleanup := launchPostSupervisor(t, log.Named("supervisor1"), cfg, serviceCfg, opts) + id, postCleanup := launchPostSupervisor(t, log.Named("supervisor1"), serviceCfg, opts) t.Cleanup(postCleanup) opts.DataDir = t.TempDir() - _, postCleanup = launchPostSupervisor(t, log.Named("supervisor2"), cfg, serviceCfg, opts) + _, postCleanup = launchPostSupervisor(t, log.Named("supervisor2"), serviceCfg, opts) t.Cleanup(postCleanup) opts.DataDir = t.TempDir() - _, postCleanup = launchPostSupervisor(t, log.Named("supervisor3"), cfg, serviceCfg, opts) + _, postCleanup = launchPostSupervisor(t, log.Named("supervisor3"), serviceCfg, opts) t.Cleanup(postCleanup) var client activation.PostClient diff --git a/api/grpcserver/v2alpha1/layer.go b/api/grpcserver/v2alpha1/layer.go index 901bb46a28..192f334072 100644 --- a/api/grpcserver/v2alpha1/layer.go +++ b/api/grpcserver/v2alpha1/layer.go @@ -63,10 +63,7 @@ func (s *LayerStreamService) Stream( dbChan := make(chan *spacemeshv2alpha1.Layer, 100) errChan := make(chan error, 1) - ops, err := toLayerOperations(toLayerRequest(request)) - if err != nil { - return status.Error(codes.InvalidArgument, err.Error()) - } + ops := toLayerOperations(toLayerRequest(request)) // send db data to chan to avoid buffer overflow go func() { defer close(dbChan) @@ -201,10 +198,7 @@ func (s *LayerService) List( return nil, status.Error(codes.InvalidArgument, "limit must be set to <= 100") } - ops, err := toLayerOperations(request) - if err != nil { - return nil, status.Error(codes.InvalidArgument, err.Error()) - } + ops := toLayerOperations(request) rst := make([]*spacemeshv2alpha1.Layer, 0, request.Limit) if err := layers.IterateLayersWithBlockOps(s.db, ops, func(layer *layers.Layer) bool { @@ -217,10 +211,10 @@ func (s *LayerService) List( return &spacemeshv2alpha1.LayerList{Layers: rst}, nil } -func toLayerOperations(filter *spacemeshv2alpha1.LayerRequest) (builder.Operations, error) { +func toLayerOperations(filter *spacemeshv2alpha1.LayerRequest) builder.Operations { ops := builder.Operations{} if filter == nil { - return ops, nil + return ops } if filter.StartLayer != 0 { @@ -259,7 +253,7 @@ func toLayerOperations(filter *spacemeshv2alpha1.LayerRequest) (builder.Operatio }) } - return ops, nil + return ops } func toLayer(layer *layers.Layer) *spacemeshv2alpha1.Layer { diff --git a/atxsdata/warmup_test.go b/atxsdata/warmup_test.go index c2051fa1c7..371eb92377 100644 --- a/atxsdata/warmup_test.go +++ b/atxsdata/warmup_test.go @@ -17,11 +17,12 @@ import ( "github.com/spacemeshos/go-spacemesh/sql/mocks" ) +var nonce = types.VRFPostIndex(1) + func gatx( id types.ATXID, epoch types.EpochID, smesher types.NodeID, - nonce types.VRFPostIndex, ) types.ActivationTx { atx := &types.ActivationTx{ NumUnits: 1, @@ -40,14 +41,13 @@ func TestWarmup(t *testing.T) { t.Run("sanity", func(t *testing.T) { db := sql.InMemory() applied := types.LayerID(10) - nonce := types.VRFPostIndex(1) data := []types.ActivationTx{ - gatx(types.ATXID{1, 1}, 1, types.NodeID{1}, nonce), - gatx(types.ATXID{1, 2}, 1, types.NodeID{2}, nonce), - gatx(types.ATXID{2, 1}, 2, types.NodeID{1}, nonce), - gatx(types.ATXID{2, 2}, 2, types.NodeID{2}, nonce), - gatx(types.ATXID{3, 2}, 3, types.NodeID{2}, nonce), - gatx(types.ATXID{3, 3}, 3, types.NodeID{3}, nonce), + gatx(types.ATXID{1, 1}, 1, types.NodeID{1}), + gatx(types.ATXID{1, 2}, 1, types.NodeID{2}), + gatx(types.ATXID{2, 1}, 2, types.NodeID{1}), + gatx(types.ATXID{2, 2}, 2, types.NodeID{2}), + gatx(types.ATXID{3, 2}, 3, types.NodeID{2}), + gatx(types.ATXID{3, 3}, 3, types.NodeID{3}), } for i := range data { require.NoError(t, atxs.Add(db, &data[i], types.AtxBlob{})) @@ -74,8 +74,7 @@ func TestWarmup(t *testing.T) { }) t.Run("db failures", func(t *testing.T) { db := sql.InMemory() - nonce := types.VRFPostIndex(1) - data := gatx(types.ATXID{1, 1}, 1, types.NodeID{1}, nonce) + data := gatx(types.ATXID{1, 1}, 1, types.NodeID{1}) require.NoError(t, atxs.Add(db, &data, types.AtxBlob{})) exec := mocks.NewMockExecutor(gomock.NewController(t)) diff --git a/beacon/handlers.go b/beacon/handlers.go index 89d838e985..e090be7115 100644 --- a/beacon/handlers.go +++ b/beacon/handlers.go @@ -409,7 +409,7 @@ func (pd *ProtocolDriver) HandleFollowingVotes(ctx context.Context, peer p2p.Pee return errUntimelyMessage } - nodeID, err := pd.verifyFollowingVotes(ctx, m) + nodeID, err := pd.verifyFollowingVotes(m) if err != nil { return err } @@ -434,7 +434,7 @@ func (pd *ProtocolDriver) HandleFollowingVotes(ctx context.Context, peer p2p.Pee return nil } -func (pd *ProtocolDriver) verifyFollowingVotes(ctx context.Context, m FollowingVotingMessage) (types.NodeID, error) { +func (pd *ProtocolDriver) verifyFollowingVotes(m FollowingVotingMessage) (types.NodeID, error) { messageBytes := codec.MustEncode(&m.FollowingVotingMessageBody) if !pd.edVerifier.Verify(signing.BEACON_FOLLOWUP_MSG, m.SmesherID, messageBytes, m.Signature) { return types.EmptyNodeID, fmt.Errorf("[round %v] verify signature %s: failed", types.FirstRound, m.Signature) diff --git a/beacon/handlers_test.go b/beacon/handlers_test.go index 3fe1bcdd98..a37f16a6b6 100644 --- a/beacon/handlers_test.go +++ b/beacon/handlers_test.go @@ -17,14 +17,18 @@ import ( "github.com/spacemeshos/go-spacemesh/signing" ) -const epochWeight = uint64(100) +const ( + epochWeight = uint64(100) + // FIXME: pulled out to satisfy the linter but needs to be + // actually modified in tests to run different values. + epoch = types.EpochID(10) + round = types.RoundID(5) +) func createProtocolDriverWithFirstRoundVotes( t *testing.T, signer *signing.EdSigner, malicious bool, - epoch types.EpochID, - round types.RoundID, ) (*testProtocolDriver, proposalList) { tpd := setUpProtocolDriver(t) tpd.setBeginProtocol(context.Background()) @@ -131,7 +135,6 @@ func checkProposals(t *testing.T, pd *ProtocolDriver, epoch types.EpochID, expec } func createFirstVote( - t *testing.T, signer *signing.EdSigner, epoch types.EpochID, valid, pValid proposalList, @@ -185,10 +188,8 @@ func checkFirstIncomingVotes( } func createFollowingVote( - t *testing.T, signer *signing.EdSigner, epoch types.EpochID, - round types.RoundID, bitVector []byte, corruptSignature bool, ) *FollowingVotingMessage { @@ -874,7 +875,7 @@ func Test_HandleFirstVotes_Success(t *testing.T) { } createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -909,7 +910,7 @@ func Test_HandleFirstVotes_Malicious(t *testing.T) { } createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -941,7 +942,7 @@ func Test_HandleFirstVotes_Shutdown(t *testing.T) { } createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -966,7 +967,7 @@ func Test_HandleFirstVotes_NotInProtocol(t *testing.T) { signer.NodeID(): {atxid: createATX(t, tpd.cdb, epoch.FirstLayer().Sub(1), signer, 10, time.Now())}, } createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -992,7 +993,7 @@ func Test_handleFirstVotes_CorruptMsg(t *testing.T) { signer.NodeID(): {atxid: createATX(t, tpd.cdb, epoch.FirstLayer().Sub(1), signer, 10, time.Now())}, } createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1019,7 +1020,7 @@ func Test_handleFirstVotes_WrongEpoch(t *testing.T) { createEpochState(t, tpd.ProtocolDriver, epoch-1, minerAtxs, nil) createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) createEpochState(t, tpd.ProtocolDriver, epoch+1, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch+1, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch+1, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1032,7 +1033,7 @@ func Test_handleFirstVotes_WrongEpoch(t *testing.T) { checkVoted(t, tpd.ProtocolDriver, epoch+1, signer, types.FirstRound, false) checkFirstIncomingVotes(t, tpd.ProtocolDriver, epoch+1, map[types.NodeID]proposalList{}) - msg = createFirstVote(t, signer, epoch-1, validVotes, pValidVotes, false) + msg = createFirstVote(signer, epoch-1, validVotes, pValidVotes, false) msgBytes, err = codec.Encode(msg) require.NoError(t, err) @@ -1060,7 +1061,7 @@ func Test_handleFirstVotes_TooLate(t *testing.T) { signer.NodeID(): {atxid: createATX(t, tpd.cdb, epoch.FirstLayer().Sub(1), signer, 10, time.Now())}, } createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1088,7 +1089,7 @@ func Test_HandleFirstVotes_FailedToVerifySig(t *testing.T) { signer.NodeID(): {atxid: createATX(t, tpd.cdb, epoch.FirstLayer().Sub(1), signer, 10, time.Now())}, } createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, true) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, true) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1115,7 +1116,7 @@ func Test_HandleFirstVotes_AlreadyVoted(t *testing.T) { signer.NodeID(): {atxid: createATX(t, tpd.cdb, epoch.FirstLayer().Sub(1), signer, 10, time.Now())}, } createEpochState(t, tpd.ProtocolDriver, epoch, minerAtxs, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1130,7 +1131,7 @@ func Test_HandleFirstVotes_AlreadyVoted(t *testing.T) { checkFirstIncomingVotes(t, tpd.ProtocolDriver, epoch, expected) // the same ed key will not cause double-vote - msg2 := createFirstVote(t, signer, epoch, validVotes, proposalList{}, false) + msg2 := createFirstVote(signer, epoch, validVotes, proposalList{}, false) msgBytes2, err := codec.Encode(msg2) require.NoError(t, err) @@ -1153,7 +1154,7 @@ func Test_HandleFirstVotes_MinerMissingATX(t *testing.T) { signer, err := signing.NewEdSigner() require.NoError(t, err) createEpochState(t, tpd.ProtocolDriver, epoch, map[types.NodeID]*minerInfo{}, nil) - msg := createFirstVote(t, signer, epoch, validVotes, pValidVotes, false) + msg := createFirstVote(signer, epoch, validVotes, pValidVotes, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1168,14 +1169,12 @@ func Test_HandleFirstVotes_MinerMissingATX(t *testing.T) { func Test_HandleFollowingVotes_Success(t *testing.T) { t.Parallel() - const epoch = types.EpochID(10) - const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch, round, []byte{0b101}, false) + msg := createFollowingVote(signer, epoch, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1202,10 +1201,10 @@ func Test_HandleFollowingVotes_Malicious(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, true, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, true) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch, round, []byte{0b101}, false) + msg := createFollowingVote(signer, epoch, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1228,11 +1227,11 @@ func Test_HandleFollowingVotes_Shutdown(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) tpd.Close() // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch, round, []byte{0b101}, false) + msg := createFollowingVote(signer, epoch, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1249,10 +1248,10 @@ func Test_HandleFollowingVotes_NotInProtocol(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch, round, []byte{0b101}, false) + msg := createFollowingVote(signer, epoch, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1270,10 +1269,10 @@ func Test_handleFollowingVotes_CorruptMsg(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch, round, []byte{0b101}, false) + msg := createFollowingVote(signer, epoch, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1290,7 +1289,7 @@ func Test_handleFollowingVotes_WrongEpoch(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) minerAtxs := map[types.NodeID]*minerInfo{ signer.NodeID(): {atxid: createATX(t, tpd.cdb, (epoch - 1).FirstLayer().Sub(1), signer, 10, time.Now())}, } @@ -1301,7 +1300,7 @@ func Test_handleFollowingVotes_WrongEpoch(t *testing.T) { createEpochState(t, tpd.ProtocolDriver, epoch+1, minerAtxs, nil) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch+1, round, []byte{0b101}, false) + msg := createFollowingVote(signer, epoch+1, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1313,7 +1312,7 @@ func Test_handleFollowingVotes_WrongEpoch(t *testing.T) { checkVoted(t, tpd.ProtocolDriver, epoch+1, signer, round, false) checkVoteMargins(t, tpd.ProtocolDriver, epoch+1, emptyVoteMargins(proposalList{})) - msg = createFollowingVote(t, signer, epoch-1, round, []byte{0b101}, false) + msg = createFollowingVote(signer, epoch-1, []byte{0b101}, false) msgBytes, err = codec.Encode(msg) require.NoError(t, err) @@ -1333,10 +1332,10 @@ func Test_handleFollowingVotes_TooEarly(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch, round, []byte{0b101}, false) + msg := createFollowingVote(signer, epoch, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1356,10 +1355,10 @@ func Test_handleFollowingVotes_FailedToVerifySig(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch, round, []byte{0b101}, true) + msg := createFollowingVote(signer, epoch, []byte{0b101}, true) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1378,10 +1377,10 @@ func Test_handleFollowingVotes_AlreadyVoted(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, signer, epoch, round, []byte{0b101}, false) + msg := createFollowingVote(signer, epoch, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1401,7 +1400,7 @@ func Test_handleFollowingVotes_AlreadyVoted(t *testing.T) { checkVoteMargins(t, tpd.ProtocolDriver, epoch, expected) // now vote again - msg = createFollowingVote(t, signer, epoch, round, []byte{0b111}, false) + msg = createFollowingVote(signer, epoch, []byte{0b111}, false) msgBytes, err = codec.Encode(msg) require.NoError(t, err) @@ -1420,13 +1419,13 @@ func Test_handleFollowingVotes_MinerMissingATX(t *testing.T) { const round = types.RoundID(5) signer, err := signing.NewEdSigner() require.NoError(t, err) - tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false, epoch, round) + tpd, plist := createProtocolDriverWithFirstRoundVotes(t, signer, false) miner, err := signing.NewEdSigner() require.NoError(t, err) // this msg will contain a bit vector that set bit 0 and 2 - msg := createFollowingVote(t, miner, epoch, round, []byte{0b101}, false) + msg := createFollowingVote(miner, epoch, []byte{0b101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) @@ -1442,7 +1441,6 @@ func Test_handleFollowingVotes_IgnoreUnknownProposal(t *testing.T) { t.Parallel() const epoch = types.EpochID(10) - const round = types.RoundID(5) tpd := setUpProtocolDriver(t) tpd.setBeginProtocol(context.Background()) signer, err := signing.NewEdSigner() @@ -1469,7 +1467,7 @@ func Test_handleFollowingVotes_IgnoreUnknownProposal(t *testing.T) { // this msg will contain a bit vector that set bit 0 and 2-4. the miner voted for two proposals // we don't know about locally - msg := createFollowingVote(t, signer, epoch, round, []byte{0b11101}, false) + msg := createFollowingVote(signer, epoch, []byte{0b11101}, false) msgBytes, err := codec.Encode(msg) require.NoError(t, err) diff --git a/blocks/utils.go b/blocks/utils.go index 96dcd82b3a..9b2ff2b5b7 100644 --- a/blocks/utils.go +++ b/blocks/utils.go @@ -67,7 +67,7 @@ func getProposalMetadata( meshHashes = make(map[types.Hash32]*meshState) err error ) - md.tickHeight, md.rewards, err = rewardInfoAndHeight(cfg, db, atxs, proposals) + md.tickHeight, md.rewards, err = rewardInfoAndHeight(db, atxs, proposals) if err != nil { return nil, err } @@ -231,7 +231,6 @@ func toUint64Slice(b []byte) []uint64 { } func rewardInfoAndHeight( - cfg Config, db *sql.Database, atxs *atxsdata.Data, props []*types.Proposal, diff --git a/cmd/merge-nodes/internal/merge_action.go b/cmd/merge-nodes/internal/merge_action.go index c516ff297c..1964de514f 100644 --- a/cmd/merge-nodes/internal/merge_action.go +++ b/cmd/merge-nodes/internal/merge_action.go @@ -53,7 +53,7 @@ func MergeDBs(ctx context.Context, dbLog *zap.Logger, from, to string) error { defer dstDB.Close() // target database exists, check if there is at least one key in the target key directory // not named supervisedIDKeyFileName - if err := checkIdentities(dbLog, to); err != nil { + if err := checkIdentities(to); err != nil { switch { case errors.Is(err, ErrSupervisedNode): dbLog.Sugar().Errorf( @@ -76,7 +76,7 @@ func MergeDBs(ctx context.Context, dbLog *zap.Logger, from, to string) error { return fmt.Errorf("close source database: %w", err) } - if err := checkIdentities(dbLog, from); err != nil { + if err := checkIdentities(from); err != nil { switch { case errors.Is(err, ErrSupervisedNode): dbLog.Sugar().Errorf( @@ -226,7 +226,7 @@ func openDB(dbLog *zap.Logger, path string) (*localsql.Database, error) { return db, nil } -func checkIdentities(dbLog *zap.Logger, path string) error { +func checkIdentities(path string) error { dir := filepath.Join(path, keyDir) if err := os.MkdirAll(dir, 0o700); err != nil { return err diff --git a/fetch/cache_test.go b/fetch/cache_test.go index 7482fbc935..b2a2bc2948 100644 --- a/fetch/cache_test.go +++ b/fetch/cache_test.go @@ -15,11 +15,12 @@ import ( ) // getCachedEntry is a thread-safe cache get helper. -func getCachedEntry(cache *HashPeersCache, hash types.Hash32) (HashPeers, bool) { +func getCachedEntry(cache *HashPeersCache, hash types.Hash32) HashPeers { cache.mu.Lock() defer cache.mu.Unlock() - return cache.get(hash) + hp, _ := cache.get(hash) + return hp } func TestAdd(t *testing.T) { @@ -45,7 +46,7 @@ func TestAdd(t *testing.T) { cache.Add(hash, peer3) }() wg.Wait() - hashPeers, _ := getCachedEntry(cache, hash) + hashPeers := getCachedEntry(cache, hash) require.Len(t, hashPeers, 3) }) t.Run("2Hashes1Peer", func(t *testing.T) { @@ -64,9 +65,9 @@ func TestAdd(t *testing.T) { cache.Add(hash2, peer) }() wg.Wait() - hash1Peers, _ := getCachedEntry(cache, hash1) + hash1Peers := getCachedEntry(cache, hash1) require.Len(t, hash1Peers, 1) - hash2Peers, _ := getCachedEntry(cache, hash2) + hash2Peers := getCachedEntry(cache, hash2) require.Len(t, hash2Peers, 1) }) } @@ -144,11 +145,11 @@ func TestRegisterPeerHashes(t *testing.T) { hash3 := types.RandomHash() peer1 := p2p.Peer("test_peer_1") cache.RegisterPeerHashes(peer1, []types.Hash32{hash1, hash2, hash3}) - hash1Peers, _ := getCachedEntry(cache, hash1) + hash1Peers := getCachedEntry(cache, hash1) require.Len(t, hash1Peers, 1) - hash2Peers, _ := getCachedEntry(cache, hash2) + hash2Peers := getCachedEntry(cache, hash2) require.Len(t, hash2Peers, 1) - hash3Peers, _ := getCachedEntry(cache, hash3) + hash3Peers := getCachedEntry(cache, hash3) require.Len(t, hash3Peers, 1) }) } diff --git a/fetch/fetch.go b/fetch/fetch.go index 94e93caea6..7d379f0fcd 100644 --- a/fetch/fetch.go +++ b/fetch/fetch.go @@ -786,7 +786,7 @@ func (f *Fetch) streamBatch(peer p2p.Peer, batch *batchInfo) error { batchMap := batch.toMap() n, err := server.ReadResponse(s, func(respLen uint32) (n int, err error) { - return f.receiveStreamedBatch(ctx, s, batch, batchMap) + return f.receiveStreamedBatch(s, batch, batchMap) }) if err != nil { return n, err @@ -819,7 +819,6 @@ func (f *Fetch) streamBatch(peer p2p.Peer, batch *batchInfo) error { } func (f *Fetch) receiveStreamedBatch( - ctx context.Context, s io.ReadWriter, batch *batchInfo, batchMap map[types.Hash32]RequestMessage, diff --git a/fetch/handler_test.go b/fetch/handler_test.go index 24749e1a2d..8b96258f2a 100644 --- a/fetch/handler_test.go +++ b/fetch/handler_test.go @@ -260,7 +260,7 @@ func TestHandleMeshHashReq(t *testing.T) { } } -func newAtx(t *testing.T, published types.EpochID) *types.ActivationTx { +func newAtx(published types.EpochID) *types.ActivationTx { atx := &types.ActivationTx{ PublishEpoch: published, NumUnits: 2, @@ -295,7 +295,7 @@ func TestHandleEpochInfoReq(t *testing.T) { var expected EpochData if !tc.missingData { for i := 0; i < 10; i++ { - vatx := newAtx(t, epoch) + vatx := newAtx(epoch) require.NoError(t, atxs.Add(th.cdb, vatx, types.AtxBlob{})) expected.AtxIDs = append(expected.AtxIDs, vatx.ID()) } @@ -344,7 +344,7 @@ func testHandleEpochInfoReqWithQueryCache( var expected EpochData for i := 0; i < 10; i++ { - vatx := newAtx(t, epoch) + vatx := newAtx(epoch) require.NoError(t, atxs.Add(th.cdb, vatx, types.AtxBlob{})) atxs.AtxAdded(th.cdb, vatx) expected.AtxIDs = append(expected.AtxIDs, vatx.ID()) @@ -363,7 +363,7 @@ func testHandleEpochInfoReqWithQueryCache( } // Add another ATX which should be appended to the cached slice - vatx := newAtx(t, epoch) + vatx := newAtx(epoch) require.NoError(t, atxs.Add(th.cdb, vatx, types.AtxBlob{})) atxs.AtxAdded(th.cdb, vatx) expected.AtxIDs = append(expected.AtxIDs, vatx.ID()) diff --git a/fetch/p2p_test.go b/fetch/p2p_test.go index b76929320c..57c20a629e 100644 --- a/fetch/p2p_test.go +++ b/fetch/p2p_test.go @@ -86,7 +86,6 @@ func createP2PFetch( clientStreaming, serverStreaming, sqlCache bool, - opts ...Option, ) (*testP2PFetch, context.Context) { lg := zaptest.NewLogger(t) ctx, cancel := context.WithTimeout(context.Background(), time.Second*30) @@ -171,7 +170,7 @@ func createP2PFetch( func (tpf *testP2PFetch) createATXs(epoch types.EpochID) []types.ATXID { atxIDs := make([]types.ATXID, 10) for i := range atxIDs { - atx := newAtx(tpf.t, epoch) + atx := newAtx(epoch) require.NoError(tpf.t, atxs.Add(tpf.serverCDB, atx, types.AtxBlob{})) atxIDs[i] = atx.ID() } @@ -182,7 +181,6 @@ func (tpf *testP2PFetch) verifyGetHash( toCall func() error, errStr, kind, protocol string, h types.Hash32, - id []byte, data []byte, ) { srv := tpf.serverFetch.servers[protocol].(*server.Server) @@ -351,12 +349,12 @@ func TestP2PGetATXs(t *testing.T) { t, "database: no free connection", func(t *testing.T, ctx context.Context, tpf *testP2PFetch, errStr string) { epoch := types.EpochID(11) - atx := newAtx(tpf.t, epoch) + atx := newAtx(epoch) blob := types.AtxBlob{Blob: types.RandomBytes(100)} require.NoError(tpf.t, atxs.Add(tpf.serverCDB, atx, blob)) tpf.verifyGetHash( func() error { return tpf.clientFetch.GetAtxs(context.Background(), []types.ATXID{atx.ID()}) }, - errStr, "atx", "hs/1", types.Hash32(atx.ID()), atx.ID().Bytes(), + errStr, "atx", "hs/1", types.Hash32(atx.ID()), blob.Blob, ) }) @@ -371,7 +369,7 @@ func TestP2PGetPoet(t *testing.T) { tpf.verifyGetHash( func() error { return tpf.clientFetch.GetPoetProof(context.Background(), types.Hash32(ref)) }, - errStr, "poet", "hs/1", types.Hash32(ref), ref[:], + errStr, "poet", "hs/1", types.Hash32(ref), []byte("proof1"), ) }) @@ -393,7 +391,7 @@ func TestP2PGetBallot(t *testing.T) { tpf.verifyGetHash( func() error { return tpf.clientFetch.GetBallots(context.Background(), []types.BallotID{b.ID()}) }, - errStr, "ballot", "hs/1", b.ID().AsHash32(), b.ID().Bytes(), + errStr, "ballot", "hs/1", b.ID().AsHash32(), codec.MustEncode(b), ) }) @@ -412,7 +410,7 @@ func TestP2PGetActiveSet(t *testing.T) { tpf.verifyGetHash( func() error { return tpf.clientFetch.GetActiveSet(context.Background(), id) }, - errStr, "activeset", "as/1", id, id.Bytes(), + errStr, "activeset", "as/1", id, codec.MustEncode(set), ) }) @@ -428,7 +426,7 @@ func TestP2PGetBlock(t *testing.T) { tpf.verifyGetHash( func() error { return tpf.clientFetch.GetBlocks(context.Background(), []types.BlockID{bk.ID()}) }, - errStr, "block", "hs/1", bk.ID().AsHash32(), bk.ID().Bytes(), + errStr, "block", "hs/1", bk.ID().AsHash32(), codec.MustEncode(bk), ) }) @@ -464,7 +462,7 @@ func TestP2PGetProp(t *testing.T) { return tpf.clientFetch.GetProposals( context.Background(), []types.ProposalID{id}) }, - errStr, "prop", "hs/1", proposal.ID().AsHash32(), proposal.ID().Bytes(), + errStr, "prop", "hs/1", proposal.ID().AsHash32(), codec.MustEncode(proposal)) }) } @@ -479,7 +477,7 @@ func TestP2PGetBlockTransactions(t *testing.T) { require.NoError(t, transactions.Add(tpf.serverCDB, &tx, time.Now())) tpf.verifyGetHash( func() error { return tpf.clientFetch.GetBlockTxs(context.Background(), []types.TransactionID{tx.ID}) }, - errStr, "txBlock", "hs/1", types.Hash32(tx.ID), tx.ID.Bytes(), + errStr, "txBlock", "hs/1", types.Hash32(tx.ID), tx.Raw, ) }) @@ -497,9 +495,8 @@ func TestP2PGetProposalTransactions(t *testing.T) { func() error { return tpf.clientFetch.GetProposalTxs(context.Background(), []types.TransactionID{tx.ID}) }, - errStr, "txProposal", "hs/1", types.Hash32(tx.ID), tx.ID.Bytes(), - tx.Raw, - ) + errStr, "txProposal", "hs/1", types.Hash32(tx.ID), + tx.Raw) }) } @@ -512,7 +509,7 @@ func TestP2PGetMalfeasanceProofs(t *testing.T) { require.NoError(t, identities.SetMalicious(tpf.serverCDB, nid, proof, time.Now())) tpf.verifyGetHash( func() error { return tpf.clientFetch.GetMalfeasanceProofs(context.Background(), []types.NodeID{nid}) }, - errStr, "mal", "hs/1", types.Hash32(nid), nid.Bytes(), + errStr, "mal", "hs/1", types.Hash32(nid), proof, ) }) diff --git a/genvm/vm_test.go b/genvm/vm_test.go index 4ee7934da8..a036741a8f 100644 --- a/genvm/vm_test.go +++ b/genvm/vm_test.go @@ -465,11 +465,13 @@ func (t *tester) estimateSpendGas(principal, to, amount int, nonce core.Nonce) i int(core.TxDataGas(len(tx))) } -func (t *tester) estimateDrainGas(principal, vault, to, amount int, nonce core.Nonce) int { +const vaultVal = 20 + +func (t *tester) estimateDrainGas(principal, to, amount int, nonce core.Nonce) int { require.IsType(t, &vestingAccount{}, t.accounts[principal]) vestacc := t.accounts[principal].(*vestingAccount) tx := vestacc.drainVault( - t.accounts[vault].getAddress(), + t.accounts[vaultVal].getAddress(), t.accounts[to].getAddress(), uint64(amount), nonce) @@ -704,7 +706,7 @@ type layertc struct { headers map[int]struct{} // is vm expected to return the header } -func singleWalletTestCases(defaultGasPrice int, template core.Address, ref *tester) []templateTestCase { +func singleWalletTestCases(template core.Address, ref *tester) []templateTestCase { return []templateTestCase{ { desc: "Sanity", @@ -1459,10 +1461,12 @@ func runTestCases(t *testing.T, tcs []templateTestCase, genTester func(t *testin } } -func testWallet(t *testing.T, defaultGasPrice int, template core.Address, genTester func(t *testing.T) *tester) { +const defaultGasPrice = 1 + +func testWallet(t *testing.T, template core.Address, genTester func(t *testing.T) *tester) { t.Parallel() runTestCases(t, - singleWalletTestCases(defaultGasPrice, template, genTester(t)), + singleWalletTestCases(template, genTester(t)), genTester, ) } @@ -1473,10 +1477,9 @@ func TestWallets(t *testing.T) { funded = 10 // number of funded accounts, included in genesis total = 100 // total number of accounts - defaultGasPrice = 1 ) t.Run("SingleSig", func(t *testing.T) { - testWallet(t, defaultGasPrice, wallet.TemplateAddress, func(t *testing.T) *tester { + testWallet(t, wallet.TemplateAddress, func(t *testing.T) *tester { return newTester(t). addSingleSig(funded). applyGenesisWithBalance(). @@ -1485,7 +1488,7 @@ func TestWallets(t *testing.T) { }) t.Run("MultiSig13", func(t *testing.T) { const n = 3 - testWallet(t, defaultGasPrice, multisig.TemplateAddress, func(t *testing.T) *tester { + testWallet(t, multisig.TemplateAddress, func(t *testing.T) *tester { return newTester(t). addMultisig(funded, 1, n). applyGenesisWithBalance(). @@ -1494,7 +1497,7 @@ func TestWallets(t *testing.T) { }) t.Run("MultiSig25", func(t *testing.T) { const n = 5 - testWallet(t, defaultGasPrice, multisig.TemplateAddress, func(t *testing.T) *tester { + testWallet(t, multisig.TemplateAddress, func(t *testing.T) *tester { return newTester(t). addMultisig(funded, 2, n). applyGenesisWithBalance(). @@ -1503,7 +1506,7 @@ func TestWallets(t *testing.T) { }) t.Run("MultiSig310", func(t *testing.T) { const n = 10 - testWallet(t, defaultGasPrice, multisig.TemplateAddress, func(t *testing.T) *tester { + testWallet(t, multisig.TemplateAddress, func(t *testing.T) *tester { return newTester(t). addMultisig(funded, 3, n). applyGenesisWithBalance(). @@ -1512,7 +1515,7 @@ func TestWallets(t *testing.T) { }) t.Run("Vesting13", func(t *testing.T) { const n = 3 - testWallet(t, defaultGasPrice, vesting.TemplateAddress, func(t *testing.T) *tester { + testWallet(t, vesting.TemplateAddress, func(t *testing.T) *tester { return newTester(t). addVesting(funded, 1, n). applyGenesisWithBalance(). @@ -1521,7 +1524,7 @@ func TestWallets(t *testing.T) { }) t.Run("Vesting25", func(t *testing.T) { const n = 5 - testWallet(t, defaultGasPrice, vesting.TemplateAddress, func(t *testing.T) *tester { + testWallet(t, vesting.TemplateAddress, func(t *testing.T) *tester { return newTester(t). addVesting(funded, 2, n). applyGenesisWithBalance(). @@ -1530,7 +1533,7 @@ func TestWallets(t *testing.T) { }) t.Run("Vesting310", func(t *testing.T) { const n = 10 - testWallet(t, defaultGasPrice, vesting.TemplateAddress, func(t *testing.T) *tester { + testWallet(t, vesting.TemplateAddress, func(t *testing.T) *tester { return newTester(t). addVesting(funded, 3, n). applyGenesisWithBalance(). @@ -1802,7 +1805,7 @@ func TestVestingWithVault(t *testing.T) { &drainVault{0, 20, 11, 500}, }, expected: map[int]change{ - 0: spent{amount: ref.estimateDrainGas(0, 20, 11, 500, 2)}, + 0: spent{amount: ref.estimateDrainGas(0, 11, 500, 2)}, 20: spent{amount: 500}, 11: earned{amount: 500}, }, @@ -1837,7 +1840,7 @@ func TestVestingWithVault(t *testing.T) { }, expected: map[int]change{ // gas was spent on failed tx - 0: spent{amount: ref.estimateDrainGas(0, 20, 11, 1, 2)}, + 0: spent{amount: ref.estimateDrainGas(0, 11, 1, 2)}, }, }, { @@ -1855,9 +1858,9 @@ func TestVestingWithVault(t *testing.T) { }, expected: map[int]change{ // gas spent on one successful and two unsuccessful txs - 0: spent{amount: ref.estimateDrainGas(0, 20, 11, 5501, 2) + - ref.estimateDrainGas(0, 20, 11, 5500, 2) + - ref.estimateDrainGas(0, 20, 11, 1, 3)}, + 0: spent{amount: ref.estimateDrainGas(0, 11, 5501, 2) + + ref.estimateDrainGas(0, 11, 5500, 2) + + ref.estimateDrainGas(0, 11, 1, 3)}, 20: spent{amount: 5500}, 11: earned{amount: 5500}, }, @@ -1893,7 +1896,7 @@ func TestVestingWithVault(t *testing.T) { expected: map[int]change{ 0: same{}, 1: spent{ - amount: ref.estimateDrainGas(1, 20, 11, 100, 1), + amount: ref.estimateDrainGas(1, 11, 100, 1), change: nonce{increased: 1}, }, 11: same{}, @@ -1941,9 +1944,9 @@ func TestVestingWithVault(t *testing.T) { }, expected: map[int]change{ 0: spent{ - amount: ref.estimateDrainGas(0, 20, 11, 1001, 3) + - ref.estimateDrainGas(0, 20, 11, 1000, 4) + - ref.estimateDrainGas(0, 20, 11, 1000, 5), + amount: ref.estimateDrainGas(0, 11, 1001, 3) + + ref.estimateDrainGas(0, 11, 1000, 4) + + ref.estimateDrainGas(0, 11, 1000, 5), }, 11: earned{amount: 1000}, 20: spent{amount: 1000}, @@ -1964,8 +1967,8 @@ func TestVestingWithVault(t *testing.T) { 0: vault.ErrAmountNotAvailable, }, expected: map[int]change{ - 0: spent{amount: ref.estimateDrainGas(0, 20, 10, 10000, 5) + - ref.estimateDrainGas(0, 20, 10, 5000, 6)}, + 0: spent{amount: ref.estimateDrainGas(0, 10, 10000, 5) + + ref.estimateDrainGas(0, 10, 5000, 6)}, 10: earned{amount: 5000}, 20: spent{amount: 5000}, }, @@ -1985,8 +1988,8 @@ func TestVestingWithVault(t *testing.T) { 0: vault.ErrAmountNotAvailable, }, expected: map[int]change{ - 0: spent{amount: ref.estimateDrainGas(0, 20, 9, 5001, 7) + - ref.estimateDrainGas(0, 20, 9, 5000, 8)}, + 0: spent{amount: ref.estimateDrainGas(0, 9, 5001, 7) + + ref.estimateDrainGas(0, 9, 5000, 8)}, 9: earned{amount: 5000}, 20: spent{amount: 5000}, }, diff --git a/hare3/eligibility/oracle.go b/hare3/eligibility/oracle.go index c33cf0c50b..9b4515ece1 100644 --- a/hare3/eligibility/oracle.go +++ b/hare3/eligibility/oracle.go @@ -178,7 +178,7 @@ func (o *Oracle) resetCacheOnSynced(ctx context.Context) { } // buildVRFMessage builds the VRF message used as input for hare eligibility validation. -func (o *Oracle) buildVRFMessage(ctx context.Context, layer types.LayerID, round uint32) ([]byte, error) { +func (o *Oracle) buildVRFMessage(layer types.LayerID, round uint32) ([]byte, error) { beacon, err := o.beacons.GetBeacon(layer.GetEpoch()) if err != nil { return nil, fmt.Errorf("get beacon: %w", err) @@ -240,7 +240,7 @@ func (o *Oracle) prepareEligibilityCheck( return 0, fixed.Fixed{}, fixed.Fixed{}, true, err } - msg, err := o.buildVRFMessage(ctx, layer, round) + msg, err := o.buildVRFMessage(layer, round) if err != nil { logger.Warn("could not build vrf message", zap.Error(err)) return 0, fixed.Fixed{}, fixed.Fixed{}, true, err diff --git a/hare3/eligibility/oracle_test.go b/hare3/eligibility/oracle_test.go index d6ae2e4a58..6caacc1165 100644 --- a/hare3/eligibility/oracle_test.go +++ b/hare3/eligibility/oracle_test.go @@ -451,7 +451,7 @@ func TestBuildVRFMessage_BeaconError(t *testing.T) { o := defaultOracle(t) errUnknown := errors.New("unknown") o.mBeacon.EXPECT().GetBeacon(gomock.Any()).Return(types.EmptyBeacon, errUnknown).Times(1) - msg, err := o.buildVRFMessage(context.Background(), types.LayerID(1), 1) + msg, err := o.buildVRFMessage(types.LayerID(1), 1) require.ErrorIs(t, err, errUnknown) require.Nil(t, msg) } @@ -462,24 +462,24 @@ func TestBuildVRFMessage(t *testing.T) { secondLayer := firstLayer.Add(1) beacon := types.RandomBeacon() o.mBeacon.EXPECT().GetBeacon(firstLayer.GetEpoch()).Return(beacon, nil).Times(1) - m1, err := o.buildVRFMessage(context.Background(), firstLayer, 2) + m1, err := o.buildVRFMessage(firstLayer, 2) require.NoError(t, err) // check not same for different round o.mBeacon.EXPECT().GetBeacon(firstLayer.GetEpoch()).Return(beacon, nil).Times(1) - m3, err := o.buildVRFMessage(context.Background(), firstLayer, 3) + m3, err := o.buildVRFMessage(firstLayer, 3) require.NoError(t, err) require.NotEqual(t, m1, m3) // check not same for different layer o.mBeacon.EXPECT().GetBeacon(firstLayer.GetEpoch()).Return(beacon, nil).Times(1) - m4, err := o.buildVRFMessage(context.Background(), secondLayer, 2) + m4, err := o.buildVRFMessage(secondLayer, 2) require.NoError(t, err) require.NotEqual(t, m1, m4) // check same call returns same result o.mBeacon.EXPECT().GetBeacon(firstLayer.GetEpoch()).Return(beacon, nil).Times(1) - m5, err := o.buildVRFMessage(context.Background(), firstLayer, 2) + m5, err := o.buildVRFMessage(firstLayer, 2) require.NoError(t, err) require.Equal(t, m1, m5) // check same result } @@ -495,7 +495,7 @@ func TestBuildVRFMessage_Concurrency(t *testing.T) { for i := 0; i < total; i++ { wg.Add(1) go func(x int) { - _, err := o.buildVRFMessage(context.Background(), firstLayer, uint32(x%expectAdd)) + _, err := o.buildVRFMessage(firstLayer, uint32(x%expectAdd)) assert.NoError(t, err) wg.Done() }(i) diff --git a/hare3/hare_test.go b/hare3/hare_test.go index 6ca0b02b91..d28847776d 100644 --- a/hare3/hare_test.go +++ b/hare3/hare_test.go @@ -537,8 +537,8 @@ func (t *testTracer) waitEligibility() []*types.HareEligibility { return waitForChan(t.TB, t.eligibility, 10*time.Second, "no eligibility") } -func (t *testTracer) waitSent() *Message { - return waitForChan(t.TB, t.sent, 10*time.Second, "no message") +func (t *testTracer) waitSent() { + waitForChan(t.TB, t.sent, 10*time.Second, "no message") } func (*testTracer) OnStart(types.LayerID) {} @@ -753,7 +753,9 @@ func TestHandler(t *testing.T) { }) } -func gatx(id types.ATXID, epoch types.EpochID, smesher types.NodeID, base, height uint64) types.ActivationTx { +const epoch = types.EpochID(1) + +func gatx(id types.ATXID, smesher types.NodeID, base, height uint64) types.ActivationTx { atx := &types.ActivationTx{ NumUnits: 10, PublishEpoch: epoch, @@ -797,8 +799,7 @@ func TestProposals(t *testing.T) { pids[i][0] = byte(i) + 1 ids[i][0] = byte(i) + 1 } - publish := types.EpochID(1) - layer := (publish + 1).FirstLayer() + layer := (epoch + 1).FirstLayer() goodBeacon := types.Beacon{1} badBeacon := types.Beacon{2} @@ -818,9 +819,9 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 10, 100), - gatx(atxids[1], publish, ids[1], 10, 100), - gatx(atxids[2], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 10, 100), + gatx(atxids[1], ids[1], 10, 100), + gatx(atxids[2], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), @@ -833,9 +834,9 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 10, 100), - gatx(atxids[1], publish, ids[1], 10, 100), - gatx(atxids[2], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 10, 100), + gatx(atxids[1], ids[1], 10, 100), + gatx(atxids[2], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), @@ -848,9 +849,9 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 10, 100), - gatx(atxids[1], publish, ids[1], 10, 100), - gatx(atxids[2], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 10, 100), + gatx(atxids[1], ids[1], 10, 100), + gatx(atxids[2], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), @@ -864,8 +865,8 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 101, 1000), - gatx(atxids[1], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 101, 1000), + gatx(atxids[1], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), @@ -878,9 +879,9 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 10, 100), - gatx(atxids[1], publish, ids[1], 10, 100), - gatx(atxids[2], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 10, 100), + gatx(atxids[1], ids[1], 10, 100), + gatx(atxids[2], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), diff --git a/hare3/protocol_test.go b/hare3/protocol_test.go index 611dec4470..d0c7727dcc 100644 --- a/hare3/protocol_test.go +++ b/hare3/protocol_test.go @@ -50,9 +50,13 @@ func (t *tinput) round(r Round) *tinput { return t } -func (t *tinput) iter(i uint8) *tinput { +// FIXME: made to satisfy the linter but actually needs unit test +// changes to test different cases. +const iter1 = uint8(1) + +func (t *tinput) iter() *tinput { t.ensureMsg() - t.Iter = i + t.Iter = iter1 return t } @@ -143,9 +147,9 @@ func (t *toutput) round(r Round) *toutput { return t } -func (t *toutput) iter(i uint8) *toutput { +func (t *toutput) iter() *toutput { t.ensureMsg() - t.message.Iter = i + t.message.Iter = iter1 return t } @@ -182,8 +186,10 @@ type setup struct { proposals []types.ProposalID } -func (s *setup) thresh(v uint16) *setup { - s.threshold = v +const threshold = 10 + +func (s *setup) thresh() *setup { + s.threshold = threshold return s } @@ -204,7 +210,7 @@ func gen(desc string, steps ...any) testCase { func TestProtocol(t *testing.T) { for _, tc := range []testCase{ gen("sanity", // simplest e2e protocol run - new(setup).thresh(10).initial("a", "b"), + new(setup).thresh().initial("a", "b"), new(toutput).active().round(preround).proposals("a", "b"), new(tinput).sender("1").round(preround).proposals("b", "a").vrfcount(3).g(grade5), new(tinput).sender("2").round(preround).proposals("a", "c").vrfcount(9).g(grade5), @@ -224,15 +230,15 @@ func TestProtocol(t *testing.T) { new(toutput).result("a", "c"), // hardlock new(toutput), // softlock // propose, commit, notify messages are built based on prervious state - new(toutput).active().round(propose).iter(1).proposals("a", "c"), // propose + new(toutput).active().round(propose).iter().proposals("a", "c"), // propose new(toutput), // wait1 new(toutput), // wait2 - new(toutput).active().round(commit).iter(1).ref("a", "c"), // commit - new(toutput).active().round(notify).iter(1).ref("a", "c"), // notify + new(toutput).active().round(commit).iter().ref("a", "c"), // commit + new(toutput).active().round(notify).iter().ref("a", "c"), // notify new(toutput).terminated(), ), gen("commit on softlock", - new(setup).thresh(10).initial("a", "b"), + new(setup).thresh().initial("a", "b"), new(toutput), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(11).g(grade5), new(toutput).coin(false), @@ -248,13 +254,13 @@ func TestProtocol(t *testing.T) { new(toutput), // softlock // propose, commit, notify messages are built based on prervious state new(toutput), // propose - new(tinput).sender("1").iter(1).round(propose).proposals("b").g(grade5), + new(tinput).sender("1").iter().round(propose).proposals("b").g(grade5), new(toutput), // wait1 new(toutput), // wait2 - new(toutput).active().round(commit).iter(1).ref("b"), // commit + new(toutput).active().round(commit).iter().ref("b"), // commit ), gen("empty 0 iteration", // test that protocol can complete not only in 0st iteration - new(setup).thresh(10).initial("a", "b"), + new(setup).thresh().initial("a", "b"), new(toutput), // preround new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(3).g(grade5), new(tinput).sender("2").round(preround).proposals("a", "b").vrfcount(9).g(grade5), @@ -266,14 +272,14 @@ func TestProtocol(t *testing.T) { new(toutput), // notify new(toutput), // 2nd hardlock new(toutput), // 2nd softlock - new(toutput).active().iter(1).round(propose).proposals("a", "b"), // 2nd propose - new(tinput).sender("1").iter(1).round(propose).proposals("a", "b").g(grade5), + new(toutput).active().iter().round(propose).proposals("a", "b"), // 2nd propose + new(tinput).sender("1").iter().round(propose).proposals("a", "b").g(grade5), new(toutput), // 2nd wait1 new(toutput), // 2nd wait2 - new(toutput).active().iter(1).round(commit).ref("a", "b"), - new(tinput).sender("1").iter(1).round(commit).ref("a", "b").g(grade5).vrfcount(11), - new(toutput).active().iter(1).round(notify).ref("a", "b"), - new(tinput).sender("1").iter(1).round(notify).ref("a", "b").g(grade5).vrfcount(11), + new(toutput).active().iter().round(commit).ref("a", "b"), + new(tinput).sender("1").iter().round(commit).ref("a", "b").g(grade5).vrfcount(11), + new(toutput).active().iter().round(notify).ref("a", "b"), + new(tinput).sender("1").iter().round(notify).ref("a", "b").g(grade5).vrfcount(11), new(toutput).result("a", "b"), // 3rd hardlock new(toutput), // 3rd softlock new(toutput), // 3rd propose @@ -284,7 +290,7 @@ func TestProtocol(t *testing.T) { new(toutput).terminated(), // 4th softlock ), gen("empty proposal", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), // preround new(tinput).sender("1").round(preround).vrfcount(11).g(grade5), new(toutput).coin(false), // softlock @@ -299,7 +305,7 @@ func TestProtocol(t *testing.T) { new(toutput).result(), // hardlock ), gen("coin true", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("2").round(preround).vrf(2).g(grade5), new(tinput).sender("1").round(preround).vrf(1).g(grade5), @@ -307,7 +313,7 @@ func TestProtocol(t *testing.T) { new(toutput).coin(true), ), gen("coin false", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("2").round(preround).vrf(1, 2).g(grade5), new(tinput).sender("1").round(preround).vrf(0, 1).g(grade5), @@ -315,7 +321,7 @@ func TestProtocol(t *testing.T) { new(toutput).coin(false), ), gen("coin delayed", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(toutput), new(tinput).sender("2").round(preround).vrf(1, 2).g(grade5), @@ -323,7 +329,7 @@ func TestProtocol(t *testing.T) { new(toutput).coin(true), ), gen("duplicates don't affect thresholds", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(5).g(grade5), new(tinput).sender("3").round(preround).proposals("d").vrfcount(6).g(grade5).gossip(), @@ -344,7 +350,7 @@ func TestProtocol(t *testing.T) { new(toutput).active().round(notify).ref("a"), // duplicates commits were ignored ), gen("malicious preround", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(9).g(grade5), new(tinput).sender("2").malicious().gossip(). @@ -354,7 +360,7 @@ func TestProtocol(t *testing.T) { new(toutput).active().round(propose).proposals("b"), ), gen("malicious proposal", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(toutput), // softlock new(tinput).sender("5"). @@ -369,7 +375,7 @@ func TestProtocol(t *testing.T) { new(toutput).active().round(commit).ref("a", "c"), // commit ), gen("malicious commit", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("5"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -384,7 +390,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // notify outputs nothing ), gen("malicious notify", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("5"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -401,7 +407,7 @@ func TestProtocol(t *testing.T) { new(toutput), // no result as the only notify is malicious ), gen("equivocation preround", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("7").mshHash("m0"). round(preround).proposals("a").vrfcount(11).g(grade4), @@ -411,7 +417,7 @@ func TestProtocol(t *testing.T) { round(preround).proposals("c").vrfcount(11).g(grade3), ), gen("multiple malicious not broadcasted", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("7").malicious().gossip(). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -421,7 +427,7 @@ func TestProtocol(t *testing.T) { round(preround).proposals("c").vrfcount(11).g(grade5), ), gen("no commit for grade1", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("5"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -433,7 +439,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // commit ), gen("other gradecast was received", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("5"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -446,7 +452,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // commit ), gen("no commit if not subset of grade3", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), // preround new(toutput), // softlock new(toutput), // propose @@ -458,7 +464,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // commit ), gen("grade5 proposals are not in propose", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), // preround new(tinput).sender("1"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -472,7 +478,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // commit ), gen("commit locked", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), // preround new(tinput).sender("1"). round(preround).proposals("a", "b").vrfcount(11).g(grade5), @@ -490,16 +496,16 @@ func TestProtocol(t *testing.T) { new(toutput), // propose // commit on b will have grade1, to satisfy condition (g) new(tinput).sender("2").round(commit).ref("b").vrfcount(11).g(grade5), - new(tinput).sender("1").iter(1).round(propose).proposals("a").g(grade5).vrf(2), - new(tinput).sender("2").iter(1).round(propose).proposals("b").g(grade5).vrf(1), + new(tinput).sender("1").iter().round(propose).proposals("a").g(grade5).vrf(2), + new(tinput).sender("2").iter().round(propose).proposals("b").g(grade5).vrf(1), new(toutput), // wait1 new(toutput), // wait2 // condition (h) ensures that we commit on locked value, even though proposal for b // is first in the order - new(toutput).active().round(commit).iter(1).ref("a"), // commit + new(toutput).active().round(commit).iter().ref("a"), // commit ), gen("early proposal by one", - new(setup).thresh(10), + new(setup).thresh(), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(11).g(grade5), new(toutput).coin(false), // preround new(toutput), // softlock @@ -510,7 +516,7 @@ func TestProtocol(t *testing.T) { new(toutput).active().round(commit).ref("a", "b"), ), gen("early proposal by two", - new(setup).thresh(10), + new(setup).thresh(), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(11).g(grade5), new(toutput).coin(false), // preround new(tinput).sender("1").round(propose).proposals("a", "b").g(grade5).vrf(1), diff --git a/hare4/eligibility/oracle.go b/hare4/eligibility/oracle.go index 701d8da800..98b96313bb 100644 --- a/hare4/eligibility/oracle.go +++ b/hare4/eligibility/oracle.go @@ -178,7 +178,7 @@ func (o *Oracle) resetCacheOnSynced(ctx context.Context) { } // buildVRFMessage builds the VRF message used as input for hare eligibility validation. -func (o *Oracle) buildVRFMessage(ctx context.Context, layer types.LayerID, round uint32) ([]byte, error) { +func (o *Oracle) buildVRFMessage(layer types.LayerID, round uint32) ([]byte, error) { beacon, err := o.beacons.GetBeacon(layer.GetEpoch()) if err != nil { return nil, fmt.Errorf("get beacon: %w", err) @@ -240,7 +240,7 @@ func (o *Oracle) prepareEligibilityCheck( return 0, fixed.Fixed{}, fixed.Fixed{}, true, err } - msg, err := o.buildVRFMessage(ctx, layer, round) + msg, err := o.buildVRFMessage(layer, round) if err != nil { logger.Warn("could not build vrf message", zap.Error(err)) return 0, fixed.Fixed{}, fixed.Fixed{}, true, err diff --git a/hare4/eligibility/oracle_test.go b/hare4/eligibility/oracle_test.go index 5dfdf877b6..591eb9cd30 100644 --- a/hare4/eligibility/oracle_test.go +++ b/hare4/eligibility/oracle_test.go @@ -451,7 +451,7 @@ func TestBuildVRFMessage_BeaconError(t *testing.T) { o := defaultOracle(t) errUnknown := errors.New("unknown") o.mBeacon.EXPECT().GetBeacon(gomock.Any()).Return(types.EmptyBeacon, errUnknown).Times(1) - msg, err := o.buildVRFMessage(context.Background(), types.LayerID(1), 1) + msg, err := o.buildVRFMessage(types.LayerID(1), 1) require.ErrorIs(t, err, errUnknown) require.Nil(t, msg) } @@ -462,24 +462,24 @@ func TestBuildVRFMessage(t *testing.T) { secondLayer := firstLayer.Add(1) beacon := types.RandomBeacon() o.mBeacon.EXPECT().GetBeacon(firstLayer.GetEpoch()).Return(beacon, nil).Times(1) - m1, err := o.buildVRFMessage(context.Background(), firstLayer, 2) + m1, err := o.buildVRFMessage(firstLayer, 2) require.NoError(t, err) // check not same for different round o.mBeacon.EXPECT().GetBeacon(firstLayer.GetEpoch()).Return(beacon, nil).Times(1) - m3, err := o.buildVRFMessage(context.Background(), firstLayer, 3) + m3, err := o.buildVRFMessage(firstLayer, 3) require.NoError(t, err) require.NotEqual(t, m1, m3) // check not same for different layer o.mBeacon.EXPECT().GetBeacon(firstLayer.GetEpoch()).Return(beacon, nil).Times(1) - m4, err := o.buildVRFMessage(context.Background(), secondLayer, 2) + m4, err := o.buildVRFMessage(secondLayer, 2) require.NoError(t, err) require.NotEqual(t, m1, m4) // check same call returns same result o.mBeacon.EXPECT().GetBeacon(firstLayer.GetEpoch()).Return(beacon, nil).Times(1) - m5, err := o.buildVRFMessage(context.Background(), firstLayer, 2) + m5, err := o.buildVRFMessage(firstLayer, 2) require.NoError(t, err) require.Equal(t, m1, m5) // check same result } @@ -495,7 +495,7 @@ func TestBuildVRFMessage_Concurrency(t *testing.T) { for i := 0; i < total; i++ { wg.Add(1) go func(x int) { - _, err := o.buildVRFMessage(context.Background(), firstLayer, uint32(x%expectAdd)) + _, err := o.buildVRFMessage(firstLayer, uint32(x%expectAdd)) assert.NoError(t, err) wg.Done() }(i) diff --git a/hare4/hare.go b/hare4/hare.go index 9ce948dbd8..5adb2895eb 100644 --- a/hare4/hare.go +++ b/hare4/hare.go @@ -390,12 +390,12 @@ func (h *Hare) handleProposalsStream(ctx context.Context, msg []byte, s io.ReadW // reconstructProposals tries to reconstruct the full list of proposals from a peer based on a delivered // set of compact IDs. -func (h *Hare) reconstructProposals(ctx context.Context, peer p2p.Peer, msgId types.Hash32, msg *Message) error { +func (h *Hare) reconstructProposals(msg *Message) error { proposals := h.proposals.GetForLayer(msg.Layer) if len(proposals) == 0 { return errNoLayerProposals } - compacted := h.compactProposals(msg.Layer, proposals) + compacted := h.compactProposals(proposals) proposalIds := make([]proposalTuple, len(proposals)) for i := range proposals { proposalIds[i] = proposalTuple{id: proposals[i].ID(), compact: compacted[i]} @@ -476,7 +476,7 @@ func (h *Hare) Handler(ctx context.Context, peer p2p.Peer, buf []byte) error { // original sent message for signature validation to occur compacts = msg.Value.CompactProposals messageCompactsCounter.Add(float64(len(compacts))) - err := h.reconstructProposals(ctx, peer, msgId, msg) + err := h.reconstructProposals(msg) switch { case errors.Is(err, errCannotMatchProposals): msg.Value.Proposals, err = h.fetchFull(ctx, peer, msgId) @@ -885,9 +885,7 @@ type session struct { vrfs []*types.HareEligibility } -func (h *Hare) compactProposals(layer types.LayerID, - proposals []*types.Proposal, -) []types.CompactProposalID { +func (h *Hare) compactProposals(proposals []*types.Proposal) []types.CompactProposalID { compactProposals := make([]types.CompactProposalID, len(proposals)) for i, prop := range proposals { vrf := prop.EligibilityProofs[0].Sig diff --git a/hare4/hare_test.go b/hare4/hare_test.go index e798a39f51..73a4ac84c7 100644 --- a/hare4/hare_test.go +++ b/hare4/hare_test.go @@ -662,8 +662,8 @@ func (t *testTracer) waitEligibility() []*types.HareEligibility { return waitForChan(t.TB, t.eligibility, wait, "no eligibility") } -func (t *testTracer) waitSent() *Message { - return waitForChan(t.TB, t.sent, wait, "no message") +func (t *testTracer) waitSent() { + waitForChan(t.TB, t.sent, wait, "no message") } func (*testTracer) OnStart(types.LayerID) {} @@ -928,7 +928,9 @@ func TestHandler(t *testing.T) { }) } -func gatx(id types.ATXID, epoch types.EpochID, smesher types.NodeID, base, height uint64) types.ActivationTx { +const epoch = types.EpochID(1) + +func gatx(id types.ATXID, smesher types.NodeID, base, height uint64) types.ActivationTx { atx := &types.ActivationTx{ NumUnits: 10, PublishEpoch: epoch, @@ -993,9 +995,9 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 10, 100), - gatx(atxids[1], publish, ids[1], 10, 100), - gatx(atxids[2], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 10, 100), + gatx(atxids[1], ids[1], 10, 100), + gatx(atxids[2], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), @@ -1008,9 +1010,9 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 10, 100), - gatx(atxids[1], publish, ids[1], 10, 100), - gatx(atxids[2], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 10, 100), + gatx(atxids[1], ids[1], 10, 100), + gatx(atxids[2], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), @@ -1023,9 +1025,9 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 10, 100), - gatx(atxids[1], publish, ids[1], 10, 100), - gatx(atxids[2], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 10, 100), + gatx(atxids[1], ids[1], 10, 100), + gatx(atxids[2], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), @@ -1039,8 +1041,8 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 101, 1000), - gatx(atxids[1], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 101, 1000), + gatx(atxids[1], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), @@ -1053,9 +1055,9 @@ func TestProposals(t *testing.T) { layer: layer, beacon: goodBeacon, atxs: []types.ActivationTx{ - gatx(atxids[0], publish, ids[0], 10, 100), - gatx(atxids[1], publish, ids[1], 10, 100), - gatx(atxids[2], publish, signer.NodeID(), 10, 100), + gatx(atxids[0], ids[0], 10, 100), + gatx(atxids[1], ids[1], 10, 100), + gatx(atxids[2], signer.NodeID(), 10, 100), }, proposals: []*types.Proposal{ gproposal(pids[0], atxids[0], ids[0], layer, goodBeacon), diff --git a/hare4/protocol_test.go b/hare4/protocol_test.go index c04e69fdcf..12602724e6 100644 --- a/hare4/protocol_test.go +++ b/hare4/protocol_test.go @@ -50,9 +50,9 @@ func (t *tinput) round(r Round) *tinput { return t } -func (t *tinput) iter(i uint8) *tinput { +func (t *tinput) iter() *tinput { t.ensureMsg() - t.Iter = i + t.Iter = iter1 return t } @@ -143,9 +143,13 @@ func (t *toutput) round(r Round) *toutput { return t } -func (t *toutput) iter(i uint8) *toutput { +// FIXME: made to satisfy the linter but actually needs unit test +// changes to test different cases. +const iter1 = uint8(1) + +func (t *toutput) iter() *toutput { t.ensureMsg() - t.message.Iter = i + t.message.Iter = iter1 return t } @@ -182,8 +186,10 @@ type setup struct { proposals []types.ProposalID } -func (s *setup) thresh(v uint16) *setup { - s.threshold = v +const threshold = 10 + +func (s *setup) thresh() *setup { + s.threshold = threshold return s } @@ -204,7 +210,7 @@ func gen(desc string, steps ...any) testCase { func TestProtocol(t *testing.T) { for _, tc := range []testCase{ gen("sanity", // simplest e2e protocol run - new(setup).thresh(10).initial("a", "b"), + new(setup).thresh().initial("a", "b"), new(toutput).active().round(preround).proposals("a", "b"), new(tinput).sender("1").round(preround).proposals("b", "a").vrfcount(3).g(grade5), new(tinput).sender("2").round(preround).proposals("a", "c").vrfcount(9).g(grade5), @@ -224,15 +230,15 @@ func TestProtocol(t *testing.T) { new(toutput).result("a", "c"), // hardlock new(toutput), // softlock // propose, commit, notify messages are built based on prervious state - new(toutput).active().round(propose).iter(1).proposals("a", "c"), // propose + new(toutput).active().round(propose).iter().proposals("a", "c"), // propose new(toutput), // wait1 new(toutput), // wait2 - new(toutput).active().round(commit).iter(1).ref("a", "c"), // commit - new(toutput).active().round(notify).iter(1).ref("a", "c"), // notify + new(toutput).active().round(commit).iter().ref("a", "c"), // commit + new(toutput).active().round(notify).iter().ref("a", "c"), // notify new(toutput).terminated(), ), gen("commit on softlock", - new(setup).thresh(10).initial("a", "b"), + new(setup).thresh().initial("a", "b"), new(toutput), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(11).g(grade5), new(toutput).coin(false), @@ -248,13 +254,13 @@ func TestProtocol(t *testing.T) { new(toutput), // softlock // propose, commit, notify messages are built based on prervious state new(toutput), // propose - new(tinput).sender("1").iter(1).round(propose).proposals("b").g(grade5), + new(tinput).sender("1").iter().round(propose).proposals("b").g(grade5), new(toutput), // wait1 new(toutput), // wait2 - new(toutput).active().round(commit).iter(1).ref("b"), // commit + new(toutput).active().round(commit).iter().ref("b"), // commit ), gen("empty 0 iteration", // test that protocol can complete not only in 0st iteration - new(setup).thresh(10).initial("a", "b"), + new(setup).thresh().initial("a", "b"), new(toutput), // preround new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(3).g(grade5), new(tinput).sender("2").round(preround).proposals("a", "b").vrfcount(9).g(grade5), @@ -266,14 +272,14 @@ func TestProtocol(t *testing.T) { new(toutput), // notify new(toutput), // 2nd hardlock new(toutput), // 2nd softlock - new(toutput).active().iter(1).round(propose).proposals("a", "b"), // 2nd propose - new(tinput).sender("1").iter(1).round(propose).proposals("a", "b").g(grade5), + new(toutput).active().iter().round(propose).proposals("a", "b"), // 2nd propose + new(tinput).sender("1").iter().round(propose).proposals("a", "b").g(grade5), new(toutput), // 2nd wait1 new(toutput), // 2nd wait2 - new(toutput).active().iter(1).round(commit).ref("a", "b"), - new(tinput).sender("1").iter(1).round(commit).ref("a", "b").g(grade5).vrfcount(11), - new(toutput).active().iter(1).round(notify).ref("a", "b"), - new(tinput).sender("1").iter(1).round(notify).ref("a", "b").g(grade5).vrfcount(11), + new(toutput).active().iter().round(commit).ref("a", "b"), + new(tinput).sender("1").iter().round(commit).ref("a", "b").g(grade5).vrfcount(11), + new(toutput).active().iter().round(notify).ref("a", "b"), + new(tinput).sender("1").iter().round(notify).ref("a", "b").g(grade5).vrfcount(11), new(toutput).result("a", "b"), // 3rd hardlock new(toutput), // 3rd softlock new(toutput), // 3rd propose @@ -284,7 +290,7 @@ func TestProtocol(t *testing.T) { new(toutput).terminated(), // 4th softlock ), gen("empty proposal", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), // preround new(tinput).sender("1").round(preround).vrfcount(11).g(grade5), new(toutput).coin(false), // softlock @@ -299,7 +305,7 @@ func TestProtocol(t *testing.T) { new(toutput).result(), // hardlock ), gen("coin true", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("2").round(preround).vrf(2).g(grade5), new(tinput).sender("1").round(preround).vrf(1).g(grade5), @@ -307,7 +313,7 @@ func TestProtocol(t *testing.T) { new(toutput).coin(true), ), gen("coin false", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("2").round(preround).vrf(1, 2).g(grade5), new(tinput).sender("1").round(preround).vrf(0, 1).g(grade5), @@ -315,7 +321,7 @@ func TestProtocol(t *testing.T) { new(toutput).coin(false), ), gen("coin delayed", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(toutput), new(tinput).sender("2").round(preround).vrf(1, 2).g(grade5), @@ -323,7 +329,7 @@ func TestProtocol(t *testing.T) { new(toutput).coin(true), ), gen("duplicates don't affect thresholds", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(5).g(grade5), new(tinput).sender("3").round(preround).proposals("d").vrfcount(6).g(grade5).gossip(), @@ -344,7 +350,7 @@ func TestProtocol(t *testing.T) { new(toutput).active().round(notify).ref("a"), // duplicates commits were ignored ), gen("malicious preround", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(9).g(grade5), new(tinput).sender("2").malicious().gossip(). @@ -354,7 +360,7 @@ func TestProtocol(t *testing.T) { new(toutput).active().round(propose).proposals("b"), ), gen("malicious proposal", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(toutput), // softlock new(tinput).sender("5"). @@ -369,7 +375,7 @@ func TestProtocol(t *testing.T) { new(toutput).active().round(commit).ref("a", "c"), // commit ), gen("malicious commit", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("5"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -384,7 +390,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // notify outputs nothing ), gen("malicious notify", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("5"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -401,7 +407,7 @@ func TestProtocol(t *testing.T) { new(toutput), // no result as the only notify is malicious ), gen("equivocation preround", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("7").mshHash("m0"). round(preround).proposals("a").vrfcount(11).g(grade4), @@ -411,7 +417,7 @@ func TestProtocol(t *testing.T) { round(preround).proposals("c").vrfcount(11).g(grade3), ), gen("multiple malicious not broadcasted", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("7").malicious().gossip(). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -421,7 +427,7 @@ func TestProtocol(t *testing.T) { round(preround).proposals("c").vrfcount(11).g(grade5), ), gen("no commit for grade1", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("5"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -433,7 +439,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // commit ), gen("other gradecast was received", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), new(tinput).sender("5"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -446,7 +452,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // commit ), gen("no commit if not subset of grade3", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), // preround new(toutput), // softlock new(toutput), // propose @@ -458,7 +464,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // commit ), gen("grade5 proposals are not in propose", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), // preround new(tinput).sender("1"). round(preround).proposals("a").vrfcount(11).g(grade5), @@ -472,7 +478,7 @@ func TestProtocol(t *testing.T) { new(toutput).active(), // commit ), gen("commit locked", - new(setup).thresh(10), + new(setup).thresh(), new(toutput), // preround new(tinput).sender("1"). round(preround).proposals("a", "b").vrfcount(11).g(grade5), @@ -490,16 +496,16 @@ func TestProtocol(t *testing.T) { new(toutput), // propose // commit on b will have grade1, to satisfy condition (g) new(tinput).sender("2").round(commit).ref("b").vrfcount(11).g(grade5), - new(tinput).sender("1").iter(1).round(propose).proposals("a").g(grade5).vrf(2), - new(tinput).sender("2").iter(1).round(propose).proposals("b").g(grade5).vrf(1), + new(tinput).sender("1").iter().round(propose).proposals("a").g(grade5).vrf(2), + new(tinput).sender("2").iter().round(propose).proposals("b").g(grade5).vrf(1), new(toutput), // wait1 new(toutput), // wait2 // condition (h) ensures that we commit on locked value, even though proposal for b // is first in the order - new(toutput).active().round(commit).iter(1).ref("a"), // commit + new(toutput).active().round(commit).iter().ref("a"), // commit ), gen("early proposal by one", - new(setup).thresh(10), + new(setup).thresh(), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(11).g(grade5), new(toutput).coin(false), // preround new(toutput), // softlock @@ -510,7 +516,7 @@ func TestProtocol(t *testing.T) { new(toutput).active().round(commit).ref("a", "b"), ), gen("early proposal by two", - new(setup).thresh(10), + new(setup).thresh(), new(tinput).sender("1").round(preround).proposals("a", "b").vrfcount(11).g(grade5), new(toutput).coin(false), // preround new(tinput).sender("1").round(propose).proposals("a", "b").g(grade5).vrf(1), diff --git a/mesh/mesh_test.go b/mesh/mesh_test.go index 290d4af93d..87e86e9330 100644 --- a/mesh/mesh_test.go +++ b/mesh/mesh_test.go @@ -111,7 +111,6 @@ func createBlock( db sql.Executor, mesh *Mesh, layerID types.LayerID, - nodeID types.NodeID, ) *types.Block { t.Helper() txIDs := CreateAndSaveTxs(t, db, numTXs) @@ -135,8 +134,7 @@ func createLayerBlocks( t.Helper() blks := make([]*types.Block, 0, numBlocks) for i := 0; i < numBlocks; i++ { - nodeID := types.NodeID{byte(i)} - blk := createBlock(t, db, mesh, lyrID, nodeID) + blk := createBlock(t, db, mesh, lyrID) blks = append(blks, blk) } return blks @@ -752,7 +750,7 @@ func TestProcessLayer(t *testing.T) { } tm.mockTortoise.EXPECT().Updates().Return(c.updates) - ensuresDatabaseConsistent(t, tm.cdb, c.updates) + ensuresDatabaseConsistent(tm.cdb, c.updates) err := tm.ProcessLayer(context.TODO(), lid) if len(c.err) > 0 { require.ErrorContains(t, err, c.err) @@ -775,7 +773,7 @@ func TestProcessLayer(t *testing.T) { } } -func ensuresDatabaseConsistent(t *testing.T, db sql.Executor, results []result.Layer) { +func ensuresDatabaseConsistent(db sql.Executor, results []result.Layer) { for _, layer := range results { for _, rst := range layer.Blocks { if !rst.Data { diff --git a/miner/active_set_generator_test.go b/miner/active_set_generator_test.go index 660952d03c..b81a647b16 100644 --- a/miner/active_set_generator_test.go +++ b/miner/active_set_generator_test.go @@ -58,8 +58,8 @@ type test struct { expectErr string } -func unixPtr(sec, nsec int64) *time.Time { - t := time.Unix(sec, nsec) +func unixPtr(sec int64) *time.Time { + t := time.Unix(sec, 0) return &t } @@ -115,8 +115,8 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "fallback success", atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, types.NodeID{1}, 2), - gatx(types.ATXID{2}, 2, types.NodeID{1}, 3), + gatx(types.ATXID{1}, types.NodeID{1}, 2), + gatx(types.ATXID{2}, types.NodeID{1}, 3), }, fallbacks: []types.EpochActiveSet{ {Epoch: 3, Set: []types.ATXID{{1}, {2}}}, @@ -127,7 +127,7 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "fallback failure", atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, types.NodeID{1}, 2), + gatx(types.ATXID{1}, types.NodeID{1}, 2), }, fallbacks: []types.EpochActiveSet{ {Epoch: 3, Set: []types.ATXID{{1}, {2}}}, @@ -138,12 +138,12 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "graded active set > 60", atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, types.NodeID{1}, 2, genAtxWithReceived(time.Unix(20, 0))), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{1}, types.NodeID{1}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{2}, types.NodeID{2}, 2, genAtxWithReceived(time.Unix(20, 0))), // the last atx won't be marked as good due to being received only 2 seconds before epoch start - gatx(types.ATXID{3}, 2, types.NodeID{3}, 2, genAtxWithReceived(time.Unix(28, 0))), + gatx(types.ATXID{3}, types.NodeID{3}, 2, genAtxWithReceived(time.Unix(28, 0))), }, - epochStart: unixPtr(30, 0), + epochStart: unixPtr(30), networkDelay: 2 * time.Second, goodAtxPercent: 60, target: 3, @@ -152,12 +152,12 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "graded active set < 60", atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, types.NodeID{1}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{1}, types.NodeID{1}, 2, genAtxWithReceived(time.Unix(20, 0))), // two last atx won't be marked as good due to being received only 2 seconds before epoch start - gatx(types.ATXID{2}, 2, types.NodeID{2}, 2, genAtxWithReceived(time.Unix(28, 0))), - gatx(types.ATXID{3}, 2, types.NodeID{3}, 2, genAtxWithReceived(time.Unix(28, 0))), + gatx(types.ATXID{2}, types.NodeID{2}, 2, genAtxWithReceived(time.Unix(28, 0))), + gatx(types.ATXID{3}, types.NodeID{3}, 2, genAtxWithReceived(time.Unix(28, 0))), }, - epochStart: unixPtr(30, 0), + epochStart: unixPtr(30), networkDelay: 2 * time.Second, goodAtxPercent: 60, target: 3, @@ -166,14 +166,14 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "graded active set with malicious", atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, types.NodeID{1}, 2, genAtxWithReceived(time.Unix(20, 0))), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 2, genAtxWithReceived(time.Unix(20, 0))), - gatx(types.ATXID{3}, 2, types.NodeID{3}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{1}, types.NodeID{1}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{2}, types.NodeID{2}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{3}, types.NodeID{3}, 2, genAtxWithReceived(time.Unix(20, 0))), }, malfeasent: []identity{ gidentity(types.NodeID{3}, time.Unix(29, 0)), }, - epochStart: unixPtr(30, 0), + epochStart: unixPtr(30), networkDelay: 2 * time.Second, goodAtxPercent: 60, target: 3, @@ -182,14 +182,14 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "graded active set with late malicious", atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, types.NodeID{1}, 2, genAtxWithReceived(time.Unix(20, 0))), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 2, genAtxWithReceived(time.Unix(20, 0))), - gatx(types.ATXID{3}, 2, types.NodeID{3}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{1}, types.NodeID{1}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{2}, types.NodeID{2}, 2, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{3}, types.NodeID{3}, 2, genAtxWithReceived(time.Unix(20, 0))), }, malfeasent: []identity{ gidentity(types.NodeID{3}, time.Unix(31, 0)), }, - epochStart: unixPtr(30, 0), + epochStart: unixPtr(30), networkDelay: 2 * time.Second, goodAtxPercent: 60, target: 3, @@ -198,7 +198,7 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "graded empty", atxs: []*types.ActivationTx{}, - epochStart: unixPtr(30, 0), + epochStart: unixPtr(30), networkDelay: 2 * time.Second, goodAtxPercent: 60, target: 3, @@ -207,10 +207,10 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "first block not found", atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, types.NodeID{1}, 2), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 2), + gatx(types.ATXID{1}, types.NodeID{1}, 2), + gatx(types.ATXID{2}, types.NodeID{2}, 2), }, - epochStart: unixPtr(0, 0), + epochStart: unixPtr(0), networkDelay: 2 * time.Second, goodAtxPercent: 100, current: thirdFirst + 1, @@ -220,8 +220,8 @@ func TestActiveSetGenerate(t *testing.T) { { desc: "first block success", atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, types.NodeID{1}, 2), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 2), + gatx(types.ATXID{1}, types.NodeID{1}, 2), + gatx(types.ATXID{2}, types.NodeID{2}, 2), }, blocks: []*types.Block{ gblock(thirdFirst, types.ATXID{1}, types.ATXID{2}), @@ -237,7 +237,7 @@ func TestActiveSetGenerate(t *testing.T) { activesets: []*types.EpochActiveSet{ {Epoch: 3, Set: []types.ATXID{{1}, {2}}}, }, - epochStart: unixPtr(0, 0), + epochStart: unixPtr(0), networkDelay: 2 * time.Second, goodAtxPercent: 100, current: types.EpochID(3).FirstLayer() + 1, @@ -343,7 +343,7 @@ func TestActiveSetEnsure(t *testing.T) { require.ErrorIs(t, err, sql.ErrNotFound) // computes from first try - tester.atxsdata.AddFromAtx(gatx(expected[0], 2, types.NodeID{1}, 1), false) + tester.atxsdata.AddFromAtx(gatx(expected[0], types.NodeID{1}, 1), false) tester.clock.EXPECT().CurrentLayer().Return(0).Times(1) tester.gen.ensure(ctx, target) id, weight, set, err := activeset.Get(tester.localdb, activeset.Tortoise, target) diff --git a/miner/proposal_builder.go b/miner/proposal_builder.go index 96c0ee46e4..9ce5546aea 100644 --- a/miner/proposal_builder.go +++ b/miner/proposal_builder.go @@ -449,7 +449,7 @@ func (pb *ProposalBuilder) UpdateActiveSet(target types.EpochID, set []types.ATX pb.activeGen.updateFallback(target, set) } -func (pb *ProposalBuilder) initSharedData(ctx context.Context, current types.LayerID) error { +func (pb *ProposalBuilder) initSharedData(current types.LayerID) error { if pb.shared.epoch != current.GetEpoch() { pb.shared = sharedSession{epoch: current.GetEpoch()} } @@ -480,7 +480,6 @@ func (pb *ProposalBuilder) initSharedData(ctx context.Context, current types.Lay } func (pb *ProposalBuilder) initSignerData( - ctx context.Context, ss *signerSession, lid types.LayerID, ) error { @@ -559,7 +558,7 @@ func (pb *ProposalBuilder) initSignerData( func (pb *ProposalBuilder) build(ctx context.Context, lid types.LayerID) error { start := time.Now() - if err := pb.initSharedData(ctx, lid); err != nil { + if err := pb.initSharedData(lid); err != nil { return err } @@ -573,7 +572,7 @@ func (pb *ProposalBuilder) build(ctx context.Context, lid types.LayerID) error { for _, ss := range signers { ss.latency.start = start eg.Go(func() error { - if err := pb.initSignerData(ctx, ss, lid); err != nil { + if err := pb.initSignerData(ss, lid); err != nil { if errors.Is(err, errAtxNotAvailable) { ss.log.Debug("smesher doesn't have atx that targets this epoch", log.ZContext(ctx), diff --git a/miner/proposal_builder_test.go b/miner/proposal_builder_test.go index 6df1c62592..3ce80e0b00 100644 --- a/miner/proposal_builder_test.go +++ b/miner/proposal_builder_test.go @@ -61,11 +61,13 @@ func genAtxWithReceived(received time.Time) genAtxOpt { } } -const ticks = 100 +const ( + ticks = 100 + epoch = types.EpochID(2) +) func gatx( id types.ATXID, - epoch types.EpochID, smesher types.NodeID, units uint32, opts ...genAtxOpt, @@ -145,9 +147,10 @@ func expectMeshHash(hash types.Hash32) expectOpt { } } +const epochExpectCounter = types.EpochID(3) + func expectCounters( signer *signing.EdSigner, - epoch types.EpochID, beacon types.Beacon, nonce types.VRFPostIndex, js ...uint32, @@ -157,7 +160,7 @@ func expectCounters( for _, j := range js { p.EligibilityProofs = append(p.EligibilityProofs, types.VotingEligibility{ J: j, - Sig: vsigner.Sign(proposals.MustSerializeVRFMessage(beacon, epoch, nonce, j)), + Sig: vsigner.Sign(proposals.MustSerializeVRFMessage(beacon, epochExpectCounter, nonce, j)), }) } } @@ -269,10 +272,10 @@ func TestBuild(t *testing.T) { lid: 15, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 1), - gatx(types.ATXID{3}, 2, types.NodeID{3}, 1), - gatx(types.ATXID{4}, 2, types.NodeID{4}, 1), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{2}, types.NodeID{2}, 1), + gatx(types.ATXID{3}, types.NodeID{3}, 1), + gatx(types.ATXID{4}, types.NodeID{4}, 1), }, opinion: &types.Opinion{Hash: types.Hash32{1}}, txs: []types.TransactionID{{1}, {2}}, @@ -285,7 +288,7 @@ func TestBuild(t *testing.T) { types.Beacon{1}, ), expectTxs([]types.TransactionID{{1}, {2}}), - expectCounters(signer, 3, types.Beacon{1}, 777, 0, 6, 9), + expectCounters(signer, types.Beacon{1}, 777, 0, 6, 9), ), }, }, @@ -297,12 +300,12 @@ func TestBuild(t *testing.T) { lid: 15, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 1), - gatx(types.ATXID{3}, 2, types.NodeID{3}, 1), - gatx(types.ATXID{4}, 2, types.NodeID{4}, 1), - gatx(types.ATXID{5}, 2, types.NodeID{5}, 1), - gatx(types.ATXID{6}, 2, types.NodeID{6}, 1), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{2}, types.NodeID{2}, 1), + gatx(types.ATXID{3}, types.NodeID{3}, 1), + gatx(types.ATXID{4}, types.NodeID{4}, 1), + gatx(types.ATXID{5}, types.NodeID{5}, 1), + gatx(types.ATXID{6}, types.NodeID{6}, 1), }, fallbackActiveSets: []struct { epoch types.EpochID @@ -321,7 +324,7 @@ func TestBuild(t *testing.T) { types.Beacon{1}, ), expectTxs([]types.TransactionID{{1}, {2}}), - expectCounters(signer, 3, types.Beacon{1}, 777, 0, 6, 9), + expectCounters(signer, types.Beacon{1}, 777, 0, 6, 9), ), }, }, @@ -334,7 +337,7 @@ func TestBuild(t *testing.T) { lid: 15, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), }, opinion: &types.Opinion{Hash: types.Hash32{1}}, txs: []types.TransactionID{}, @@ -346,7 +349,7 @@ func TestBuild(t *testing.T) { 5, types.Beacon{1}, ), - expectCounters(signer, 3, types.Beacon{1}, 777, 0), + expectCounters(signer, types.Beacon{1}, 777, 0), ), }, }, @@ -358,8 +361,8 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 1), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{2}, types.NodeID{2}, 1), }, ballots: []*types.Ballot{ gballot(types.BallotID{1}, types.ATXID{1}, signer.NodeID(), 15, &types.EpochData{ @@ -375,7 +378,7 @@ func TestBuild(t *testing.T) { expectProposal: expectProposal( signer, 16, types.ATXID{1}, types.Opinion{Hash: types.Hash32{1}}, expectRef(types.BallotID{1}), - expectCounters(signer, 3, types.Beacon{1}, 777, 2), + expectCounters(signer, types.Beacon{1}, 777, 2), ), }, }, @@ -395,13 +398,13 @@ func TestBuild(t *testing.T) { { lid: 15, atxs: []*types.ActivationTx{ - gatx(types.ATXID{20}, 2, types.NodeID{20}, 1), + gatx(types.ATXID{20}, types.NodeID{20}, 1), }, }, { lid: 16, atxs: []*types.ActivationTx{ - gatx(types.ATXID{10}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{10}, signer.NodeID(), 1, genAtxWithNonce(777)), }, ballots: []*types.Ballot{ gballot(types.BallotID{1}, types.ATXID{10}, signer.NodeID(), 15, &types.EpochData{ @@ -417,7 +420,7 @@ func TestBuild(t *testing.T) { signer, 16, types.ATXID{10}, types.Opinion{Hash: types.Hash32{1}}, expectRef(types.BallotID{1}), expectTxs([]types.TransactionID{{1}}), - expectCounters(signer, 3, types.Beacon{1}, 777, 2), + expectCounters(signer, types.Beacon{1}, 777, 2), ), }, }, @@ -429,8 +432,8 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 100), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{2}, types.NodeID{2}, 100), }, ballots: []*types.Ballot{ gballot(types.BallotID{1}, types.ATXID{1}, signer.NodeID(), 15, &types.EpochData{ @@ -453,7 +456,7 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), }, ballots: []*types.Ballot{ gballot(types.BallotID{1}, types.ATXID{1}, signer.NodeID(), 15, &types.EpochData{ @@ -476,7 +479,7 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), }, ballots: []*types.Ballot{ gballot(types.BallotID{1}, types.ATXID{1}, signer.NodeID(), 15, &types.EpochData{ @@ -493,7 +496,7 @@ func TestBuild(t *testing.T) { expectProposal: expectProposal( signer, 16, types.ATXID{1}, types.Opinion{}, expectRef(types.BallotID{1}), - expectCounters(signer, 3, types.Beacon{1}, 777, 2, 5), + expectCounters(signer, types.Beacon{1}, 777, 2, 5), ), }, }, @@ -505,8 +508,8 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 1), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{2}, types.NodeID{2}, 1), }, identities: []identity{{ id: types.NodeID{2}, @@ -525,7 +528,7 @@ func TestBuild(t *testing.T) { 50, types.Beacon{1}, ), - expectCounters(signer, 3, types.Beacon{1}, 777, + expectCounters(signer, types.Beacon{1}, 777, 2, 5, 11, 19, 22, 24, 28, 30, 33, 36), ), }, @@ -542,9 +545,9 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), - gatx(types.ATXID{2}, 2, types.NodeID{2}, 1, genAtxWithReceived(time.Unix(20, 0))), - gatx(types.ATXID{3}, 2, types.NodeID{3}, 1, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{2}, types.NodeID{2}, 1, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{3}, types.NodeID{3}, 1, genAtxWithReceived(time.Unix(20, 0))), }, expectErr: "first block", }, @@ -572,7 +575,7 @@ func TestBuild(t *testing.T) { { lid: 16, atxs: []*types.ActivationTx{ - gatx(types.ATXID{4}, 2, types.NodeID{4}, 1, genAtxWithReceived(time.Unix(20, 0))), + gatx(types.ATXID{4}, types.NodeID{4}, 1, genAtxWithReceived(time.Unix(20, 0))), }, opinion: &types.Opinion{Hash: types.Hash32{1}}, txs: []types.TransactionID{}, @@ -584,7 +587,7 @@ func TestBuild(t *testing.T) { 16, types.Beacon{1}, ), - expectCounters(signer, 3, types.Beacon{1}, 777, 2, 5, 11), + expectCounters(signer, types.Beacon{1}, 777, 2, 5, 11), ), }, }, @@ -596,7 +599,7 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), }, ballots: []*types.Ballot{ gballot(types.BallotID{11}, types.ATXID{1}, signer.NodeID(), 15, nil), @@ -613,7 +616,7 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), }, ballots: []*types.Ballot{ gballot(types.BallotID{1}, types.ATXID{1}, signer.NodeID(), 15, &types.EpochData{ @@ -629,7 +632,7 @@ func TestBuild(t *testing.T) { expectProposal: expectProposal( signer, 16, types.ATXID{1}, types.Opinion{Hash: types.Hash32{1}}, expectRef(types.BallotID{1}), - expectCounters(signer, 3, types.Beacon{1}, 777, 2, 5), + expectCounters(signer, types.Beacon{1}, 777, 2, 5), ), }, { @@ -640,7 +643,7 @@ func TestBuild(t *testing.T) { expectProposal: expectProposal( signer, 17, types.ATXID{1}, types.Opinion{Hash: types.Hash32{1}}, expectRef(types.BallotID{1}), - expectCounters(signer, 3, types.Beacon{1}, 777, 3, 7), + expectCounters(signer, types.Beacon{1}, 777, 3, 7), ), }, { @@ -652,7 +655,7 @@ func TestBuild(t *testing.T) { expectProposal: expectProposal( signer, 18, types.ATXID{1}, types.Opinion{Hash: types.Hash32{1}}, expectRef(types.BallotID{1}), - expectCounters(signer, 3, types.Beacon{1}, 777, 1, 4, 8), + expectCounters(signer, types.Beacon{1}, 777, 1, 4, 8), ), }, }, @@ -665,7 +668,7 @@ func TestBuild(t *testing.T) { lid: 16, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signer.NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{1}, signer.NodeID(), 1, genAtxWithNonce(777)), }, ballots: []*types.Ballot{ gballot(types.BallotID{1}, types.ATXID{1}, signer.NodeID(), 15, &types.EpochData{ @@ -681,7 +684,7 @@ func TestBuild(t *testing.T) { expectProposal: expectProposal( signer, 16, types.ATXID{1}, types.Opinion{Hash: types.Hash32{1}}, expectRef(types.BallotID{1}), - expectCounters(signer, 3, types.Beacon{1}, 777, 2, 5), + expectCounters(signer, types.Beacon{1}, 777, 2, 5), ), }, { @@ -695,7 +698,7 @@ func TestBuild(t *testing.T) { signer, 17, types.ATXID{1}, types.Opinion{Hash: types.Hash32{1}}, expectRef(types.BallotID{1}), expectMeshHash(types.Hash32{9, 9, 9}), - expectCounters(signer, 3, types.Beacon{1}, 777, 3, 7), + expectCounters(signer, types.Beacon{1}, 777, 3, 7), ), }, }, @@ -708,8 +711,8 @@ func TestBuild(t *testing.T) { lid: 15, beacon: types.Beacon{1}, atxs: []*types.ActivationTx{ - gatx(types.ATXID{1}, 2, signers[0].NodeID(), 1, genAtxWithNonce(777)), - gatx(types.ATXID{2}, 2, signers[1].NodeID(), 1, genAtxWithNonce(999)), + gatx(types.ATXID{1}, signers[0].NodeID(), 1, genAtxWithNonce(777)), + gatx(types.ATXID{2}, signers[1].NodeID(), 1, genAtxWithNonce(999)), }, opinion: &types.Opinion{Hash: types.Hash32{1}}, txs: []types.TransactionID{{1}, {2}}, @@ -723,7 +726,7 @@ func TestBuild(t *testing.T) { types.Beacon{1}, ), expectTxs([]types.TransactionID{{1}, {2}}), - expectCounters(signers[0], 3, types.Beacon{1}, 777, 0, 6, 9, 12, 16, 18, 20, 23), + expectCounters(signers[0], types.Beacon{1}, 777, 0, 6, 9, 12, 16, 18, 20, 23), ), expectProposal( signers[1], 15, types.ATXID{2}, types.Opinion{Hash: types.Hash32{1}}, @@ -733,7 +736,7 @@ func TestBuild(t *testing.T) { types.Beacon{1}, ), expectTxs([]types.TransactionID{{1}, {2}}), - expectCounters(signers[1], 3, types.Beacon{1}, 999, 0, 4, 6, 8, 9, 17), + expectCounters(signers[1], types.Beacon{1}, 999, 0, 4, 6, 8, 9, 17), ), }, }, diff --git a/node/node.go b/node/node.go index 6c404e41a3..ab38a09fda 100644 --- a/node/node.go +++ b/node/node.go @@ -1580,7 +1580,7 @@ func (app *App) grpcService(svc grpcserver.Service, lg log.Log) (grpcserver.Serv return nil, fmt.Errorf("unknown service %s", svc) } -func (app *App) startAPIServices(ctx context.Context) error { +func (app *App) startAPIServices() error { logger := app.addLogger(GRPCLogger, app.log) grpczap.SetGrpcLoggerV2(grpcLog, logger.Zap()) @@ -2189,7 +2189,7 @@ func (app *App) startSynchronous(ctx context.Context) (err error) { app.log.Info("no need to preserve data after recovery") } - if err := app.startAPIServices(ctx); err != nil { + if err := app.startAPIServices(); err != nil { return err } diff --git a/node/node_test.go b/node/node_test.go index 6b6f7773ea..197fdc22ee 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -228,7 +228,7 @@ func TestSpacemeshApp_GrpcService(t *testing.T) { require.NoError(t, err) run := func(c *cobra.Command, args []string) error { - return app.startAPIServices(context.Background()) + return app.startAPIServices() } defer app.stopServices(context.Background()) @@ -277,7 +277,7 @@ func TestSpacemeshApp_JsonServiceNotRunning(t *testing.T) { // Make sure the service is not running by default run := func(c *cobra.Command, args []string) error { - return app.startAPIServices(context.Background()) + return app.startAPIServices() } str, err := testArgs(context.Background(), cmdWithRun(run)) @@ -312,7 +312,7 @@ func TestSpacemeshApp_JsonService(t *testing.T) { // Make sure the service is not running by default run := func(c *cobra.Command, args []string) error { - return app.startAPIServices(context.Background()) + return app.startAPIServices() } // Test starting the JSON server from the command line @@ -368,7 +368,7 @@ func TestSpacemeshApp_NodeService(t *testing.T) { appCtx, appCancel := context.WithCancel(context.Background()) defer appCancel() - run := func(c *cobra.Command, args []string) error { + run := func(_ *cobra.Command, _ []string) error { // Give the error channel a buffer events.CloseEventReporter() events.InitializeReporter() @@ -483,7 +483,7 @@ func TestSpacemeshApp_TransactionService(t *testing.T) { appCtx, appCancel := context.WithCancel(context.Background()) defer appCancel() - run := func(c *cobra.Command, args []string) error { + run := func(_ *cobra.Command, _ []string) error { require.NoError(t, app.Initialize()) // GRPC configuration diff --git a/proposals/eligibility_validator_test.go b/proposals/eligibility_validator_test.go index 2168c6e5d4..4be8f6cffe 100644 --- a/proposals/eligibility_validator_test.go +++ b/proposals/eligibility_validator_test.go @@ -14,11 +14,12 @@ import ( "github.com/spacemeshos/go-spacemesh/tortoise" ) +const units = uint32(10) + func gatx( id types.ATXID, epoch types.EpochID, smesher types.NodeID, - units uint32, nonce types.VRFPostIndex, ) types.ActivationTx { atx := types.ActivationTx{ @@ -83,8 +84,10 @@ func geligibilities(js ...uint32) (rst []types.VotingEligibility) { return rst } +const j = uint32(1) + // geligibilityWithSig is useful to influence CalcEligibleLayer. -func geligibilityWithSig(j uint32, sig string) []types.VotingEligibility { +func geligibilityWithSig(sig string) []types.VotingEligibility { el := types.VotingEligibility{J: j} copy(el.Sig[:], sig) return []types.VotingEligibility{el} @@ -140,8 +143,8 @@ func TestEligibilityValidator(t *testing.T) { desc: "ref ballot in current", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1}, 10, 10), - gatx(types.ATXID{2}, publish, types.NodeID{2}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1}, 10), + gatx(types.ATXID{2}, publish, types.NodeID{2}, 10), }, actives: gactiveset(types.ATXID{1}, types.ATXID{2}), executed: gballot( @@ -156,8 +159,8 @@ func TestEligibilityValidator(t *testing.T) { current: epoch.FirstLayer(), minWeight: 10000, atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1}, 10, 10), - gatx(types.ATXID{2}, publish, types.NodeID{2}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1}, 10), + gatx(types.ATXID{2}, publish, types.NodeID{2}, 10), }, actives: gactiveset(types.ATXID{1}, types.ATXID{2}), executed: gballot( @@ -186,7 +189,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "ref ballot in previous", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish-1, types.NodeID{1}, 10, 10), + gatx(types.ATXID{1}, publish-1, types.NodeID{1}, 10), }, executed: gballot( types.BallotID{1}, types.ATXID{1}, @@ -218,7 +221,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "ref ballot in secondary no epoch data", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish-1, types.NodeID{1}, 10, 10), + gatx(types.ATXID{1}, publish-1, types.NodeID{1}, 10), }, executed: gballot( types.BallotID{1}, types.ATXID{1}, @@ -232,7 +235,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "ref ballot in current no epoch data", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 10, 10), + gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 10), }, executed: gballot( types.BallotID{1}, types.ATXID{1}, @@ -246,7 +249,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "ref ballot in current activeset empty", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 10, 10), + gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 10), }, actives: types.ATXIDList{}, executed: gballot( @@ -261,7 +264,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "ref ballot in current empty beacon", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 10, 10), + gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 10), }, executed: gballot( types.BallotID{1}, types.ATXID{1}, @@ -275,7 +278,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "mismatched num eligible", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 10, 0), + gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 0), }, actives: gactiveset(types.ATXID{1}), executed: gballot( @@ -290,7 +293,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "ballot targets wrong epoch", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 10, 0), + gatx(types.ATXID{1}, epoch-1, types.NodeID{1}, 0), }, actives: gactiveset(types.ATXID{1}), executed: gballot( @@ -306,7 +309,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "ballot uses wrong atx", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, epoch-1, types.NodeID{2}, 10, 0), + gatx(types.ATXID{1}, epoch-1, types.NodeID{2}, 0), }, actives: gactiveset(types.ATXID{1}), executed: gballot( @@ -337,7 +340,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "secondary ballot", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10), }, ballots: []types.Ballot{ gballot( @@ -353,14 +356,14 @@ func TestEligibilityValidator(t *testing.T) { types.NodeID{1, 1, 1}, epoch.FirstLayer()+2, types.BallotID{1}, - geligibilityWithSig(1, "test1111111"), + geligibilityWithSig("test1111111"), ), }, { desc: "secondary ballot empty ref", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10), }, executed: gref( types.BallotID{2}, types.ATXID{1}, @@ -376,7 +379,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "secondary ballot missing ref", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10), }, executed: gref( types.BallotID{2}, types.ATXID{1}, @@ -392,7 +395,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "secondary ballot atx id mismatch", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10), }, ballots: []types.Ballot{ gballot( @@ -408,7 +411,7 @@ func TestEligibilityValidator(t *testing.T) { types.NodeID{1, 1, 1}, epoch.FirstLayer()+2, types.BallotID{1}, - geligibilityWithSig(1, "test1111111"), + geligibilityWithSig("test1111111"), ), fail: true, err: "sharing atx with a reference ballot", @@ -417,7 +420,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "secondary ballot smesher id mismatch", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10), }, ballots: []types.Ballot{ gballot( @@ -433,7 +436,7 @@ func TestEligibilityValidator(t *testing.T) { types.NodeID{1, 1, 1}, epoch.FirstLayer()+2, types.BallotID{1}, - geligibilityWithSig(1, "test1111111"), + geligibilityWithSig("test1111111"), ), fail: true, err: "mismatched smesher id with refballot", @@ -442,7 +445,7 @@ func TestEligibilityValidator(t *testing.T) { desc: "secondary ballot mismatched epochs", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1, 1, 1}, 10), }, ballots: []types.Ballot{ gballot( @@ -458,7 +461,7 @@ func TestEligibilityValidator(t *testing.T) { types.NodeID{1, 1, 1}, epoch.FirstLayer()+2, types.BallotID{1}, - geligibilityWithSig(1, "test1111111"), + geligibilityWithSig("test1111111"), ), fail: true, err: "targets mismatched epoch", @@ -467,8 +470,8 @@ func TestEligibilityValidator(t *testing.T) { desc: "ref ballot bad elig order", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1}, 10, 10), - gatx(types.ATXID{2}, publish, types.NodeID{2}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1}, 10), + gatx(types.ATXID{2}, publish, types.NodeID{2}, 10), }, actives: gactiveset(types.ATXID{1}, types.ATXID{2}), executed: gballot( @@ -484,8 +487,8 @@ func TestEligibilityValidator(t *testing.T) { desc: "proof overflows slots", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1}, 10, 10), - gatx(types.ATXID{2}, publish, types.NodeID{2}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1}, 10), + gatx(types.ATXID{2}, publish, types.NodeID{2}, 10), }, actives: gactiveset(types.ATXID{1}, types.ATXID{2}), executed: gballot( @@ -501,8 +504,8 @@ func TestEligibilityValidator(t *testing.T) { desc: "verified didnt pass", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1}, 10, 10), - gatx(types.ATXID{2}, publish, types.NodeID{2}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1}, 10), + gatx(types.ATXID{2}, publish, types.NodeID{2}, 10), }, actives: gactiveset(types.ATXID{1}, types.ATXID{2}), executed: gballot( @@ -519,15 +522,15 @@ func TestEligibilityValidator(t *testing.T) { desc: "layer is wrong", current: epoch.FirstLayer(), atxs: []types.ActivationTx{ - gatx(types.ATXID{1}, publish, types.NodeID{1}, 10, 10), - gatx(types.ATXID{2}, publish, types.NodeID{2}, 10, 10), + gatx(types.ATXID{1}, publish, types.NodeID{1}, 10), + gatx(types.ATXID{2}, publish, types.NodeID{2}, 10), }, actives: gactiveset(types.ATXID{1}, types.ATXID{2}), executed: gballot( types.BallotID{1}, types.ATXID{1}, types.NodeID{1}, epoch.FirstLayer(), gdata(15, types.Beacon{1}, gactiveset(types.ATXID{1}, types.ATXID{2}).Hash()), - geligibilityWithSig(1, "adjust layer"), + geligibilityWithSig("adjust layer"), ), fail: true, err: "ballot has incorrect layer index", diff --git a/proposals/handler_test.go b/proposals/handler_test.go index 37485e7428..65bb3d2723 100644 --- a/proposals/handler_test.go +++ b/proposals/handler_test.go @@ -56,17 +56,15 @@ type mockSet struct { mconsumer *MockproposalsConsumer } -func (ms *mockSet) decodeAnyBallots() *mockSet { +func (ms *mockSet) decodeAnyBallots() { ms.md.EXPECT().DecodeBallot(gomock.Any()).AnyTimes() ms.md.EXPECT().StoreBallot(gomock.Any()).AnyTimes() - return ms } -func (ms *mockSet) setCurrentLayer(layer types.LayerID) *mockSet { +func (ms *mockSet) setCurrentLayer(layer types.LayerID) { ms.mclock.EXPECT().CurrentLayer().Return(layer).AnyTimes() ms.mm.EXPECT().ProcessedLayer().Return(layer - 1).AnyTimes() ms.mclock.EXPECT().LayerToTime(gomock.Any()).Return(time.Now().Add(-5 * time.Second)).AnyTimes() - return ms } type testHandler struct { diff --git a/sql/atxs/atxs.go b/sql/atxs/atxs.go index 9d749a035b..2c995b3237 100644 --- a/sql/atxs/atxs.go +++ b/sql/atxs/atxs.go @@ -359,7 +359,7 @@ func LoadBlob(ctx context.Context, db sql.Executor, id []byte, blob *sql.Blob) ( // We don't use the provided blob in this case to avoid // caching references to the underlying slice (subsequent calls would modify it). var blob sql.Blob - v, err := getBlob(ctx, db, id, &blob) + v, err := getBlob(db, id, &blob) if err != nil { return nil, err } @@ -373,10 +373,10 @@ func LoadBlob(ctx context.Context, db sql.Executor, id []byte, blob *sql.Blob) ( return cached.version, nil } - return getBlob(ctx, db, id, blob) + return getBlob(db, id, blob) } -func getBlob(ctx context.Context, db sql.Executor, id []byte, blob *sql.Blob) (types.AtxVersion, error) { +func getBlob(db sql.Executor, id []byte, blob *sql.Blob) (types.AtxVersion, error) { var version types.AtxVersion rows, err := db.Exec("select atx, version from atx_blobs where id = ?1", func(stmt *sql.Statement) { diff --git a/sql/atxs/atxs_test.go b/sql/atxs/atxs_test.go index 67c7811715..b2480a9a21 100644 --- a/sql/atxs/atxs_test.go +++ b/sql/atxs/atxs_test.go @@ -29,13 +29,13 @@ func TestMain(m *testing.M) { } func TestGet(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) atxList := make([]*types.ActivationTx, 0) for i := 0; i < 3; i++ { sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withPublishEpoch(types.EpochID(i))) + atx := newAtx(sig, withPublishEpoch(types.EpochID(i))) atxList = append(atxList, atx) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) } @@ -51,13 +51,13 @@ func TestGet(t *testing.T) { } func TestAll(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) var expected []types.ATXID for i := 0; i < 3; i++ { sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withPublishEpoch(types.EpochID(i))) + atx := newAtx(sig, withPublishEpoch(types.EpochID(i))) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) expected = append(expected, atx.ID()) } @@ -68,13 +68,13 @@ func TestAll(t *testing.T) { } func TestHasID(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) atxList := make([]*types.ActivationTx, 0) for i := 0; i < 3; i++ { sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withPublishEpoch(types.EpochID(i))) + atx := newAtx(sig, withPublishEpoch(types.EpochID(i))) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) atxList = append(atxList, atx) } @@ -91,7 +91,7 @@ func TestHasID(t *testing.T) { } func Test_IdentityExists(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) @@ -100,7 +100,7 @@ func Test_IdentityExists(t *testing.T) { require.NoError(t, err) require.False(t, yes) - atx := newAtx(t, sig) + atx := newAtx(sig) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) yes, err = atxs.IdentityExists(db, sig.NodeID()) @@ -109,7 +109,7 @@ func Test_IdentityExists(t *testing.T) { } func TestGetFirstIDByNodeID(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) @@ -119,10 +119,10 @@ func TestGetFirstIDByNodeID(t *testing.T) { require.NoError(t, err) // Arrange - atx1 := newAtx(t, sig1, withPublishEpoch(1)) - atx2 := newAtx(t, sig1, withPublishEpoch(2), withSequence(atx1.Sequence+1)) - atx3 := newAtx(t, sig2, withPublishEpoch(3)) - atx4 := newAtx(t, sig2, withPublishEpoch(4), withSequence(atx3.Sequence+1)) + atx1 := newAtx(sig1, withPublishEpoch(1)) + atx2 := newAtx(sig1, withPublishEpoch(2), withSequence(atx1.Sequence+1)) + atx3 := newAtx(sig2, withPublishEpoch(3)) + atx4 := newAtx(sig2, withPublishEpoch(4), withSequence(atx3.Sequence+1)) for _, atx := range []*types.ActivationTx{atx1, atx2, atx3, atx4} { require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) @@ -142,7 +142,7 @@ func TestGetFirstIDByNodeID(t *testing.T) { } func TestLatestN(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig1, err := signing.NewEdSigner() require.NoError(t, err) @@ -151,12 +151,12 @@ func TestLatestN(t *testing.T) { sig3, err := signing.NewEdSigner() require.NoError(t, err) - atx1 := newAtx(t, sig1, withPublishEpoch(1), withSequence(0)) - atx2 := newAtx(t, sig1, withPublishEpoch(2), withSequence(1)) - atx3 := newAtx(t, sig2, withPublishEpoch(3), withSequence(1)) - atx4 := newAtx(t, sig2, withPublishEpoch(4), withSequence(2)) - atx5 := newAtx(t, sig2, withPublishEpoch(5), withSequence(3)) - atx6 := newAtx(t, sig3, withPublishEpoch(1), withSequence(0)) + atx1 := newAtx(sig1, withPublishEpoch(1), withSequence(0)) + atx2 := newAtx(sig1, withPublishEpoch(2), withSequence(1)) + atx3 := newAtx(sig2, withPublishEpoch(3), withSequence(1)) + atx4 := newAtx(sig2, withPublishEpoch(4), withSequence(2)) + atx5 := newAtx(sig2, withPublishEpoch(5), withSequence(3)) + atx6 := newAtx(sig3, withPublishEpoch(1), withSequence(0)) for _, atx := range []*types.ActivationTx{atx1, atx2, atx3, atx4, atx5, atx6} { require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) @@ -234,15 +234,15 @@ func TestLatestN(t *testing.T) { } func TestGetByEpochAndNodeID(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig1, err := signing.NewEdSigner() require.NoError(t, err) sig2, err := signing.NewEdSigner() require.NoError(t, err) - atx1 := newAtx(t, sig1, withPublishEpoch(1)) - atx2 := newAtx(t, sig2, withPublishEpoch(2)) + atx1 := newAtx(sig1, withPublishEpoch(1)) + atx2 := newAtx(sig2, withPublishEpoch(2)) for _, atx := range []*types.ActivationTx{atx1, atx2} { require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) @@ -266,7 +266,7 @@ func TestGetByEpochAndNodeID(t *testing.T) { } func TestGetLastIDByNodeID(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) @@ -276,10 +276,10 @@ func TestGetLastIDByNodeID(t *testing.T) { require.NoError(t, err) // Arrange - atx1 := newAtx(t, sig1, withPublishEpoch(1)) - atx2 := newAtx(t, sig1, withPublishEpoch(2), withSequence(atx1.Sequence+1)) - atx3 := newAtx(t, sig2, withPublishEpoch(3)) - atx4 := newAtx(t, sig2, withPublishEpoch(4), withSequence(atx3.Sequence+1)) + atx1 := newAtx(sig1, withPublishEpoch(1)) + atx2 := newAtx(sig1, withPublishEpoch(2), withSequence(atx1.Sequence+1)) + atx3 := newAtx(sig2, withPublishEpoch(3)) + atx4 := newAtx(sig2, withPublishEpoch(4), withSequence(atx3.Sequence+1)) for _, atx := range []*types.ActivationTx{atx1, atx2, atx3, atx4} { require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) @@ -300,7 +300,7 @@ func TestGetLastIDByNodeID(t *testing.T) { } func TestGetIDByEpochAndNodeID(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig1, err := signing.NewEdSigner() require.NoError(t, err) @@ -311,10 +311,10 @@ func TestGetIDByEpochAndNodeID(t *testing.T) { e2 := types.EpochID(2) e3 := types.EpochID(3) - atx1 := newAtx(t, sig1, withPublishEpoch(e1)) - atx2 := newAtx(t, sig1, withPublishEpoch(e2)) - atx3 := newAtx(t, sig2, withPublishEpoch(e2)) - atx4 := newAtx(t, sig2, withPublishEpoch(e3)) + atx1 := newAtx(sig1, withPublishEpoch(e1)) + atx2 := newAtx(sig1, withPublishEpoch(e2)) + atx3 := newAtx(sig2, withPublishEpoch(e2)) + atx4 := newAtx(sig2, withPublishEpoch(e3)) for _, atx := range []*types.ActivationTx{atx1, atx2, atx3, atx4} { require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) @@ -344,7 +344,7 @@ func TestGetIDByEpochAndNodeID(t *testing.T) { } func TestGetIDsByEpoch(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) ctx := context.Background() sig1, err := signing.NewEdSigner() @@ -356,10 +356,10 @@ func TestGetIDsByEpoch(t *testing.T) { e2 := types.EpochID(2) e3 := types.EpochID(3) - atx1 := newAtx(t, sig1, withPublishEpoch(e1)) - atx2 := newAtx(t, sig1, withPublishEpoch(e2)) - atx3 := newAtx(t, sig2, withPublishEpoch(e2)) - atx4 := newAtx(t, sig2, withPublishEpoch(e3)) + atx1 := newAtx(sig1, withPublishEpoch(e1)) + atx2 := newAtx(sig1, withPublishEpoch(e2)) + atx3 := newAtx(sig2, withPublishEpoch(e2)) + atx4 := newAtx(sig2, withPublishEpoch(e3)) for _, atx := range []*types.ActivationTx{atx1, atx2, atx3, atx4} { require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) @@ -392,12 +392,12 @@ func TestGetIDsByEpochCached(t *testing.T) { e2 := types.EpochID(2) e3 := types.EpochID(3) - atx1 := newAtx(t, sig1, withPublishEpoch(e1)) - atx2 := newAtx(t, sig1, withPublishEpoch(e2)) - atx3 := newAtx(t, sig2, withPublishEpoch(e2)) - atx4 := newAtx(t, sig2, withPublishEpoch(e3)) - atx5 := newAtx(t, sig2, withPublishEpoch(e3)) - atx6 := newAtx(t, sig2, withPublishEpoch(e3)) + atx1 := newAtx(sig1, withPublishEpoch(e1)) + atx2 := newAtx(sig1, withPublishEpoch(e2)) + atx3 := newAtx(sig2, withPublishEpoch(e2)) + atx4 := newAtx(sig2, withPublishEpoch(e3)) + atx5 := newAtx(sig2, withPublishEpoch(e3)) + atx6 := newAtx(sig2, withPublishEpoch(e3)) for _, atx := range []*types.ActivationTx{atx1, atx2, atx3, atx4} { require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) @@ -454,14 +454,14 @@ func TestGetIDsByEpochCached(t *testing.T) { } func Test_IterateAtxsWithMalfeasance(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) e1 := types.EpochID(1) m := make(map[types.ATXID]bool) for i := uint32(0); i < 20; i++ { sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withPublishEpoch(types.EpochID(i/4))) + atx := newAtx(sig, withPublishEpoch(types.EpochID(i/4))) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) malicious := (i % 2) == 0 m[atx.ID()] = malicious @@ -484,14 +484,14 @@ func Test_IterateAtxsWithMalfeasance(t *testing.T) { } func Test_IterateAtxIdsWithMalfeasance(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) e1 := types.EpochID(1) m := make(map[types.ATXID]bool) for i := uint32(0); i < 20; i++ { sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withPublishEpoch(types.EpochID(i/4))) + atx := newAtx(sig, withPublishEpoch(types.EpochID(i/4))) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) malicious := (i % 2) == 0 m[atx.ID()] = malicious @@ -515,15 +515,15 @@ func Test_IterateAtxIdsWithMalfeasance(t *testing.T) { func TestVRFNonce(t *testing.T) { // Arrange - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) - atx1 := newAtx(t, sig, withPublishEpoch(20), withNonce(333)) + atx1 := newAtx(sig, withPublishEpoch(20), withNonce(333)) require.NoError(t, atxs.Add(db, atx1, types.AtxBlob{})) - atx2 := newAtx(t, sig, withPublishEpoch(50), withNonce(777)) + atx2 := newAtx(sig, withPublishEpoch(50), withNonce(777)) require.NoError(t, atxs.Add(db, atx2, types.AtxBlob{})) // Act & Assert @@ -548,12 +548,12 @@ func TestVRFNonce(t *testing.T) { } func TestLoadBlob(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) ctx := context.Background() sig, err := signing.NewEdSigner() require.NoError(t, err) - atx1 := newAtx(t, sig, withPublishEpoch(1)) + atx1 := newAtx(sig, withPublishEpoch(1)) blob := types.AtxBlob{ Blob: []byte("blob"), Version: types.AtxV1, @@ -572,7 +572,7 @@ func TestLoadBlob(t *testing.T) { require.Equal(t, []int{len(blob1.Bytes)}, blobSizes) var blob2 sql.Blob - atx2 := newAtx(t, sig) + atx2 := newAtx(sig) blob = types.AtxBlob{ Blob: []byte("blob2 of different size"), Version: types.AtxV2, @@ -606,11 +606,11 @@ func TestLoadBlob(t *testing.T) { } func TestLoadBlob_DefaultsToV1(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig) + atx := newAtx(sig) blob := types.AtxBlob{ Blob: []byte("blob"), Version: 0, @@ -631,7 +631,7 @@ func TestGetBlobCached(t *testing.T) { sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withPublishEpoch(1)) + atx := newAtx(sig, withPublishEpoch(1)) blob := types.AtxBlob{Blob: []byte("blob")} require.NoError(t, atxs.Add(db, atx, blob)) @@ -712,7 +712,7 @@ func TestCachedBlobEviction(t *testing.T) { blobs := make([][]byte, 11) var b sql.Blob for n := range addedATXs { - atx := newAtx(t, sig, withPublishEpoch(1)) + atx := newAtx(sig, withPublishEpoch(1)) blob := types.AtxBlob{Blob: []byte(fmt.Sprintf("blob %d", n))} require.NoError(t, atxs.Add(db, atx, blob)) addedATXs[n] = atx @@ -741,12 +741,12 @@ func TestCachedBlobEviction(t *testing.T) { } func TestCheckpointATX(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) ctx := context.Background() sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withPublishEpoch(3), withSequence(4)) + atx := newAtx(sig, withPublishEpoch(3), withSequence(4)) catx := &atxs.CheckpointAtx{ ID: atx.ID(), Epoch: atx.PublishEpoch, @@ -788,7 +788,7 @@ func TestCheckpointATX(t *testing.T) { } func TestAdd(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) nonExistingATXID := types.ATXID(types.CalcHash32([]byte("0"))) _, err := atxs.Get(db, nonExistingATXID) @@ -796,7 +796,7 @@ func TestAdd(t *testing.T) { sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withPublishEpoch(1)) + atx := newAtx(sig, withPublishEpoch(1)) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) require.ErrorIs(t, atxs.Add(db, atx, types.AtxBlob{}), sql.ErrObjectExists) @@ -832,7 +832,7 @@ func withCoinbase(addr types.Address) createAtxOpt { } } -func newAtx(t testing.TB, signer *signing.EdSigner, opts ...createAtxOpt) *types.ActivationTx { +func newAtx(signer *signing.EdSigner, opts ...createAtxOpt) *types.ActivationTx { atx := &types.ActivationTx{ NumUnits: 2, TickCount: 1, @@ -969,7 +969,7 @@ func TestGetIDWithMaxHeight(t *testing.T) { }, } { t.Run(tc.desc, func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) var sigs []*signing.EdSigner var ids []types.ATXID filtered := make(map[types.ATXID]struct{}) @@ -1010,7 +1010,7 @@ func TestLatest(t *testing.T) { {"out of order", []uint32{3, 4, 1, 2}, 4}, } { t.Run(tc.desc, func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) for i, epoch := range tc.epochs { full := &types.ActivationTx{ PublishEpoch: types.EpochID(epoch), @@ -1029,15 +1029,15 @@ func TestLatest(t *testing.T) { } func Test_PrevATXCollision(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) // create two ATXs with the same PrevATXID prevATXID := types.RandomATXID() - atx1 := newAtx(t, sig, withPublishEpoch(1)) - atx2 := newAtx(t, sig, withPublishEpoch(2)) + atx1 := newAtx(sig, withPublishEpoch(1)) + atx2 := newAtx(sig, withPublishEpoch(2)) require.NoError(t, atxs.Add(db, atx1, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx1.ID(), prevATXID, 0, sig.NodeID(), 10)) @@ -1060,7 +1060,7 @@ func Test_PrevATXCollision(t *testing.T) { require.NoError(t, err) otherIds = append(otherIds, otherSig.NodeID()) - atx2 := newAtx(t, otherSig, withPublishEpoch(types.EpochID(i+1))) + atx2 := newAtx(otherSig, withPublishEpoch(types.EpochID(i+1))) require.NoError(t, atxs.Add(db, atx2, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx2.ID(), prevATXID, 0, atx2.SmesherID, 10)) } @@ -1082,16 +1082,16 @@ func TestCoinbase(t *testing.T) { t.Parallel() t.Run("not found", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) _, err := atxs.Coinbase(db, types.NodeID{}) require.ErrorIs(t, err, sql.ErrNotFound) }) t.Run("found", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) - atx := newAtx(t, sig, withCoinbase(types.Address{1, 2, 3})) + atx := newAtx(sig, withCoinbase(types.Address{1, 2, 3})) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) cb, err := atxs.Coinbase(db, sig.NodeID()) require.NoError(t, err) @@ -1099,11 +1099,11 @@ func TestCoinbase(t *testing.T) { }) t.Run("picks last", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) - atx1 := newAtx(t, sig, withPublishEpoch(1), withCoinbase(types.Address{1, 2, 3})) - atx2 := newAtx(t, sig, withPublishEpoch(2), withCoinbase(types.Address{4, 5, 6})) + atx1 := newAtx(sig, withPublishEpoch(1), withCoinbase(types.Address{1, 2, 3})) + atx2 := newAtx(sig, withPublishEpoch(2), withCoinbase(types.Address{4, 5, 6})) require.NoError(t, atxs.Add(db, atx1, types.AtxBlob{})) require.NoError(t, atxs.Add(db, atx2, types.AtxBlob{})) cb, err := atxs.Coinbase(db, sig.NodeID()) @@ -1116,13 +1116,13 @@ func TestUnits(t *testing.T) { t.Parallel() t.Run("ATX not found", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) _, err := atxs.Units(db, types.RandomATXID(), types.RandomNodeID()) require.ErrorIs(t, err, sql.ErrNotFound) }) t.Run("smesher has no units in ATX", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) atxID := types.RandomATXID() require.NoError(t, atxs.SetPost(db, atxID, types.EmptyATXID, 0, types.RandomNodeID(), 10)) _, err := atxs.Units(db, atxID, types.RandomNodeID()) @@ -1130,7 +1130,7 @@ func TestUnits(t *testing.T) { }) t.Run("returns units for given smesher in given ATX", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) atxID := types.RandomATXID() units := map[types.NodeID]uint32{ {1, 2, 3}: 10, @@ -1159,15 +1159,15 @@ func Test_AtxWithPrevious(t *testing.T) { prev := types.RandomATXID() t.Run("no atxs", func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) _, err := atxs.AtxWithPrevious(db, prev, sig.NodeID()) require.ErrorIs(t, err, sql.ErrNotFound) }) t.Run("finds other ATX with same previous", func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) prev := types.RandomATXID() - atx := newAtx(t, sig) + atx := newAtx(sig) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx.ID(), prev, 0, sig.NodeID(), 10)) @@ -1176,9 +1176,9 @@ func Test_AtxWithPrevious(t *testing.T) { require.Equal(t, atx.ID(), id) }) t.Run("finds other ATX with same previous (empty)", func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) - atx := newAtx(t, sig) + atx := newAtx(sig) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx.ID(), types.EmptyATXID, 0, sig.NodeID(), 10)) @@ -1187,17 +1187,17 @@ func Test_AtxWithPrevious(t *testing.T) { require.Equal(t, atx.ID(), id) }) t.Run("same previous used by 2 IDs in two ATXs", func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig2, err := signing.NewEdSigner() require.NoError(t, err) prev := types.RandomATXID() - atx := newAtx(t, sig) + atx := newAtx(sig) require.NoError(t, atxs.Add(db, atx, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx.ID(), prev, 0, sig.NodeID(), 10)) - atx2 := newAtx(t, sig2) + atx2 := newAtx(sig2) require.NoError(t, atxs.Add(db, atx2, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx2.ID(), prev, 0, sig2.NodeID(), 10)) @@ -1217,17 +1217,17 @@ func Test_FindDoublePublish(t *testing.T) { require.NoError(t, err) t.Run("no atxs", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) _, err := atxs.FindDoublePublish(db, types.RandomNodeID(), 0) require.ErrorIs(t, err, sql.ErrNotFound) }) t.Run("no double publish", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) // one atx - atx0 := newAtx(t, sig, withPublishEpoch(1)) + atx0 := newAtx(sig, withPublishEpoch(1)) require.NoError(t, atxs.Add(db, atx0, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx0.ID(), types.EmptyATXID, 0, atx0.SmesherID, 10)) @@ -1235,7 +1235,7 @@ func Test_FindDoublePublish(t *testing.T) { require.ErrorIs(t, err, sql.ErrNotFound) // two atxs in different epochs - atx1 := newAtx(t, sig, withPublishEpoch(atx0.PublishEpoch+1)) + atx1 := newAtx(sig, withPublishEpoch(atx0.PublishEpoch+1)) require.NoError(t, atxs.Add(db, atx1, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx1.ID(), types.EmptyATXID, 0, atx0.SmesherID, 10)) @@ -1244,13 +1244,13 @@ func Test_FindDoublePublish(t *testing.T) { }) t.Run("double publish", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) - atx0 := newAtx(t, sig) + atx0 := newAtx(sig) require.NoError(t, atxs.Add(db, atx0, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx0.ID(), types.EmptyATXID, 0, atx0.SmesherID, 10)) - atx1 := newAtx(t, sig) + atx1 := newAtx(sig) require.NoError(t, atxs.Add(db, atx1, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx1.ID(), types.EmptyATXID, 0, atx0.SmesherID, 10)) @@ -1264,12 +1264,12 @@ func Test_FindDoublePublish(t *testing.T) { }) t.Run("double publish different smesher", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) atx0Signer, err := signing.NewEdSigner() require.NoError(t, err) - atx0 := newAtx(t, atx0Signer) + atx0 := newAtx(atx0Signer) require.NoError(t, atxs.Add(db, atx0, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx0.ID(), types.EmptyATXID, 0, atx0.SmesherID, 10)) require.NoError(t, atxs.SetPost(db, atx0.ID(), types.EmptyATXID, 0, sig.NodeID(), 10)) @@ -1277,7 +1277,7 @@ func Test_FindDoublePublish(t *testing.T) { atx1Signer, err := signing.NewEdSigner() require.NoError(t, err) - atx1 := newAtx(t, atx1Signer) + atx1 := newAtx(atx1Signer) require.NoError(t, atxs.Add(db, atx1, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx1.ID(), types.EmptyATXID, 0, atx1.SmesherID, 10)) require.NoError(t, atxs.SetPost(db, atx1.ID(), types.EmptyATXID, 0, sig.NodeID(), 10)) @@ -1292,13 +1292,13 @@ func Test_MergeConflict(t *testing.T) { t.Parallel() t.Run("no atxs", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) _, err := atxs.MergeConflict(db, types.RandomATXID(), 0) require.ErrorIs(t, err, sql.ErrNotFound) }) t.Run("no conflict", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) marriage := types.RandomATXID() atx := types.ActivationTx{MarriageATX: &marriage} @@ -1310,7 +1310,7 @@ func Test_MergeConflict(t *testing.T) { }) t.Run("finds conflict", func(t *testing.T) { t.Parallel() - db := sql.InMemory() + db := sql.InMemoryTest(t) marriage := types.RandomATXID() atx0 := types.ActivationTx{MarriageATX: &marriage} @@ -1370,20 +1370,20 @@ func Test_Previous(t *testing.T) { func TestPrevIDByNodeID(t *testing.T) { t.Run("no previous ATXs", func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) _, err := atxs.PrevIDByNodeID(db, types.RandomNodeID(), 0) require.ErrorIs(t, err, sql.ErrNotFound) }) t.Run("filters by epoch", func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) - atx1 := newAtx(t, sig, withPublishEpoch(1)) + atx1 := newAtx(sig, withPublishEpoch(1)) require.NoError(t, atxs.Add(db, atx1, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx1.ID(), types.EmptyATXID, 0, sig.NodeID(), 4)) - atx2 := newAtx(t, sig, withPublishEpoch(2)) + atx2 := newAtx(sig, withPublishEpoch(2)) require.NoError(t, atxs.Add(db, atx2, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx2.ID(), types.EmptyATXID, 0, sig.NodeID(), 4)) @@ -1399,18 +1399,18 @@ func TestPrevIDByNodeID(t *testing.T) { require.Equal(t, atx2.ID(), prevID) }) t.Run("the previous is merged and ID is not the signer", func(t *testing.T) { - db := sql.InMemory() + db := sql.InMemoryTest(t) sig, err := signing.NewEdSigner() require.NoError(t, err) id := types.RandomNodeID() - atx1 := newAtx(t, sig, withPublishEpoch(1)) + atx1 := newAtx(sig, withPublishEpoch(1)) require.NoError(t, atxs.Add(db, atx1, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx1.ID(), types.EmptyATXID, 0, sig.NodeID(), 4)) require.NoError(t, atxs.SetPost(db, atx1.ID(), types.EmptyATXID, 0, id, 8)) require.NoError(t, atxs.SetPost(db, atx1.ID(), types.EmptyATXID, 0, types.RandomNodeID(), 12)) - atx2 := newAtx(t, sig, withPublishEpoch(2)) + atx2 := newAtx(sig, withPublishEpoch(2)) require.NoError(t, atxs.Add(db, atx2, types.AtxBlob{})) require.NoError(t, atxs.SetPost(db, atx2.ID(), atx1.ID(), 0, sig.NodeID(), 4)) require.NoError(t, atxs.SetPost(db, atx2.ID(), atx1.ID(), 0, types.RandomNodeID(), 12)) diff --git a/sql/transactions/transactions_test.go b/sql/transactions/transactions_test.go index ed2eef3cc9..73d026aeca 100644 --- a/sql/transactions/transactions_test.go +++ b/sql/transactions/transactions_test.go @@ -17,11 +17,13 @@ import ( "github.com/spacemeshos/go-spacemesh/sql/transactions" ) +const amount = uint64(191) + func createTX( t *testing.T, principal *signing.EdSigner, dest types.Address, - nonce, amount, fee uint64, + nonce, fee uint64, ) *types.Transaction { t.Helper() @@ -78,9 +80,9 @@ func TestAddGetHas(t *testing.T) { signer2, err := signing.NewEdSigner(signing.WithKeyFromRand(rng)) require.NoError(t, err) txs := []*types.Transaction{ - createTX(t, signer1, types.Address{1}, 1, 191, 1), - createTX(t, signer2, types.Address{2}, 1, 191, 1), - createTX(t, signer1, types.Address{3}, 1, 191, 1), + createTX(t, signer1, types.Address{1}, 1, 1), + createTX(t, signer2, types.Address{2}, 1, 1), + createTX(t, signer1, types.Address{3}, 1, 1), } received := time.Now() @@ -147,7 +149,7 @@ func TestAddToProposal(t *testing.T) { rng := rand.New(rand.NewSource(1001)) signer, err := signing.NewEdSigner(signing.WithKeyFromRand(rng)) require.NoError(t, err) - tx := createTX(t, signer, types.Address{1}, 1, 191, 1) + tx := createTX(t, signer, types.Address{1}, 1, 1) require.NoError(t, transactions.Add(db, tx, time.Now())) lid := types.LayerID(10) @@ -202,7 +204,7 @@ func TestAddToBlock(t *testing.T) { rng := rand.New(rand.NewSource(1001)) signer, err := signing.NewEdSigner(signing.WithKeyFromRand(rng)) require.NoError(t, err) - tx := createTX(t, signer, types.Address{1}, 1, 191, 1) + tx := createTX(t, signer, types.Address{1}, 1, 1) require.NoError(t, transactions.Add(db, tx, time.Now())) lid := types.LayerID(10) @@ -227,7 +229,7 @@ func TestApply_AlreadyApplied(t *testing.T) { lid := types.LayerID(10) signer, err := signing.NewEdSigner(signing.WithKeyFromRand(rng)) require.NoError(t, err) - tx := createTX(t, signer, types.Address{1}, 1, 191, 1) + tx := createTX(t, signer, types.Address{1}, 1, 1) require.NoError(t, transactions.Add(db, tx, time.Now())) bid := types.RandomBlockID() @@ -268,7 +270,7 @@ func TestApplyAndUndoLayers(t *testing.T) { for lid := firstLayer; lid.Before(firstLayer.Add(numLayers)); lid = lid.Add(1) { signer, err := signing.NewEdSigner(signing.WithKeyFromRand(rng)) require.NoError(t, err) - tx := createTX(t, signer, types.Address{1}, uint64(lid), 191, 2) + tx := createTX(t, signer, types.Address{1}, uint64(lid), 2) require.NoError(t, transactions.Add(db, tx, time.Now())) bid := types.RandomBlockID() @@ -309,7 +311,7 @@ func TestGetBlob(t *testing.T) { for i := 0; i < numTXs; i++ { signer, err := signing.NewEdSigner(signing.WithKeyFromRand(rng)) require.NoError(t, err) - tx := createTX(t, signer, types.Address{1}, 1, 191, 1) + tx := createTX(t, signer, types.Address{1}, 1, 1) require.NoError(t, transactions.Add(db, tx, time.Now())) txs = append(txs, tx) } @@ -343,9 +345,9 @@ func TestGetByAddress(t *testing.T) { signer2Address := types.GenerateAddress(signer2.PublicKey().Bytes()) lid := types.LayerID(10) txs := []*types.Transaction{ - createTX(t, signer1, types.Address{1}, 1, 191, 1), - createTX(t, signer2, types.Address{2}, 1, 191, 1), - createTX(t, signer1, signer2Address, 1, 191, 1), + createTX(t, signer1, types.Address{1}, 1, 1), + createTX(t, signer2, types.Address{2}, 1, 1), + createTX(t, signer1, signer2Address, 1, 1), } received := time.Now() require.NoError(t, db.WithTx(context.Background(), func(dbtx *sql.Tx) error { @@ -379,10 +381,10 @@ func TestGetAcctPendingFromNonce(t *testing.T) { nonce := uint64(math.MaxInt64 + 1) received := time.Now() for i := 0; i < numTXs; i++ { - tx := createTX(t, signer, types.Address{1}, nonce+uint64(i), 191, 1) + tx := createTX(t, signer, types.Address{1}, nonce+uint64(i), 1) require.NoError(t, transactions.Add(db, tx, received.Add(time.Duration(i)))) if i > 0 { - tx = createTX(t, signer, types.Address{1}, nonce-uint64(i), 191, 1) + tx = createTX(t, signer, types.Address{1}, nonce-uint64(i), 1) require.NoError(t, transactions.Add(db, tx, received.Add(time.Duration(i)))) } } @@ -391,7 +393,7 @@ func TestGetAcctPendingFromNonce(t *testing.T) { for i := 0; i < numTXs; i++ { signer, err := signing.NewEdSigner(signing.WithKeyFromRand(rng)) require.NoError(t, err) - tx := createTX(t, signer, types.Address{1}, 1, 191, 1) + tx := createTX(t, signer, types.Address{1}, 1, 1) require.NoError(t, transactions.Add(db, tx, received)) } @@ -409,8 +411,8 @@ func TestAppliedLayer(t *testing.T) { signer, err := signing.NewEdSigner(signing.WithKeyFromRand(rng)) require.NoError(t, err) txs := []*types.Transaction{ - createTX(t, signer, types.Address{1}, 1, 191, 1), - createTX(t, signer, types.Address{1}, 2, 191, 1), + createTX(t, signer, types.Address{2}, 1, 1), + createTX(t, signer, types.Address{1}, 2, 1), } lid := types.LayerID(10) diff --git a/syncer/state_syncer.go b/syncer/state_syncer.go index 2b95b00138..eb3ab6964c 100644 --- a/syncer/state_syncer.go +++ b/syncer/state_syncer.go @@ -161,7 +161,7 @@ func (s *Syncer) processLayerOpinions(ctx context.Context, lid types.LayerID, re } } -func (s *Syncer) needCert(ctx context.Context, lid types.LayerID) (bool, error) { +func (s *Syncer) needCert(lid types.LayerID) (bool, error) { cutoff := s.certCutoffLayer() if !lid.After(cutoff) { return false, nil @@ -183,7 +183,7 @@ func (s *Syncer) layerOpinions( } v2OpnPoll.Inc() - needCert, err := s.needCert(ctx, lid) + needCert, err := s.needCert(lid) if err != nil { return nil, nil, err } @@ -233,7 +233,7 @@ func (s *Syncer) checkMeshAgreement( } func (s *Syncer) adopt(ctx context.Context, lid types.LayerID, certs []*types.Certificate) error { - needCert, err := s.needCert(ctx, lid) + needCert, err := s.needCert(lid) if err != nil { return err } diff --git a/systest/cluster/cluster.go b/systest/cluster/cluster.go index 36e495d77f..58338eafc6 100644 --- a/systest/cluster/cluster.go +++ b/systest/cluster/cluster.go @@ -742,8 +742,7 @@ func (c *Cluster) Wait(tctx *testcontext.Context, i int) error { func (c *Cluster) WaitAll(ctx context.Context) error { var eg errgroup.Group wait := func(clients []*NodeClient) { - for i := range c.clients { - client := c.clients[i] + for _, client := range clients { eg.Go(func() error { _, err := client.Resolve(ctx) return err diff --git a/systest/tests/smeshing_test.go b/systest/tests/smeshing_test.go index 3bc8ad8ede..de13a83bc4 100644 --- a/systest/tests/smeshing_test.go +++ b/systest/tests/smeshing_test.go @@ -35,10 +35,10 @@ func TestSmeshing(t *testing.T) { tctx := testcontext.New(t) tctx.RemoteSize = tctx.ClusterSize / 4 // 25% of nodes are remote vests := vestingAccs{ - prepareVesting(t, 3, 8, 20, 1e15, 10e15), - prepareVesting(t, 5, 8, 20, 1e15, 10e15), - prepareVesting(t, 1, 8, 20, 1e15, 1e15), - prepareVesting(t, 1, 8, 20, 0, 1e15), + prepareVesting(t, 3, 1e15, 10e15), + prepareVesting(t, 5, 1e15, 10e15), + prepareVesting(t, 1, 1e15, 1e15), + prepareVesting(t, 1, 0, 1e15), } cl, err := cluster.ReuseWait(tctx, cluster.WithKeys(tctx.ClusterSize), @@ -381,7 +381,12 @@ func genKeys(tb testing.TB, n int) (pks []ed25519.PrivateKey, pubs []ed25519.Pub return pks, pubs } -func prepareVesting(tb testing.TB, keys, start, end, initial, total int) vestingAcc { +const ( + start = 8 + end = 20 +) + +func prepareVesting(tb testing.TB, keys, initial, total int) vestingAcc { tb.Helper() pks, pubs := genKeys(tb, keys) var hashes []types.Hash32 diff --git a/tortoise/algorithm.go b/tortoise/algorithm.go index 215051c438..16623108f9 100644 --- a/tortoise/algorithm.go +++ b/tortoise/algorithm.go @@ -308,7 +308,7 @@ func (t *Tortoise) TallyVotes(ctx context.Context, lid types.LayerID) { defer t.mu.Unlock() waitTallyVotes.Observe(float64(time.Since(start).Nanoseconds())) start = time.Now() - t.trtl.tallyVotes(ctx, lid) + t.trtl.tallyVotes(lid) executeTallyVotes.Observe(float64(time.Since(start).Nanoseconds())) if t.tracer != nil { t.tracer.On(&TallyTrace{Layer: lid}) diff --git a/tortoise/algorithm_test.go b/tortoise/algorithm_test.go index 139f2eef13..dff054106d 100644 --- a/tortoise/algorithm_test.go +++ b/tortoise/algorithm_test.go @@ -10,15 +10,15 @@ func TestGetBallot(t *testing.T) { const n = 2 s := newSession(t) for i := 0; i < n; i++ { - s.smesher(i).atx(1, new(aopt).height(100).weight(400)) + s.smesher(i).atx(new(aopt).height(100).weight(400)) } - ref := s.smesher(0).atx(1).ballot(1, new(bopt). - beacon("a"). + ref := s.smesher(0).atx().ballot(1, new(bopt). + beacon(). totalEligibilities(s.epochEligibilities()). eligibilities(s.layerSize/n)) - secondary := s.smesher(0).atx(1).ballot(2) + secondary := s.smesher(0).atx().ballot(2) trt := s.tortoise() s.runOn(trt) diff --git a/tortoise/fixture_test.go b/tortoise/fixture_test.go index cf6fd691de..a5df0a5329 100644 --- a/tortoise/fixture_test.go +++ b/tortoise/fixture_test.go @@ -77,9 +77,11 @@ func (s *smesher) rawatx(id types.ATXID, publish types.EpochID, opts ...*aopt) * return val } +const publish = 1 + // atx accepts publish epoch and atx fields that are relevant for tortoise // as options. -func (s *smesher) atx(publish types.EpochID, opts ...*aopt) *atxAction { +func (s *smesher) atx(opts ...*aopt) *atxAction { id := hash.Sum([]byte(strconv.Itoa(s.id)), []byte(strconv.Itoa(int(publish)))) if val, exists := s.atxs[id]; exists { return val @@ -125,12 +127,14 @@ type bopt struct { opts []ballotOpt } -func (b *bopt) beacon(value string) *bopt { +const beaconVal = "a" + +func (b *bopt) beacon() *bopt { b.opts = append(b.opts, func(ballot *ballotAction) { if ballot.EpochData == nil { ballot.EpochData = &types.ReferenceData{} } - copy(ballot.EpochData.Beacon[:], value) + copy(ballot.EpochData.Beacon[:], beaconVal) }) return b } @@ -169,10 +173,12 @@ func (e *evotes) abstain(lid uint32) *evotes { return e } -func (e *evotes) support(lid int, id string, height uint64) *evotes { +const supportHeight = uint64(0) + +func (e *evotes) support(lid int, id string) *evotes { vote := types.Vote{ LayerID: types.GetEffectiveGenesis() + types.LayerID(lid), - Height: height, + Height: supportHeight, } copy(vote.ID[:], id) e.votes.Support = append(e.votes.Support, vote) @@ -490,7 +496,7 @@ func (s *session) block(lid int, id string, height uint64) *blockAction { return val } -func (s *session) hareblock(lid int, id string, height uint64) { +func (s *session) hareblock(lid int, id string) { s.hare(s.block(lid, id, height)) } @@ -511,12 +517,19 @@ func (b *beaconAction) execute(trt *Tortoise) { trt.OnBeacon(types.EpochID(b.epoch), b.beacon) } +// FIXME: these are pulled out to satisfy the linter, but must be +// actually changed so that the tests actually test _different_ values. +const ( + epoch = 1 + value = "a" + height = uint64(0) +) + // beacon accepts publish epoch and value of the beacon. -func (s *session) beacon(epoch uint32, value string) *beaconAction { +func (s *session) beacon() { beacon := &beaconAction{epoch: epoch + 1} copy(beacon.beacon[:], value) s.register(beacon) - return beacon } type results struct { @@ -548,7 +561,7 @@ const ( local ) -func (r *results) block(id string, height uint64, fields uint) *results { +func (r *results) block(id string, fields uint) *results { rst := &r.results[len(r.results)-1] block := result.Block{ Valid: fields&valid > 0, @@ -740,29 +753,29 @@ func TestSanity(t *testing.T) { const n = 2 s := newSession(t) for i := 0; i < n; i++ { - s.smesher(i).atx(1, new(aopt).height(100).weight(400)) + s.smesher(i).atx(new(aopt).height(100).weight(400)) } - s.beacon(1, "a") + s.beacon() for i := 0; i < n; i++ { - s.smesher(i).atx(1).ballot(1, new(bopt). - beacon("a"). + s.smesher(i).atx().ballot(1, new(bopt). + beacon(). totalEligibilities(s.epochEligibilities()). eligibilities(s.layerSize/n)) } s.tally(1) - s.hareblock(1, "aa", 0) + s.hareblock(1, "aa") for i := 0; i < n; i++ { - s.smesher(i).atx(1).ballot(2, new(bopt). + s.smesher(i).atx().ballot(2, new(bopt). eligibilities(s.layerSize/n). - votes(new(evotes).support(1, "aa", 0)), + votes(new(evotes).support(1, "aa")), ) } - s.hareblock(2, "bb", 0) + s.hareblock(2, "bb") s.tallyWait(2) s.updates(t, new(results). verified(0). - verified(1).block("aa", 0, valid|hare|data). - next(2).block("bb", 0, hare|data), + verified(1).block("aa", valid|hare|data). + next(2).block("bb", hare|data), ) t.Run("inorder", func(t *testing.T) { s.runInorder() }) t.Run("random", func(t *testing.T) { s.runRandomTopoN(100) }) @@ -772,26 +785,26 @@ func TestDisagreement(t *testing.T) { const n = 5 s := newSession(t) for i := 0; i < n; i++ { - s.smesher(i).atx(1, new(aopt).height(100).weight(400)) + s.smesher(i).atx(new(aopt).height(100).weight(400)) } - s.beacon(1, "a") + s.beacon() for i := 0; i < n; i++ { - s.smesher(i).atx(1).ballot(1, new(bopt). - beacon("a"). + s.smesher(i).atx().ballot(1, new(bopt). + beacon(). totalEligibilities(s.epochEligibilities()). eligibilities(s.layerSize/n)) } - s.hareblock(1, "aa", 0) + s.hareblock(1, "aa") for i := 0; i < n; i++ { v := new(evotes) if i < n/2 { - v = v.support(1, "aa", 0) + v = v.support(1, "aa") } else if i == n/2 { v = v.abstain(1) } else { v = v.against(1, "aa", 0) } - s.smesher(i).atx(1).ballot(2, new(bopt). + s.smesher(i).atx().ballot(2, new(bopt). eligibilities(s.layerSize/n). votes(v), ) @@ -799,7 +812,7 @@ func TestDisagreement(t *testing.T) { s.tallyWait(1) s.updates(t, new(results). verified(0). - next(1).block("aa", 0, hare|data), + next(1).block("aa", hare|data), ) s.runInorder() } @@ -807,22 +820,22 @@ func TestDisagreement(t *testing.T) { func TestOpinion(t *testing.T) { s := newSession(t) - s.smesher(0).atx(1, new(aopt).height(100).weight(2000)) + s.smesher(0).atx(new(aopt).height(100).weight(2000)) - s.beacon(1, "a") - s.smesher(0).atx(1).ballot(1, new(bopt). + s.beacon() + s.smesher(0).atx().ballot(1, new(bopt). eligibilities(s.layerSize). - beacon("a"). + beacon(). totalEligibilities(s.epochEligibilities()), ) for i := 2; i < s.epochSize; i++ { id := strconv.Itoa(i) - s.hareblock(i-1, id, 0) - s.smesher(0).atx(1).ballot(i, new(bopt). + s.hareblock(i-1, id) + s.smesher(0).atx().ballot(i, new(bopt). eligibilities(s.layerSize). votes(new(evotes). - base(s.smesher(0).atx(1).ballot(i-1)). - support(i-1, id, 0)), + base(s.smesher(0).atx().ballot(i-1)). + support(i-1, id)), ) } s.tallyWait(s.epochSize) @@ -833,12 +846,12 @@ func TestOpinion(t *testing.T) { func TestEpochGap(t *testing.T) { s := newSession(t).withEpochSize(4) for i := 0; i < 2; i++ { - s.smesher(i).atx(1, new(aopt).height(1).weight(10)) + s.smesher(i).atx(new(aopt).height(1).weight(10)) } - s.beacon(1, "a") + s.beacon() for i := 0; i < 2; i++ { - s.smesher(i).atx(1).ballot(1, new(bopt). - beacon("a"). + s.smesher(i).atx().ballot(1, new(bopt). + beacon(). totalEligibilities(s.epochEligibilities()). eligibilities(s.layerSize/2)) } @@ -846,14 +859,14 @@ func TestEpochGap(t *testing.T) { verified(0) for l := 2; l <= s.epochSize; l++ { id := strconv.Itoa(l - 1) - s.hareblock(l-1, id, 0) - rst = rst.verified(l-1).block(id, 0, hare|data|valid) + s.hareblock(l-1, id) + rst = rst.verified(l-1).block(id, hare|data|valid) for i := 0; i < 2; i++ { - s.smesher(i).atx(1).ballot(l, new(bopt). + s.smesher(i).atx().ballot(l, new(bopt). eligibilities(s.layerSize/2). votes(new(evotes). - base(s.smesher(i).atx(1).ballot(l-1)). - support(l-1, id, 0)), + base(s.smesher(i).atx().ballot(l-1)). + support(l-1, id)), ) } } diff --git a/tortoise/state.go b/tortoise/state.go index 6480cc263e..8d10e51819 100644 --- a/tortoise/state.go +++ b/tortoise/state.go @@ -434,7 +434,7 @@ type headerWithSign struct { sign sign } -func decodeVotes(evicted, blid types.LayerID, base *ballotInfo, exceptions types.Votes) (votes, types.LayerID, error) { +func decodeVotes(blid types.LayerID, base *ballotInfo, exceptions types.Votes) (votes, types.LayerID, error) { from := base.layer diff := map[types.LayerID]map[types.BlockID]headerWithSign{} for _, header := range exceptions.Against { diff --git a/tortoise/state_test.go b/tortoise/state_test.go index 3455320748..819560c62a 100644 --- a/tortoise/state_test.go +++ b/tortoise/state_test.go @@ -221,9 +221,9 @@ func (o *testOpinion) support(hid string, height uint64) *testOpinion { return o } -func (o *testOpinion) against(hid string, height uint64) *testOpinion { +func (o *testOpinion) against(height uint64) *testOpinion { id := types.BlockID{} - copy(id[:], hid) + copy(id[:], "a") o.pending.ag = append(o.pending.ag, types.Vote{ ID: id, Height: height, @@ -303,7 +303,7 @@ func TestStateDecodeVotes(t *testing.T) { "cancel support", []*testOpinion{ newTestOpinion(genesis).support("a", 100), - newTestOpinion(genesis).against("a", 100), + newTestOpinion(genesis).against(100), }, newTestOpinion(genesis).next(), "", @@ -324,7 +324,7 @@ func TestStateDecodeVotes(t *testing.T) { []*testOpinion{ newTestOpinion(genesis).support("a", 100), newTestOpinion(genesis).support("a", 101), - newTestOpinion(genesis).against("a", 100), + newTestOpinion(genesis).against(100), }, nil, "wrong target", @@ -332,7 +332,7 @@ func TestStateDecodeVotes(t *testing.T) { { "conflicting votes with against", []*testOpinion{ - newTestOpinion(genesis).against("a", 100).against("a", 200), + newTestOpinion(genesis).against(100).against(200), }, nil, "conflicting", @@ -348,7 +348,7 @@ func TestStateDecodeVotes(t *testing.T) { { "conflicting votes with against and support", []*testOpinion{ - newTestOpinion(genesis).against("a", 100).support("a", 200), + newTestOpinion(genesis).against(100).support("a", 200), }, nil, "conflicting", @@ -356,7 +356,7 @@ func TestStateDecodeVotes(t *testing.T) { { "conflicting abstain", []*testOpinion{ - newTestOpinion(genesis).against("a", 100).abstain(), + newTestOpinion(genesis).against(100).abstain(), }, nil, "conflict with abstain", @@ -370,7 +370,7 @@ func TestStateDecodeVotes(t *testing.T) { lid := base.layer.Add(1) encoded := opinion.encodedVotes() var rst votes - rst, _, err = decodeVotes(genesis.Sub(1), lid, base, encoded) + rst, _, err = decodeVotes(lid, base, encoded) if err != nil { break } diff --git a/tortoise/tortoise.go b/tortoise/tortoise.go index b51f052bda..bcadcc3247 100644 --- a/tortoise/tortoise.go +++ b/tortoise/tortoise.go @@ -273,7 +273,7 @@ func (t *turtle) encodeVotes( if explen := len(votes.Support) + len(votes.Against); explen > t.MaxExceptions { return nil, fmt.Errorf("too many exceptions (%v)", explen) } - decoded, _, err := decodeVotes(t.evicted, current, base, votes) + decoded, _, err := decodeVotes(current, base, votes) if err != nil { return nil, err } @@ -320,7 +320,7 @@ func (t *turtle) updateLast(last types.LayerID) { } } -func (t *turtle) tallyVotes(ctx context.Context, last types.LayerID) { +func (t *turtle) tallyVotes(last types.LayerID) { defer t.evict() t.logger.Debug("on layer", zap.Uint32("last", last.Uint32())) @@ -779,7 +779,7 @@ func (t *turtle) decodeBallot(ballot *types.BallotTortoiseData) (*ballotInfo, ty votes votes err error ) - votes, min, err = decodeVotes(t.evicted, binfo.layer, base, ballot.Opinion.Votes) + votes, min, err = decodeVotes(binfo.layer, base, ballot.Opinion.Votes) if err != nil { return nil, 0, err } diff --git a/tortoise/tortoise_test.go b/tortoise/tortoise_test.go index 9318731824..73dae65686 100644 --- a/tortoise/tortoise_test.go +++ b/tortoise/tortoise_test.go @@ -3200,13 +3200,13 @@ func TestUpdates(t *testing.T) { func TestDuplicateBallot(t *testing.T) { s := newSession(t) - s.smesher(0).atx(1, new(aopt).height(10).weight(2)) + s.smesher(0).atx(new(aopt).height(10).weight(2)) id := types.BallotID{1} - s.smesher(0).atx(1).rawballot(id, 1, new(bopt). + s.smesher(0).atx().rawballot(id, 1, new(bopt). totalEligibilities(s.epochEligibilities()). eligibilities(1), ) - s.smesher(0).atx(1).rawballot(id, 1, new(bopt). + s.smesher(0).atx().rawballot(id, 1, new(bopt). totalEligibilities(s.epochEligibilities()). eligibilities(1).assert( func(db *DecodedBallot, err error) { @@ -3228,12 +3228,12 @@ func TestSwitch(t *testing.T) { const smeshers = 4 elig := s.layerSize / smeshers for i := 0; i < smeshers; i++ { - s.smesher(i).atx(1, new(aopt).height(10).weight(100)) + s.smesher(i).atx(new(aopt).height(10).weight(100)) } - s.beacon(1, "a") + s.beacon() for i := 0; i < smeshers; i++ { - s.smesher(i).atx(1).ballot(1, new(bopt). - beacon("a"). + s.smesher(i).atx().ballot(1, new(bopt). + beacon(). totalEligibilities(s.epochEligibilities()). eligibilities(elig)) } @@ -3241,20 +3241,20 @@ func TestSwitch(t *testing.T) { for lid := 2; lid <= s.hdist; lid++ { for i := 0; i < smeshers; i++ { votes := new(evotes). - base(s.smesher(i).atx(1).ballot(lid-1)). - support(lid-1, strconv.Itoa(lid-1), 0) - s.smesher(i).atx(1).ballot(lid, + base(s.smesher(i).atx().ballot(lid-1)). + support(lid-1, strconv.Itoa(lid-1)) + s.smesher(i).atx().ballot(lid, new(bopt).eligibilities(elig).votes(votes), ) } } nonverified := new(results).verified(0) for lid := 2; lid <= s.hdist; lid++ { - nonverified = nonverified.next(lid-1).block(strconv.Itoa(lid-1), 0, 0) + nonverified = nonverified.next(lid-1).block(strconv.Itoa(lid-1), 0) } verified := new(results) for lid := 2; lid <= s.hdist; lid++ { - verified = verified.verified(lid-1).block(strconv.Itoa(lid-1), 0, valid|local) + verified = verified.verified(lid-1).block(strconv.Itoa(lid-1), valid|local) } verified.next(s.hdist) s.tallyWait(s.hdist - 1) @@ -3273,12 +3273,12 @@ func TestOnMalfeasance(t *testing.T) { const smeshers = 3 elig := s.layerSize / smeshers for i := 0; i < smeshers; i++ { - s.smesher(i).atx(1, new(aopt).height(10).weight(100)) + s.smesher(i).atx(new(aopt).height(10).weight(100)) } - s.beacon(1, "a") + s.beacon() for i := 0; i < smeshers; i++ { - s.smesher(i).atx(1).ballot(1, new(bopt). - beacon("a"). + s.smesher(i).atx().ballot(1, new(bopt). + beacon(). totalEligibilities(s.epochEligibilities()). eligibilities(elig)) } @@ -3299,30 +3299,30 @@ func TestOnMalfeasance(t *testing.T) { const smeshers = 3 elig := s.layerSize / smeshers for i := 0; i < smeshers; i++ { - s.smesher(i).atx(1, new(aopt).height(10).weight(100)) + s.smesher(i).atx(new(aopt).height(10).weight(100)) } - s.beacon(1, "a") + s.beacon() for i := 0; i < smeshers; i++ { - s.smesher(i).atx(1).ballot(1, new(bopt). - beacon("a"). + s.smesher(i).atx().ballot(1, new(bopt). + beacon(). totalEligibilities(s.epochEligibilities()). eligibilities(elig)) } for i := 0; i < smeshers; i++ { - s.smesher(i).atx(1).ballot(2, new(bopt). + s.smesher(i).atx().ballot(2, new(bopt). votes(new(evotes). - base(s.smesher(i).atx(1).ballot(1)). - support(1, "a", 0)). + base(s.smesher(i).atx().ballot(1)). + support(1, "a")). eligibilities(elig)) } s.smesher(0).malfeasant() // without this call tally will be skewed by following ballots for i := 0; i < 10; i++ { - s.smesher(0).atx(1). + s.smesher(0).atx(). rawballot(types.BallotID{'e', byte(i)}, 2, new(bopt).eligibilities(elig)) } s.tally(2) - s.updates(t, new(results).verified(0).verified(1).block("a", 0, valid|local).next(2)) + s.updates(t, new(results).verified(0).verified(1).block("a", valid|local).next(2)) s.runInorder() }) } @@ -3330,17 +3330,17 @@ func TestOnMalfeasance(t *testing.T) { func TestBaseAbstain(t *testing.T) { s := newSession(t) - s.smesher(0).atx(1, new(aopt).height(10).weight(100)) + s.smesher(0).atx(new(aopt).height(10).weight(100)) - s.beacon(1, "a") - s.smesher(0).atx(1).ballot(1, new(bopt). - beacon("a"). + s.beacon() + s.smesher(0).atx().ballot(1, new(bopt). + beacon(). totalEligibilities(s.epochEligibilities()). eligibilities(s.layerSize)) - s.smesher(0).atx(1).ballot(2, new(bopt). + s.smesher(0).atx().ballot(2, new(bopt). eligibilities(s.layerSize). votes(new(evotes). - base(s.smesher(0).atx(1).ballot(1)). + base(s.smesher(0).atx().ballot(1)). abstain(1), )) s.block(1, "aa", 0) @@ -3350,7 +3350,7 @@ func TestBaseAbstain(t *testing.T) { s.runOn(trt) op, err := trt.EncodeVotes(context.Background()) require.NoError(t, err) - base := s.smesher(0).atx(1).ballot(2) + base := s.smesher(0).atx().ballot(2) require.Equal(t, op.Base, base.ID) require.Equal(t, []types.LayerID{base.Layer}, op.Abstain) require.Empty(t, op.Support) diff --git a/txs/cache.go b/txs/cache.go index 6741b96247..5281b21101 100644 --- a/txs/cache.go +++ b/txs/cache.go @@ -94,7 +94,7 @@ func (ac *accountCache) availBalance() uint64 { return ac.txsByNonce.Back().Value.(*candidate).postBalance } -func (ac *accountCache) precheck(logger *zap.Logger, ntx *NanoTX) (*list.Element, *candidate, error) { +func (ac *accountCache) precheck(ntx *NanoTX) (*list.Element, *candidate, error) { if ac.txsByNonce.Len() >= maxTXsPerAcct { ac.moreInDB = true return nil, nil, fmt.Errorf("%w: len %d", errTooManyNonce, ac.txsByNonce.Len()) @@ -127,7 +127,7 @@ func (ac *accountCache) accept(logger *zap.Logger, ntx *NanoTX, blockSeed []byte replaced *NanoTX err error ) - prev, cand, err = ac.precheck(logger, ntx) + prev, cand, err = ac.precheck(ntx) if err != nil { return err } diff --git a/txs/cache_test.go b/txs/cache_test.go index 352ba5d466..e117984f0b 100644 --- a/txs/cache_test.go +++ b/txs/cache_test.go @@ -17,6 +17,8 @@ import ( "github.com/spacemeshos/go-spacemesh/sql/transactions" ) +var lid = types.LayerID(97) + type testCache struct { *Cache db *sql.Database @@ -28,7 +30,7 @@ type testAcct struct { nonce, balance uint64 } -func makeResults(lid types.LayerID, bid types.BlockID, txs ...types.Transaction) []types.TransactionWithResult { +func makeResults(bid types.BlockID, txs ...types.Transaction) []types.TransactionWithResult { var results []types.TransactionWithResult for _, tx := range txs { results = append(results, types.TransactionWithResult{ @@ -319,7 +321,7 @@ func TestCache_Account_HappyFlow(t *testing.T) { ta.balance -= mtx.Spending() } ta.balance += income - applied := makeResults(lid, bid, mtxs[0].Transaction, mtxs[1].Transaction) + applied := makeResults(bid, mtxs[0].Transaction, mtxs[1].Transaction) require.NoError(t, tc.ApplyLayer(context.Background(), tc.db, lid, bid, applied, []types.Transaction{})) for _, mtx := range mtxs[:2] { @@ -392,7 +394,7 @@ func TestCache_Account_TXInMultipleLayers(t *testing.T) { income := defaultAmount * 100 ta.nonce++ ta.balance = ta.balance - mtxs[0].Spending() + income - applied := makeResults(lid, bid0, mtxs[0].Transaction) + applied := makeResults(bid0, mtxs[0].Transaction) require.NoError(t, tc.ApplyLayer(context.Background(), tc.db, lid, bid0, applied, []types.Transaction{})) checkNoTX(t, tc.Cache, mtxs[0].ID) checkTX(t, tc.Cache, mtxs[1].ID, lid.Add(1), types.EmptyBlockID) @@ -858,7 +860,7 @@ func TestCache_Account_AppliedTXsNotInCache(t *testing.T) { require.NoError(t, layers.SetApplied(tc.db, lid.Sub(1), types.RandomBlockID())) bid := types.BlockID{1, 2, 3} - applied := makeResults(lid, bid, mtxs[0].Transaction, mtxs[1].Transaction, mtxs[2].Transaction) + applied := makeResults(bid, mtxs[0].Transaction, mtxs[1].Transaction, mtxs[2].Transaction) // now the rest of the txs are fetched as part of a block saveTXs(t, tc.db, mtxs[1:]) ta.nonce = newNextNonce + 2 @@ -883,7 +885,7 @@ func TestCache_Account_TooManyNonceAfterApply(t *testing.T) { lid := types.LayerID(97) require.NoError(t, layers.SetApplied(tc.db, lid.Sub(1), types.RandomBlockID())) bid := types.BlockID{1, 2, 3} - applied := makeResults(lid, bid, mtxs[0].Transaction) + applied := makeResults(bid, mtxs[0].Transaction) // more txs arrived saveTXs(t, tc.db, mtxs[1:]) require.NoError(t, tc.ApplyLayer(context.Background(), tc.db, lid, bid, applied, []types.Transaction{})) @@ -933,7 +935,7 @@ func TestCache_Account_BalanceRelaxedAfterApply(t *testing.T) { lid := types.LayerID(97) require.NoError(t, layers.SetApplied(tc.db, lid.Sub(1), types.RandomBlockID())) bid := types.BlockID{1, 2, 3} - applied := makeResults(lid, bid, mtx.Transaction) + applied := makeResults(bid, mtx.Transaction) require.NoError(t, tc.ApplyLayer(context.Background(), tc.db, lid, bid, applied, []types.Transaction{})) // all pending txs are added to cache now newNextNonce = ta.nonce @@ -971,7 +973,7 @@ func TestCache_Account_BalanceRelaxedAfterApply_EvictLaterNonce(t *testing.T) { lid := types.LayerID(97) require.NoError(t, layers.SetApplied(tc.db, lid.Sub(1), types.RandomBlockID())) bid := types.BlockID{1, 2, 3} - applied := makeResults(lid, bid, mtxs[0].Transaction) + applied := makeResults(bid, mtxs[0].Transaction) require.NoError(t, tc.ApplyLayer(context.Background(), tc.db, lid, bid, applied, []types.Transaction{})) expectedMempool = map[types.Address][]*types.MeshTransaction{ta.principal: mtxs[1:]} checkMempool(t, tc.Cache, expectedMempool) @@ -993,7 +995,7 @@ func TestCache_Account_EvictedAfterApply(t *testing.T) { lid := types.LayerID(97) require.NoError(t, layers.SetApplied(tc.db, lid.Sub(1), types.RandomBlockID())) bid := types.BlockID{1, 2, 3} - applied := makeResults(lid, bid, mtx.Transaction) + applied := makeResults(bid, mtx.Transaction) require.NoError(t, tc.ApplyLayer(context.Background(), tc.db, lid, bid, applied, []types.Transaction{})) checkProjection(t, tc.Cache, ta.principal, newNextNonce, newBalance) checkMempool(t, tc.Cache, nil) @@ -1015,7 +1017,7 @@ func TestCache_Account_NotEvictedAfterApplyDueToNonceGap(t *testing.T) { lid := types.LayerID(97) require.NoError(t, layers.SetApplied(tc.db, lid.Sub(1), types.RandomBlockID())) bid := types.BlockID{1, 2, 3} - applied := makeResults(lid, bid, mtx.Transaction) + applied := makeResults(bid, mtx.Transaction) pendingInsufficient := &types.MeshTransaction{ Transaction: *newTx(t, ta.nonce, ta.balance, defaultFee, ta.signer), Received: time.Now(), @@ -1075,9 +1077,9 @@ func buildSmallCache( t *testing.T, tc *testCache, accounts map[types.Address]*testAcct, - maxTX uint64, ) map[types.Address][]*types.MeshTransaction { t.Helper() + maxTX := uint64(10) mtxsByAccount := make(map[types.Address][]*types.MeshTransaction) for principal, ta := range accounts { numTXs := rand.Uint64() % maxTX @@ -1109,7 +1111,7 @@ func checkMempoolSize(t *testing.T, c *Cache, expected int) { func TestCache_LinkTXsWithProposal(t *testing.T) { tc, accounts := createCache(t, 100) - mtxsByAccount := buildSmallCache(t, tc, accounts, 10) + mtxsByAccount := buildSmallCache(t, tc, accounts) lid0 := types.LayerID(97) pid0 := types.ProposalID{1, 2, 3} // take the first tx out of each account for proposal 0 @@ -1149,7 +1151,7 @@ func TestCache_LinkTXsWithProposal(t *testing.T) { func TestCache_LinkTXsWithProposal_MultipleLayers(t *testing.T) { tc, accounts := createCache(t, 100) - mtxsByAccount := buildSmallCache(t, tc, accounts, 10) + mtxsByAccount := buildSmallCache(t, tc, accounts) lid0 := types.LayerID(97) pid0 := types.ProposalID{1, 2, 3} // take the first tx out of each account for proposal 0 @@ -1179,7 +1181,7 @@ func TestCache_LinkTXsWithProposal_MultipleLayers(t *testing.T) { func TestCache_LinkTXsWithBlock(t *testing.T) { tc, accounts := createCache(t, 100) - mtxsByAccount := buildSmallCache(t, tc, accounts, 10) + mtxsByAccount := buildSmallCache(t, tc, accounts) lid0 := types.LayerID(97) bid0 := types.BlockID{1, 2, 3} // take the first tx out of each account for block 0 @@ -1218,7 +1220,7 @@ func TestCache_LinkTXsWithBlock(t *testing.T) { func TestCache_LinkTXsWithBlock_MultipleLayers(t *testing.T) { tc, accounts := createCache(t, 100) - mtxsByAccount := buildSmallCache(t, tc, accounts, 10) + mtxsByAccount := buildSmallCache(t, tc, accounts) lid0 := types.LayerID(97) bid0 := types.BlockID{1, 2, 3} // take the first tx out of each account for block 0 @@ -1248,7 +1250,7 @@ func TestCache_LinkTXsWithBlock_MultipleLayers(t *testing.T) { func TestCache_ApplyLayerAndRevert(t *testing.T) { tc, accounts := createCache(t, 100) - mtxsByAccount := buildSmallCache(t, tc, accounts, 10) + mtxsByAccount := buildSmallCache(t, tc, accounts) lid := types.LayerID(97) require.NoError(t, layers.SetApplied(tc.db, lid.Sub(1), types.RandomBlockID())) bid := types.BlockID{1, 2, 3} @@ -1259,11 +1261,11 @@ func TestCache_ApplyLayerAndRevert(t *testing.T) { lastNonce := mtxs[0].Nonce newBalance := accounts[principal].balance newBalance -= mtxs[0].Spending() - applied := makeResults(lid, bid, mtxs[0].Transaction) + applied := makeResults(bid, mtxs[0].Transaction) appliedMTXs = append(appliedMTXs, mtxs[0]) if len(mtxs) >= 2 { - applied = append(applied, makeResults(lid, bid, mtxs[1].Transaction)...) + applied = append(applied, makeResults(bid, mtxs[1].Transaction)...) appliedMTXs = append(appliedMTXs, mtxs[1]) lastNonce = mtxs[1].Nonce newBalance -= mtxs[1].Spending() @@ -1300,8 +1302,7 @@ func TestCache_ApplyLayerAndRevert(t *testing.T) { func TestCache_ApplyLayerWithSkippedTXs(t *testing.T) { tc, accounts := createCache(t, 100) - mtxsByAccount := buildSmallCache(t, tc, accounts, 10) - lid := types.LayerID(97) + mtxsByAccount := buildSmallCache(t, tc, accounts) require.NoError(t, layers.SetApplied(tc.db, lid.Sub(1), types.RandomBlockID())) bid := types.BlockID{1, 2, 3} var allSkipped []types.Transaction @@ -1321,7 +1322,7 @@ func TestCache_ApplyLayerWithSkippedTXs(t *testing.T) { // effectively make all pending txs invalid accounts[principal].nonce = mtxs[0].Nonce + uint64(len(mtxs)) } else { - applied := makeResults(lid, bid, mtxs[0].Transaction) + applied := makeResults(bid, mtxs[0].Transaction) allApplied = append(allApplied, applied...) allPendingMTXs = append(allPendingMTXs, mtxs[1:]...) appliedMTXs = append(appliedMTXs, mtxs[0]) @@ -1353,7 +1354,7 @@ func TestCache_ApplyLayerWithSkippedTXs(t *testing.T) { func TestCache_ApplyLayer_OutOfOrder(t *testing.T) { tc, accounts := createCache(t, 100) - buildSmallCache(t, tc, accounts, 10) + buildSmallCache(t, tc, accounts) lid := types.LayerID(97) require.NoError(t, layers.SetApplied(tc.db, lid.Sub(2), types.RandomBlockID())) err := tc.ApplyLayer(context.Background(), tc.db, lid, types.BlockID{1, 2, 3}, nil, []types.Transaction{}) @@ -1362,7 +1363,7 @@ func TestCache_ApplyLayer_OutOfOrder(t *testing.T) { func TestCache_GetMempool(t *testing.T) { tc, accounts := createCache(t, 100) - mtxsByAccount := buildSmallCache(t, tc, accounts, 10) + mtxsByAccount := buildSmallCache(t, tc, accounts) lid0 := types.LayerID(97) bid := types.BlockID{1, 2, 3} tids0 := make([]types.TransactionID, 0, len(mtxsByAccount)) @@ -1398,7 +1399,7 @@ func TestCache_GetMempool(t *testing.T) { func TestCache_GetProjection(t *testing.T) { tc, accounts := createCache(t, 100) - mtxsByAccount := buildSmallCache(t, tc, accounts, 10) + mtxsByAccount := buildSmallCache(t, tc, accounts) for principal, mtxs := range mtxsByAccount { expectedNonce := accounts[principal].nonce + uint64(len(mtxs)) expectedBalance := accounts[principal].balance