-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathabci_test.go
801 lines (701 loc) · 22.4 KB
/
abci_test.go
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
package cometbft
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"io"
"strings"
"sync"
"testing"
"time"
"cosmossdk.io/server/v2/cometbft/oe"
abciproto "github.com/cometbft/cometbft/api/cometbft/abci/v1"
v1 "github.com/cometbft/cometbft/api/cometbft/types/v1"
"github.com/cosmos/gogoproto/proto"
gogotypes "github.com/cosmos/gogoproto/types"
"github.com/stretchr/testify/require"
appmodulev2 "cosmossdk.io/core/appmodule/v2"
"cosmossdk.io/core/store"
"cosmossdk.io/core/transaction"
"cosmossdk.io/log"
"cosmossdk.io/server/v2/appmanager"
"cosmossdk.io/server/v2/cometbft/handlers"
cometmock "cosmossdk.io/server/v2/cometbft/internal/mock"
"cosmossdk.io/server/v2/cometbft/mempool"
"cosmossdk.io/server/v2/cometbft/types"
"cosmossdk.io/server/v2/stf"
"cosmossdk.io/server/v2/stf/branch"
"cosmossdk.io/server/v2/stf/mock"
consensustypes "cosmossdk.io/x/consensus/types"
)
var (
sum = sha256.Sum256([]byte("test-hash"))
emptyHash = sha256.Sum256([]byte(""))
DefaulConsensusParams = &v1.ConsensusParams{
Block: &v1.BlockParams{
MaxGas: 5000000,
},
}
mockTx = mock.Tx{
Sender: []byte("sender"),
Msg: &gogotypes.BoolValue{Value: true},
GasLimit: 100_000,
}
invalidMockTx = mock.Tx{
Sender: []byte("sender"),
Msg: &gogotypes.BoolValue{Value: true},
GasLimit: 0,
}
actorName = []byte("cookies")
)
func getQueryRouterBuilder[T any, PT interface {
*T
proto.Message
},
U any, UT interface {
*U
proto.Message
}](
t *testing.T,
handler func(ctx context.Context, msg PT) (UT, error),
) *stf.MsgRouterBuilder {
t.Helper()
queryRouterBuilder := stf.NewMsgRouterBuilder()
err := queryRouterBuilder.RegisterHandler(
proto.MessageName(PT(new(T))),
func(ctx context.Context, msg transaction.Msg) (msgResp transaction.Msg, err error) {
typedReq := msg.(PT)
typedResp, err := handler(ctx, typedReq)
if err != nil {
return nil, err
}
return typedResp, nil
},
)
require.NoError(t, err)
return queryRouterBuilder
}
func getMsgRouterBuilder[T any, PT interface {
*T
transaction.Msg
},
U any, UT interface {
*U
transaction.Msg
}](
t *testing.T,
handler func(ctx context.Context, msg PT) (UT, error),
) *stf.MsgRouterBuilder {
t.Helper()
msgRouterBuilder := stf.NewMsgRouterBuilder()
err := msgRouterBuilder.RegisterHandler(
proto.MessageName(PT(new(T))),
func(ctx context.Context, msg transaction.Msg) (msgResp transaction.Msg, err error) {
typedReq := msg.(PT)
typedResp, err := handler(ctx, typedReq)
if err != nil {
return nil, err
}
return typedResp, nil
},
)
require.NoError(t, err)
return msgRouterBuilder
}
func TestConsensus_InitChain_Without_UpdateParam(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
mockStore := c.store
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
assertStoreLatestVersion(t, mockStore, 0)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Hash: emptyHash[:],
})
require.NoError(t, err)
assertStoreLatestVersion(t, mockStore, 1)
}
func TestConsensus_InitChain_With_UpdateParam(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
mockStore := c.store
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
ConsensusParams: DefaulConsensusParams,
InitialHeight: 1,
})
require.NoError(t, err)
assertStoreLatestVersion(t, mockStore, 0)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Hash: emptyHash[:],
})
require.NoError(t, err)
assertStoreLatestVersion(t, mockStore, 1)
}
func TestConsensus_InitChain_Invalid_Height(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
mockStore := c.store
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 2,
})
require.NoError(t, err)
assertStoreLatestVersion(t, mockStore, 1)
// Shouldn't be able to commit genesis block 3
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 3,
Hash: emptyHash[:],
})
require.Error(t, err)
require.True(t, strings.Contains(err.Error(), "invalid height"))
}
func TestConsensus_FinalizeBlock_Invalid_Height(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Hash: emptyHash[:],
})
require.NoError(t, err)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 3,
Hash: emptyHash[:],
})
require.Error(t, err)
}
func TestConsensus_FinalizeBlock_NoTxs(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
mockStore := c.store
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Hash: emptyHash[:],
})
require.NoError(t, err)
endBlock := 10
for i := 2; i <= endBlock; i++ {
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: int64(i),
Hash: sum[:],
})
require.NoError(t, err)
assertStoreLatestVersion(t, mockStore, uint64(i))
}
require.Equal(t, int64(endBlock), c.lastCommittedHeight.Load())
}
func TestConsensus_FinalizeBlock_MultiTxs_OutOfGas(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Hash: emptyHash[:],
})
require.NoError(t, err)
endBlock := 10
for i := 2; i <= endBlock; i++ {
res, err := c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: int64(i),
Hash: sum[:],
Txs: [][]byte{invalidMockTx.Bytes(), mockTx.Bytes()},
})
require.NoError(t, err)
require.NotEqual(t, res.TxResults[0].Code, 0)
}
require.Equal(t, int64(endBlock), c.lastCommittedHeight.Load())
}
func TestConsensus_FinalizeBlock_MultiTxs(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
mockStore := c.store
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Hash: emptyHash[:],
})
require.NoError(t, err)
endBlock := 10
for i := 2; i <= endBlock; i++ {
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: int64(i),
Hash: sum[:],
Txs: [][]byte{mockTx.Bytes(), mockTx.Bytes()},
})
require.NoError(t, err)
assertStoreLatestVersion(t, mockStore, uint64(i))
}
require.Equal(t, int64(endBlock), c.lastCommittedHeight.Load())
}
func TestConsensus_CheckTx(t *testing.T) {
c := setUpConsensus(t, 0, mempool.NoOpMempool[mock.Tx]{})
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
// empty byte
_, err = c.CheckTx(context.Background(), &abciproto.CheckTxRequest{
Tx: []byte{},
})
require.Error(t, err)
// out of gas
res, err := c.CheckTx(context.Background(), &abciproto.CheckTxRequest{
Tx: mock.Tx{
Sender: []byte("sender"),
Msg: &gogotypes.BoolValue{Value: true},
GasLimit: 100_000,
}.Bytes(),
})
require.NoError(t, err)
require.NotEqual(t, res.Code, 0)
c = setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
res, err = c.CheckTx(context.Background(), &abciproto.CheckTxRequest{
Tx: mock.Tx{
Sender: []byte("sender"),
Msg: &gogotypes.BoolValue{Value: true},
GasLimit: 100_000,
}.Bytes(),
})
require.NoError(t, err)
require.NotEqual(t, res.GasUsed, 0)
}
func TestConsensus_ExtendVote(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
ConsensusParams: &v1.ConsensusParams{
Block: &v1.BlockParams{
MaxGas: 5000000,
},
Feature: &v1.FeatureParams{
VoteExtensionsEnableHeight: &gogotypes.Int64Value{Value: 2},
},
},
})
require.NoError(t, err)
// Votes not enabled yet
_, err = c.ExtendVote(context.Background(), &abciproto.ExtendVoteRequest{
Height: 1,
})
require.ErrorContains(t, err, "vote extensions are not enabled")
// Empty extendVote handler
_, err = c.ExtendVote(context.Background(), &abciproto.ExtendVoteRequest{
Height: 2,
})
require.ErrorContains(t, err, "no extend function was set")
// Use NoOp handler
c.extendVote = DefaultServerOptions[mock.Tx]().ExtendVoteHandler
res, err := c.ExtendVote(context.Background(), &abciproto.ExtendVoteRequest{
Height: 2,
})
require.NoError(t, err)
require.Equal(t, len(res.VoteExtension), 0)
}
func TestConsensus_VerifyVoteExtension(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
ConsensusParams: &v1.ConsensusParams{
Block: &v1.BlockParams{
MaxGas: 5000000,
},
Feature: &v1.FeatureParams{
VoteExtensionsEnableHeight: &gogotypes.Int64Value{Value: 2},
},
},
})
require.NoError(t, err)
// Votes not enabled yet
_, err = c.VerifyVoteExtension(context.Background(), &abciproto.VerifyVoteExtensionRequest{
Height: 1,
})
require.ErrorContains(t, err, "vote extensions are not enabled")
// Empty verifyVote handler
_, err = c.VerifyVoteExtension(context.Background(), &abciproto.VerifyVoteExtensionRequest{
Height: 2,
})
require.ErrorContains(t, err, "no verify function was set")
// Use NoOp handler
c.verifyVoteExt = DefaultServerOptions[mock.Tx]().VerifyVoteExtensionHandler
res, err := c.VerifyVoteExtension(context.Background(), &abciproto.VerifyVoteExtensionRequest{
Height: 2,
Hash: []byte("test"),
})
require.NoError(t, err)
require.Equal(t, res.Status, abciproto.VERIFY_VOTE_EXTENSION_STATUS_ACCEPT)
}
func TestConsensus_PrepareProposal(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
// Invalid height
_, err := c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 0,
})
require.Error(t, err)
// empty handler
_, err = c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 1,
})
require.Error(t, err)
// NoOp handler
c.prepareProposalHandler = DefaultServerOptions[mock.Tx]().PrepareProposalHandler
_, err = c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 1,
Txs: [][]byte{mockTx.Bytes()},
})
require.NoError(t, err)
}
func TestConsensus_PrepareProposal_With_Handler_NoOpMempool(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
c.prepareProposalHandler = handlers.NewDefaultProposalHandler(c.mempool).PrepareHandler()
// zero MaxTxBytes
res, err := c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 1,
MaxTxBytes: 0,
Txs: [][]byte{mockTx.Bytes()},
})
require.NoError(t, err)
require.Equal(t, len(res.Txs), 0)
// have tx exceed MaxTxBytes
// each mock tx has 128 bytes, should select 2 txs
res, err = c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 1,
MaxTxBytes: 300,
Txs: [][]byte{mockTx.Bytes(), mockTx.Bytes(), mockTx.Bytes()},
})
require.NoError(t, err)
require.Equal(t, len(res.Txs), 2)
// reach MaxTxBytes
res, err = c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 1,
MaxTxBytes: 256,
Txs: [][]byte{mockTx.Bytes(), mockTx.Bytes()},
})
require.NoError(t, err)
require.Equal(t, len(res.Txs), 2)
// Over gas, under MaxTxBytes
// 300_000 gas limit, should only take 3 txs
res, err = c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 1,
MaxTxBytes: 1000,
Txs: [][]byte{mockTx.Bytes(), mockTx.Bytes(), mockTx.Bytes(), mockTx.Bytes()},
})
require.NoError(t, err)
require.Equal(t, len(res.Txs), 3)
// Reach max gas
res, err = c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 1,
MaxTxBytes: 1000,
Txs: [][]byte{mockTx.Bytes(), mockTx.Bytes(), mockTx.Bytes()},
})
require.NoError(t, err)
require.Equal(t, len(res.Txs), 3)
// have a bad encoding tx
res, err = c.PrepareProposal(context.Background(), &abciproto.PrepareProposalRequest{
Height: 1,
MaxTxBytes: 1000,
Txs: [][]byte{mockTx.Bytes(), append(mockTx.Bytes(), []byte("bad")...), mockTx.Bytes()},
})
require.NoError(t, err)
require.Equal(t, len(res.Txs), 2)
}
func TestConsensus_ProcessProposal(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
// Invalid height
_, err := c.ProcessProposal(context.Background(), &abciproto.ProcessProposalRequest{
Height: 0,
})
require.Error(t, err)
// empty handler
_, err = c.ProcessProposal(context.Background(), &abciproto.ProcessProposalRequest{
Height: 1,
})
require.Error(t, err)
// NoOp handler
c.processProposalHandler = DefaultServerOptions[mock.Tx]().ProcessProposalHandler
_, err = c.ProcessProposal(context.Background(), &abciproto.ProcessProposalRequest{
Height: 1,
Txs: [][]byte{mockTx.Bytes()},
})
require.NoError(t, err)
}
func TestConsensus_ProcessProposal_With_Handler(t *testing.T) {
c := setUpConsensus(t, 100_000, cometmock.MockMempool[mock.Tx]{})
c.processProposalHandler = handlers.NewDefaultProposalHandler(c.mempool).ProcessHandler()
// exceed max gas
res, err := c.ProcessProposal(context.Background(), &abciproto.ProcessProposalRequest{
Height: 1,
Txs: [][]byte{mockTx.Bytes(), mockTx.Bytes(), mockTx.Bytes(), mockTx.Bytes()},
})
require.NoError(t, err)
require.Equal(t, res.Status, abciproto.PROCESS_PROPOSAL_STATUS_REJECT)
// have bad encode tx
// should reject
res, err = c.ProcessProposal(context.Background(), &abciproto.ProcessProposalRequest{
Height: 1,
Txs: [][]byte{mockTx.Bytes(), append(mockTx.Bytes(), []byte("bad")...), mockTx.Bytes(), mockTx.Bytes()},
})
require.NoError(t, err)
require.Equal(t, res.Status, abciproto.PROCESS_PROPOSAL_STATUS_REJECT)
}
func TestConsensus_Info(t *testing.T) {
c := setUpConsensus(t, 100_000, cometmock.MockMempool[mock.Tx]{})
// Version 0
res, err := c.Info(context.Background(), &abciproto.InfoRequest{})
require.NoError(t, err)
require.Equal(t, res.LastBlockHeight, int64(0))
// Commit store to version 1
_, err = c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Hash: emptyHash[:],
})
require.NoError(t, err)
res, err = c.Info(context.Background(), &abciproto.InfoRequest{})
require.NoError(t, err)
require.Equal(t, res.LastBlockHeight, int64(1))
}
// TODO:
// - GRPC request
// - app request
// - p2p request
func TestConsensus_Query(t *testing.T) {
c := setUpConsensus(t, 100_000, cometmock.MockMempool[mock.Tx]{})
// Write data to state storage
err := c.store.GetStateStorage().ApplyChangeset(&store.Changeset{
Version: 1,
Changes: []store.StateChanges{
{
Actor: actorName,
StateChanges: []store.KVPair{
{
Key: []byte("key"),
Value: []byte("value"),
Remove: false,
},
},
},
},
})
require.NoError(t, err)
_, err = c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Txs: [][]byte{mockTx.Bytes()},
Hash: emptyHash[:],
})
require.NoError(t, err)
// empty request
res, err := c.Query(context.Background(), &abciproto.QueryRequest{})
require.NoError(t, err)
require.Equal(t, res.Code, uint32(1))
require.Contains(t, res.Log, "no query path provided")
// Query store
res, err = c.Query(context.Background(), &abciproto.QueryRequest{
Path: "store/cookies/",
Data: []byte("key"),
Height: 1,
})
require.NoError(t, err)
require.Equal(t, string(res.Value), "value")
// Query store with no value
res, err = c.Query(context.Background(), &abciproto.QueryRequest{
Path: "store/cookies/",
Data: []byte("exec"),
Height: 1,
})
require.NoError(t, err)
require.Equal(t, res.Value, []byte(nil))
}
func setUpConsensus(t *testing.T, gasLimit uint64, mempool mempool.Mempool[mock.Tx]) *consensus[mock.Tx] {
t.Helper()
msgRouterBuilder := getMsgRouterBuilder(t, func(ctx context.Context, msg *gogotypes.BoolValue) (*gogotypes.BoolValue, error) {
return nil, nil
})
queryRouterBuilder := getQueryRouterBuilder(t, func(ctx context.Context, q *consensustypes.QueryParamsRequest) (*consensustypes.QueryParamsResponse, error) {
cParams := &v1.ConsensusParams{
Block: &v1.BlockParams{
MaxGas: 300000,
},
Feature: &v1.FeatureParams{
VoteExtensionsEnableHeight: &gogotypes.Int64Value{Value: 2},
},
}
return &consensustypes.QueryParamsResponse{
Params: cParams,
}, nil
})
s, err := stf.New(
log.NewNopLogger().With("module", "stf"),
msgRouterBuilder,
queryRouterBuilder,
func(ctx context.Context, txs []mock.Tx) error { return nil },
func(ctx context.Context) error {
return nil
},
func(ctx context.Context) error {
return nil
},
func(ctx context.Context, tx mock.Tx) error {
return nil
},
func(ctx context.Context) ([]appmodulev2.ValidatorUpdate, error) { return nil, nil },
func(ctx context.Context, tx mock.Tx, success bool) error {
return nil
},
branch.DefaultNewWriterMap,
)
require.NoError(t, err)
ss := cometmock.NewMockStorage(log.NewNopLogger(), t.TempDir())
sc := cometmock.NewMockCommiter(log.NewNopLogger(), string(actorName), "stf")
mockStore := cometmock.NewMockStore(ss, sc)
am := appmanager.New(appmanager.Config{
ValidateTxGasLimit: gasLimit,
QueryGasLimit: gasLimit,
SimulationGasLimit: gasLimit,
},
mockStore,
s,
func(ctx context.Context, src io.Reader, txHandler func(json.RawMessage) error) (store.WriterMap, error) {
_, st, err := mockStore.StateLatest()
require.NoError(t, err)
return branch.DefaultNewWriterMap(st), nil
},
nil,
)
return &consensus[mock.Tx]{
logger: log.NewNopLogger(),
appName: "testing-app",
app: am,
mempool: mempool,
store: mockStore,
cfg: Config{AppTomlConfig: DefaultAppTomlConfig()},
txCodec: mock.TxCodec{},
chainID: "test",
getProtoRegistry: sync.OnceValues(proto.MergedRegistry),
}
}
// Check target version same with store's latest version
// And should have commit info of target version
func assertStoreLatestVersion(t *testing.T, store types.Store, target uint64) {
t.Helper()
version, err := store.GetLatestVersion()
require.NoError(t, err)
require.Equal(t, target, version)
commitInfo, err := store.GetStateCommitment().GetCommitInfo(version)
require.NoError(t, err)
require.Equal(t, target, commitInfo.Version)
}
func TestOptimisticExecution(t *testing.T) {
c := setUpConsensus(t, 100_000, mempool.NoOpMempool[mock.Tx]{})
// Set up handlers
c.processProposalHandler = DefaultServerOptions[mock.Tx]().ProcessProposalHandler
// mock optimistic execution
calledTimes := 0
optimisticMockFunc := func(_ context.Context, _ *abciproto.FinalizeBlockRequest) (*abciproto.FinalizeBlockResponse, error) {
calledTimes++
return nil, errors.New("test error")
}
c.optimisticExec = oe.NewOptimisticExecution(log.NewNopLogger(), optimisticMockFunc)
_, err := c.InitChain(context.Background(), &abciproto.InitChainRequest{
Time: time.Now(),
ChainId: "test",
InitialHeight: 1,
})
require.NoError(t, err)
_, err = c.FinalizeBlock(context.Background(), &abciproto.FinalizeBlockRequest{
Time: time.Now(),
Height: 1,
Txs: [][]byte{mockTx.Bytes()},
Hash: emptyHash[:],
})
require.NoError(t, err)
theHash := sha256.Sum256([]byte("test"))
ppReq := &abciproto.ProcessProposalRequest{
Height: 2,
Hash: theHash[:],
Time: time.Now(),
Txs: [][]byte{mockTx.Bytes()},
}
// Start optimistic execution
resp, err := c.ProcessProposal(context.Background(), ppReq)
require.NoError(t, err)
require.Equal(t, resp.Status, abciproto.PROCESS_PROPOSAL_STATUS_ACCEPT)
// Initialize FinalizeBlock with correct hash - should use optimistic result
theHash = sha256.Sum256([]byte("test"))
fbReq := &abciproto.FinalizeBlockRequest{
Height: 2,
Hash: theHash[:],
Time: ppReq.Time,
Txs: ppReq.Txs,
}
fbResp, err := c.FinalizeBlock(context.Background(), fbReq)
require.Error(t, err)
require.ErrorContains(t, err, "test error") // from optimisticMockFunc
require.Equal(t, 1, calledTimes)
resp, err = c.ProcessProposal(context.Background(), ppReq)
require.NoError(t, err)
require.Equal(t, resp.Status, abciproto.PROCESS_PROPOSAL_STATUS_ACCEPT)
theWrongHash := sha256.Sum256([]byte("wrong_hash"))
fbReq.Hash = theWrongHash[:]
// Initialize FinalizeBlock with wrong hash - should abort optimistic execution
// Because is aborted, the result comes from the normal execution
fbResp, err = c.FinalizeBlock(context.Background(), fbReq)
require.NotNil(t, fbResp)
require.NoError(t, err)
require.Equal(t, 2, calledTimes)
// Verify optimistic execution was reset
require.False(t, c.optimisticExec.Initialized())
}