-
Notifications
You must be signed in to change notification settings - Fork 268
Expand file tree
/
Copy pathexecutor_logic_test.go
More file actions
329 lines (281 loc) · 10.6 KB
/
Copy pathexecutor_logic_test.go
File metadata and controls
329 lines (281 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package executing
import (
"context"
crand "crypto/rand"
"errors"
"testing"
"time"
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/sync"
"github.com/libp2p/go-libp2p/core/crypto"
"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/evstack/ev-node/block/internal/cache"
"github.com/evstack/ev-node/block/internal/common"
coreseq "github.com/evstack/ev-node/core/sequencer"
"github.com/evstack/ev-node/pkg/config"
"github.com/evstack/ev-node/pkg/genesis"
pkgsigner "github.com/evstack/ev-node/pkg/signer"
"github.com/evstack/ev-node/pkg/signer/noop"
"github.com/evstack/ev-node/pkg/store"
testmocks "github.com/evstack/ev-node/test/mocks"
"github.com/evstack/ev-node/types"
"github.com/stretchr/testify/mock"
)
// buildTestSigner returns a signer and its address for use in tests
func buildTestSigner(t *testing.T) (signerAddr []byte, tSigner types.Signer, s pkgsigner.Signer) {
t.Helper()
priv, _, err := crypto.GenerateEd25519Key(crand.Reader)
require.NoError(t, err)
n, err := noop.NewNoopSigner(priv)
require.NoError(t, err)
addr, err := n.GetAddress()
require.NoError(t, err)
pub, err := n.GetPublic()
require.NoError(t, err)
return addr, types.Signer{PubKey: pub, Address: addr}, n
}
func TestProduceBlock_EmptyBatch_SetsEmptyDataHash(t *testing.T) {
ds := sync.MutexWrap(datastore.NewMapDatastore())
memStore := store.New(ds)
cacheManager, err := cache.NewManager(config.DefaultConfig(), memStore, zerolog.Nop())
require.NoError(t, err)
metrics := common.NopMetrics()
// signer and genesis with correct proposer
addr, _, signerWrapper := buildTestSigner(t)
cfg := config.DefaultConfig()
cfg.Node.BlockTime = config.DurationWrapper{Duration: 10 * time.Millisecond}
cfg.Node.MaxPendingHeadersAndData = 1000
gen := genesis.Genesis{
ChainID: "test-chain",
InitialHeight: 1,
StartTime: time.Now().Add(-time.Second),
ProposerAddress: addr,
}
// Use mocks for executor and sequencer
mockExec := testmocks.NewMockExecutor(t)
mockSeq := testmocks.NewMockSequencer(t)
// Broadcasters are required by produceBlock; use generated mocks
hb := common.NewMockBroadcaster[*types.P2PSignedHeader](t)
hb.EXPECT().WriteToStoreAndBroadcast(mock.Anything, mock.Anything).Return(nil).Maybe()
db := common.NewMockBroadcaster[*types.P2PData](t)
db.EXPECT().WriteToStoreAndBroadcast(mock.Anything, mock.Anything).Return(nil).Maybe()
exec, err := NewExecutor(
memStore,
mockExec,
mockSeq,
signerWrapper,
cacheManager,
metrics,
cfg,
gen,
hb,
db,
zerolog.Nop(),
common.DefaultBlockOptions(),
make(chan error, 1),
nil,
)
require.NoError(t, err)
// Expect InitChain to be called
initStateRoot := []byte("init_root")
mockExec.EXPECT().InitChain(mock.Anything, mock.AnythingOfType("time.Time"), gen.InitialHeight, gen.ChainID).
Return(initStateRoot, nil).Once()
mockSeq.EXPECT().SetDAHeight(uint64(0)).Return().Once()
// initialize state (creates genesis block in store and sets state)
require.NoError(t, exec.initializeState())
// Set up context for the executor (normally done in Start method)
exec.ctx, exec.cancel = context.WithCancel(context.Background())
defer exec.cancel()
// sequencer returns empty batch
mockSeq.EXPECT().GetNextBatch(mock.Anything, mock.AnythingOfType("sequencer.GetNextBatchRequest")).
RunAndReturn(func(ctx context.Context, req coreseq.GetNextBatchRequest) (*coreseq.GetNextBatchResponse, error) {
return &coreseq.GetNextBatchResponse{Batch: &coreseq.Batch{Transactions: nil}, Timestamp: time.Now()}, nil
}).Once()
// executor ExecuteTxs called with empty txs and previous state root
mockExec.EXPECT().ExecuteTxs(mock.Anything, mock.Anything, uint64(1), mock.AnythingOfType("time.Time"), initStateRoot).
Return([]byte("new_root"), nil).Once()
mockSeq.EXPECT().GetDAHeight().Return(uint64(0)).Once()
// produce one block
err = exec.ProduceBlock(exec.ctx)
require.NoError(t, err)
// Verify height and stored block
h, err := memStore.Height(context.Background())
require.NoError(t, err)
assert.Equal(t, uint64(1), h)
sh, data, err := memStore.GetBlockData(context.Background(), 1)
require.NoError(t, err)
// Expect empty txs and special empty data hash marker
assert.Equal(t, 0, len(data.Txs))
assert.EqualValues(t, common.DataHashForEmptyTxs, sh.DataHash)
// Broadcasters should have been called with the produced header and data
// The testify mock framework tracks calls automatically
}
func TestPendingLimit_SkipsProduction(t *testing.T) {
ds := sync.MutexWrap(datastore.NewMapDatastore())
memStore := store.New(ds)
cacheManager, err := cache.NewManager(config.DefaultConfig(), memStore, zerolog.Nop())
require.NoError(t, err)
metrics := common.NopMetrics()
addr, _, signerWrapper := buildTestSigner(t)
cfg := config.DefaultConfig()
cfg.Node.BlockTime = config.DurationWrapper{Duration: 10 * time.Millisecond}
cfg.Node.MaxPendingHeadersAndData = 1 // low limit to trigger skip quickly
gen := genesis.Genesis{
ChainID: "test-chain",
InitialHeight: 1,
StartTime: time.Now().Add(-time.Second),
ProposerAddress: addr,
}
mockExec := testmocks.NewMockExecutor(t)
mockSeq := testmocks.NewMockSequencer(t)
hb := common.NewMockBroadcaster[*types.P2PSignedHeader](t)
hb.EXPECT().WriteToStoreAndBroadcast(mock.Anything, mock.Anything).Return(nil).Maybe()
db := common.NewMockBroadcaster[*types.P2PData](t)
db.EXPECT().WriteToStoreAndBroadcast(mock.Anything, mock.Anything).Return(nil).Maybe()
exec, err := NewExecutor(
memStore,
mockExec,
mockSeq,
signerWrapper,
cacheManager,
metrics,
cfg,
gen,
hb,
db,
zerolog.Nop(),
common.DefaultBlockOptions(),
make(chan error, 1),
nil,
)
require.NoError(t, err)
mockExec.EXPECT().InitChain(mock.Anything, mock.AnythingOfType("time.Time"), gen.InitialHeight, gen.ChainID).
Return([]byte("i0"), nil).Once()
mockSeq.EXPECT().SetDAHeight(uint64(0)).Return().Once()
require.NoError(t, exec.initializeState())
// Set up context for the executor (normally done in Start method)
exec.ctx, exec.cancel = context.WithCancel(context.Background())
defer exec.cancel()
// First production should succeed
// Return empty batch again
mockSeq.EXPECT().GetNextBatch(mock.Anything, mock.AnythingOfType("sequencer.GetNextBatchRequest")).
RunAndReturn(func(ctx context.Context, req coreseq.GetNextBatchRequest) (*coreseq.GetNextBatchResponse, error) {
return &coreseq.GetNextBatchResponse{Batch: &coreseq.Batch{Transactions: nil}, Timestamp: time.Now()}, nil
}).Once()
// ExecuteTxs with empty
mockExec.EXPECT().ExecuteTxs(mock.Anything, mock.Anything, uint64(1), mock.AnythingOfType("time.Time"), []byte("i0")).
Return([]byte("i1"), nil).Once()
mockSeq.EXPECT().GetDAHeight().Return(uint64(0)).Once()
require.NoError(t, exec.ProduceBlock(exec.ctx))
h1, err := memStore.Height(context.Background())
require.NoError(t, err)
assert.Equal(t, uint64(1), h1)
// With limit=1 and lastSubmitted default 0, pending >= 1 so next production should be skipped
// No new expectations; ProduceBlock should return early before hitting sequencer
require.NoError(t, exec.ProduceBlock(exec.ctx))
h2, err := memStore.Height(context.Background())
require.NoError(t, err)
assert.Equal(t, h1, h2, "height should not change when production is skipped")
}
func TestExecutor_executeTxsWithRetry(t *testing.T) {
t.Parallel()
tests := []struct {
name string
setupMock func(*testmocks.MockExecutor)
expectSuccess bool
expectHash []byte
expectError string
}{
{
name: "success on first attempt",
setupMock: func(exec *testmocks.MockExecutor) {
exec.On("ExecuteTxs", mock.Anything, mock.Anything, uint64(100), mock.Anything, mock.Anything).
Return([]byte("new-hash"), nil).Once()
},
expectSuccess: true,
expectHash: []byte("new-hash"),
},
{
name: "success on second attempt",
setupMock: func(exec *testmocks.MockExecutor) {
exec.On("ExecuteTxs", mock.Anything, mock.Anything, uint64(100), mock.Anything, mock.Anything).
Return([]byte(nil), errors.New("temporary failure")).Once()
exec.On("ExecuteTxs", mock.Anything, mock.Anything, uint64(100), mock.Anything, mock.Anything).
Return([]byte("new-hash"), nil).Once()
},
expectSuccess: true,
expectHash: []byte("new-hash"),
},
{
name: "success on third attempt",
setupMock: func(exec *testmocks.MockExecutor) {
exec.On("ExecuteTxs", mock.Anything, mock.Anything, uint64(100), mock.Anything, mock.Anything).
Return([]byte(nil), errors.New("temporary failure")).Times(2)
exec.On("ExecuteTxs", mock.Anything, mock.Anything, uint64(100), mock.Anything, mock.Anything).
Return([]byte("new-hash"), nil).Once()
},
expectSuccess: true,
expectHash: []byte("new-hash"),
},
{
name: "failure after max retries",
setupMock: func(exec *testmocks.MockExecutor) {
exec.On("ExecuteTxs", mock.Anything, mock.Anything, uint64(100), mock.Anything, mock.Anything).
Return([]byte(nil), errors.New("persistent failure")).Times(common.MaxRetriesBeforeHalt)
},
expectSuccess: false,
expectError: "failed to execute transactions",
},
{
name: "context cancelled during retry",
setupMock: func(exec *testmocks.MockExecutor) {
exec.On("ExecuteTxs", mock.Anything, mock.Anything, uint64(100), mock.Anything, mock.Anything).
Return([]byte(nil), errors.New("temporary failure")).Once()
},
expectSuccess: false,
expectError: "context cancelled during retry",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
ctx := context.Background()
execCtx := ctx
// For context cancellation test, create a cancellable context
if tt.name == "context cancelled during retry" {
var cancel context.CancelFunc
execCtx, cancel = context.WithCancel(ctx)
// Cancel context after first failure to simulate cancellation during retry
go func() {
time.Sleep(100 * time.Millisecond)
cancel()
}()
}
mockExec := testmocks.NewMockExecutor(t)
tt.setupMock(mockExec)
e := &Executor{
exec: mockExec,
ctx: execCtx,
logger: zerolog.Nop(),
}
rawTxs := [][]byte{[]byte("tx1"), []byte("tx2")}
header := types.Header{
BaseHeader: types.BaseHeader{Height: 100, Time: uint64(time.Now().UnixNano())},
}
currentState := types.State{AppHash: []byte("current-hash")}
result, err := e.executeTxsWithRetry(ctx, rawTxs, header, currentState)
if tt.expectSuccess {
require.NoError(t, err)
assert.Equal(t, tt.expectHash, result)
} else {
require.Error(t, err)
if tt.expectError != "" {
assert.Contains(t, err.Error(), tt.expectError)
}
}
mockExec.AssertExpectations(t)
})
}
}