-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
1345 lines (1147 loc) · 42.9 KB
/
client.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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package abci_client
import (
"context"
"fmt"
"reflect"
"sync"
"time"
"github.com/barkimedes/go-deepcopy"
db "github.com/cometbft/cometbft-db"
abcitypes "github.com/cometbft/cometbft/abci/types"
cryptoenc "github.com/cometbft/cometbft/crypto/encoding"
"github.com/cometbft/cometbft/crypto/merkle"
cometlog "github.com/cometbft/cometbft/libs/log"
cmtmath "github.com/cometbft/cometbft/libs/math"
cmttypes "github.com/cometbft/cometbft/proto/tendermint/types"
"github.com/cometbft/cometbft/state"
blockindexkv "github.com/cometbft/cometbft/state/indexer/block/kv"
"github.com/cometbft/cometbft/state/txindex"
indexerkv "github.com/cometbft/cometbft/state/txindex/kv"
"github.com/cometbft/cometbft/types"
"github.com/informalsystems/CometMock/cometmock/storage"
"github.com/informalsystems/CometMock/cometmock/utils"
)
var GlobalClient *AbciClient
// store a mutex that allows only running one block at a time
var blockMutex = sync.Mutex{}
var verbose = false
const ABCI_TIMEOUT = 2 * time.Second
type MisbehaviourType int
const (
DuplicateVote MisbehaviourType = iota
Lunatic
Amnesia
Equivocation
)
// hardcode max data bytes to -1 (unlimited) since we do not utilize a mempool
// to pick evidence/txs out of
const maxDataBytes = -1
// AbciClient facilitates calls to the ABCI interface of multiple nodes.
// It also tracks the current state and a common logger.
type AbciClient struct {
Clients map[string]AbciCounterpartyClient // maps validator addresses to their clients
Logger cometlog.Logger
CurState state.State
EventBus types.EventBus
LastBlock *types.Block
LastCommit *types.ExtendedCommit
Storage storage.Storage
IndexerService *txindex.IndexerService
TxIndex *indexerkv.TxIndex
BlockIndex *blockindexkv.BlockerIndexer
// if this is true, then an error will be returned if the responses from the clients are not all equal.
// can be used to check for nondeterminism in apps, but also slows down execution a bit,
// though performance difference was not measured.
ErrorOnUnequalResponses bool
// validator addresses are mapped to false if they should not be signing, and to true if they should
signingStatus map[string]bool
signingStatusMutex sync.RWMutex
// time offset. whenever we qury the time, we add this offset to it
// this means after modifying this, blocks will have the timestamp offset by this value.
// this will look to the app like one block took a long time to be produced.
timeOffset time.Duration
}
func (a *AbciClient) GetTimeOffset() time.Duration {
return a.timeOffset
}
func (a *AbciClient) IncrementTimeOffset(additionalOffset time.Duration) error {
if additionalOffset < 0 {
a.Logger.Error("time offset cannot be decremented, please provide a positive offset")
return fmt.Errorf("time offset cannot be decremented, please provide a positive offset")
}
a.Logger.Debug("Incrementing time offset", "additionalOffset", additionalOffset.String())
a.timeOffset = a.timeOffset + additionalOffset
return nil
}
func (a *AbciClient) CauseLightClientAttack(address string, misbehaviourType string) error {
a.Logger.Info("Causing double sign", "address", address)
validator, err := a.GetValidatorFromAddress(address)
if err != nil {
return err
}
// get the misbehaviour type from the string
var misbehaviour MisbehaviourType
switch misbehaviourType {
case "Lunatic":
misbehaviour = Lunatic
case "Amnesia":
misbehaviour = Amnesia
case "Equivocation":
misbehaviour = Equivocation
default:
return fmt.Errorf("unknown misbehaviour type %s, possible types are: Equivocation, Lunatic, Amnesia", misbehaviourType)
}
_, _, _, err = a.RunBlockWithEvidence(nil, map[*types.Validator]MisbehaviourType{validator: misbehaviour})
return err
}
func (a *AbciClient) CauseDoubleSign(address string) error {
a.Logger.Info("Causing double sign", "address", address)
validator, err := a.GetValidatorFromAddress(address)
if err != nil {
return err
}
_, _, _, err = a.RunBlockWithEvidence(nil, map[*types.Validator]MisbehaviourType{validator: DuplicateVote})
return err
}
func (a *AbciClient) GetValidatorFromAddress(address string) (*types.Validator, error) {
for _, validator := range a.CurState.Validators.Validators {
if validator.Address.String() == address {
return validator, nil
}
}
return nil, fmt.Errorf("validator with address %s not found", address)
}
func (a *AbciClient) GetCounterpartyFromAddress(address string) (*AbciCounterpartyClient, error) {
for _, client := range a.Clients {
if client.ValidatorAddress == address {
return &client, nil
}
}
return nil, fmt.Errorf("client with address %s not found", address)
}
// GetSigningStatusMap gets a copy of the signing status map that can be used for reading.
func (a *AbciClient) GetSigningStatusMap() map[string]bool {
a.signingStatusMutex.RLock()
defer a.signingStatusMutex.RUnlock()
statusMap := make(map[string]bool, len(a.signingStatus))
for k, v := range a.signingStatus {
statusMap[k] = v
}
return statusMap
}
// GetSigningStatus gets the signing status of the given address.
func (a *AbciClient) GetSigningStatus(address string) (bool, error) {
a.signingStatusMutex.RLock()
defer a.signingStatusMutex.RUnlock()
status, ok := a.signingStatus[address]
if !ok {
return false, fmt.Errorf("address %s not found in signing status map, please double-check this is the key address of a validator key", address)
}
return status, nil
}
func (a *AbciClient) SetSigningStatus(address string, status bool) error {
a.signingStatusMutex.Lock()
defer a.signingStatusMutex.Unlock()
_, ok := a.signingStatus[address]
if !ok {
return fmt.Errorf("address %s not found in signing status map, please double-check this is the key address of a validator key", address)
}
a.signingStatus[address] = status
a.Logger.Info("Set signing status", "address", address, "status", status)
return nil
}
func CreateAndStartEventBus(logger cometlog.Logger) (*types.EventBus, error) {
eventBus := types.NewEventBus()
eventBus.SetLogger(logger.With("module", "events"))
if err := eventBus.Start(); err != nil {
return nil, err
}
return eventBus, nil
}
func CreateAndStartIndexerService(eventBus *types.EventBus, logger cometlog.Logger) (*txindex.IndexerService, *indexerkv.TxIndex, *blockindexkv.BlockerIndexer, error) {
txIndexer := indexerkv.NewTxIndex(db.NewMemDB())
blockIndexer := blockindexkv.New(db.NewMemDB())
indexerService := txindex.NewIndexerService(txIndexer, blockIndexer, eventBus, false)
indexerService.SetLogger(logger.With("module", "txindex"))
return indexerService, txIndexer, blockIndexer, indexerService.Start()
}
func NewAbciClient(clients map[string]AbciCounterpartyClient, logger cometlog.Logger, curState state.State, lastBlock *types.Block, lastCommit *types.ExtendedCommit, storage storage.Storage, errorOnUnequalResponses bool) *AbciClient {
signingStatus := make(map[string]bool)
for addr := range clients {
signingStatus[addr] = true
}
eventBus, err := CreateAndStartEventBus(logger)
if err != nil {
logger.Error(err.Error())
panic(err)
}
indexerService, txIndex, blockIndex, err := CreateAndStartIndexerService(eventBus, logger)
if err != nil {
logger.Error(err.Error())
panic(err)
}
return &AbciClient{
Clients: clients,
Logger: logger,
CurState: curState,
EventBus: *eventBus,
LastBlock: lastBlock,
LastCommit: lastCommit,
Storage: storage,
IndexerService: indexerService,
TxIndex: txIndex,
BlockIndex: blockIndex,
ErrorOnUnequalResponses: errorOnUnequalResponses,
signingStatus: signingStatus,
}
}
// TODO: This is currently not supported, see https://github.com/informalsystems/CometMock/issues/6
// func (a *AbciClient) RetryDisconnectedClients() {
// a.Logger.Info("Retrying disconnected clients")
// for i, client := range a.Clients {
// if !client.isConnected {
// ctx, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
// infoRes, err := c.Client.Info(ctx, &abcitypes.RequestInfo{})
// if err != nil {
// if unreachableErr, ok := err.(*ClientUnreachableError); ok {
// a.Logger.Error(unreachableErr.Error())
// } else {
// a.Logger.Error("Error calling client at address %v: %v", client.NetworkAddress, err)
// }
// } else {
// client.isConnected = true
// a.Clients[i] = client
// // resync the app state
// // infoRes.(abcitypes.ResponseInfo).LastBlockHeight
// // _ = infoRes
// }
// }
// }
// }
func (a *AbciClient) SyncApp(startHeight int64, client AbciCounterpartyClient) error {
return nil
}
type ClientUnreachableError struct {
Address string
}
func (e *ClientUnreachableError) Error() string {
return fmt.Sprintf("client at address %v is unavailable", e.Address)
}
func (a *AbciClient) SendAbciInfo() (*abcitypes.ResponseInfo, error) {
if verbose {
a.Logger.Info("Sending Info to clients")
}
// send Info to all clients and collect the responses
responses := make([]*abcitypes.ResponseInfo, 0)
for _, client := range a.Clients {
ctx, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
response, err := client.Client.Info(ctx, &abcitypes.RequestInfo{})
cancel()
if err != nil {
return nil, err
}
responses = append(responses, response)
}
if a.ErrorOnUnequalResponses {
// return an error if the responses are not all equal
for i := 1; i < len(responses); i++ {
if !reflect.DeepEqual(responses[i], responses[0]) {
return nil, fmt.Errorf("responses are not all equal: %v is not equal to %v", responses[i], responses[0])
}
}
}
return responses[0], nil
}
func (a *AbciClient) SendInitChain(genesisState state.State, genesisDoc *types.GenesisDoc) error {
if verbose {
a.Logger.Info("Sending InitChain to clients")
}
// build the InitChain request
initChainRequest := CreateInitChainRequest(genesisState, genesisDoc)
responses := make([]*abcitypes.ResponseInitChain, 0)
for _, client := range a.Clients {
ctx, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
response, err := client.Client.InitChain(ctx, initChainRequest)
cancel()
if err != nil {
return err
}
responses = append(responses, response)
}
if a.ErrorOnUnequalResponses {
// return an error if the responses are not all equal
for i := 1; i < len(responses); i++ {
if !reflect.DeepEqual(responses[i], responses[0]) {
return fmt.Errorf("responses are not all equal: %v is not equal to %v", responses[i], responses[0])
}
}
}
// update the state
err := a.UpdateStateFromInit(responses[0])
if err != nil {
return err
}
return nil
}
func CreateInitChainRequest(genesisState state.State, genesisDoc *types.GenesisDoc) *abcitypes.RequestInitChain {
consensusParams := genesisState.ConsensusParams.ToProto()
genesisValidators := genesisDoc.Validators
validators := make([]*types.Validator, len(genesisValidators))
for i, val := range genesisValidators {
validators[i] = types.NewValidator(val.PubKey, val.Power)
}
validatorSet := types.NewValidatorSet(validators)
nextVals := types.TM2PB.ValidatorUpdates(validatorSet)
initChainRequest := abcitypes.RequestInitChain{
Validators: nextVals,
InitialHeight: genesisState.InitialHeight,
Time: genesisDoc.GenesisTime,
ChainId: genesisState.ChainID,
ConsensusParams: &consensusParams,
AppStateBytes: genesisDoc.AppState,
}
return &initChainRequest
}
func (a *AbciClient) UpdateStateFromInit(res *abcitypes.ResponseInitChain) error {
// if response contained a non-empty app hash, update the app hash, otherwise we keep the one from the genesis file
if len(res.AppHash) > 0 {
a.CurState.AppHash = res.AppHash
}
// if response specified validators, update the validators, otherwise we keep the ones from the genesis file
if len(res.Validators) > 0 {
validators, err := types.PB2TM.ValidatorUpdates(res.Validators)
if err != nil {
return err
}
a.CurState.LastValidators = types.NewValidatorSet(validators)
a.CurState.Validators = types.NewValidatorSet(validators)
a.CurState.NextValidators = types.NewValidatorSet(validators).CopyIncrementProposerPriority(1)
}
// if response specified consensus params, update the consensus params, otherwise we keep the ones from the genesis file
if res.ConsensusParams != nil {
a.CurState.ConsensusParams = a.CurState.ConsensusParams.Update(res.ConsensusParams)
a.CurState.Version.Consensus.App = a.CurState.ConsensusParams.Version.App
}
// to conform with RFC-6962
a.CurState.LastResultsHash = merkle.HashFromByteSlices(nil)
return nil
}
func (a *AbciClient) SendCommit() (*abcitypes.ResponseCommit, error) {
a.Logger.Info("Sending Commit to clients")
// send Commit to all clients and collect the responses
responses := make([]*abcitypes.ResponseCommit, 0)
for _, client := range a.Clients {
ctx, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
response, err := client.Client.Commit(ctx, &abcitypes.RequestCommit{})
cancel()
if err != nil {
return nil, err
}
responses = append(responses, response)
}
if a.ErrorOnUnequalResponses {
// return an error if the responses are not all equal
for i := 1; i < len(responses); i++ {
if !reflect.DeepEqual(responses[i], responses[0]) {
return nil, fmt.Errorf("responses are not all equal: %v is not equal to %v", responses[i], responses[0])
}
}
}
return responses[0], nil
}
func (a *AbciClient) SendCheckTx(tx *[]byte) (*abcitypes.ResponseCheckTx, error) {
// build the CheckTx request
checkTxRequest := abcitypes.RequestCheckTx{
Tx: *tx,
}
// send CheckTx to all clients and collect the responses
responses := make([]*abcitypes.ResponseCheckTx, 0)
for _, client := range a.Clients {
ctx, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
response, err := client.Client.CheckTx(ctx, &checkTxRequest)
cancel()
if err != nil {
return nil, err
}
responses = append(responses, response)
}
if a.ErrorOnUnequalResponses {
// return an error if the responses are not all equal
for i := 1; i < len(responses); i++ {
if !reflect.DeepEqual(responses[i], responses[0]) {
return nil, fmt.Errorf("responses are not all equal: %v is not equal to %v", responses[i], responses[0])
}
}
}
return responses[0], nil
}
func (a *AbciClient) SendAbciQuery(data []byte, path string, height int64, prove bool) (*abcitypes.ResponseQuery, error) {
// find the first connected client
var client *AbciCounterpartyClient
for _, c := range a.Clients {
if c.isConnected {
client = &c
break
}
}
if client == nil {
return nil, fmt.Errorf("no connected clients")
}
// build the Query request
request := abcitypes.RequestQuery{
Data: data,
Path: path,
Height: height,
Prove: prove,
}
// send Query to the client and collect the response
ctx, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
defer cancel()
response, err := client.Client.Query(ctx, &request)
if err != nil {
return nil, err
}
return response, nil
}
// RunEmptyBlocks runs a specified number of empty blocks through ABCI.
func (a *AbciClient) RunEmptyBlocks(numBlocks int) error {
for i := 0; i < numBlocks; i++ {
_, _, _, err := a.RunBlock(nil)
if err != nil {
return err
}
}
return nil
}
func (a *AbciClient) decideProposal(
proposerApp *AbciCounterpartyClient,
proposerVal *types.Validator,
height int64,
round int32,
txs *types.Txs,
misbehaviour []types.Evidence,
) (*types.Proposal, *types.Block, error) {
var block *types.Block
var blockParts *types.PartSet
// Create a new proposal block from state/txs from the mempool.
var err error
block, err = a.CreateProposalBlock(
proposerApp,
proposerVal,
height,
a.CurState,
a.LastCommit,
txs,
&misbehaviour,
)
if err != nil {
return nil, nil, err
} else if block == nil {
panic("Method createProposalBlock should not provide a nil block without errors")
}
blockParts, err = block.MakePartSet(types.BlockPartSizeBytes)
if err != nil {
return nil, nil, fmt.Errorf("unable to create proposal block part set: %v", err)
}
// Make proposal
propBlockID := types.BlockID{Hash: block.Hash(), PartSetHeader: blockParts.Header()}
proposal := types.NewProposal(height, round, 0, propBlockID)
p := proposal.ToProto()
if err := proposerApp.PrivValidator.SignProposal(a.CurState.ChainID, p); err == nil {
proposal.Signature = p.Signature
// TODO: evaluate if we need to emulate message sending
// send proposal and block parts on internal msg queue
// cs.sendInternalMessage(msgInfo{&ProposalMessage{proposal}, ""})
// for i := 0; i < int(blockParts.Total()); i++ {
// part := blockParts.GetPart(i)
// cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""})
// }
a.Logger.Debug("signed proposal", "height", height, "round", round, "proposal", proposal)
} else {
a.Logger.Error("propose step; failed signing proposal", "height", height, "round", round, "err", err)
}
return proposal, block, nil
}
// Create a proposal block with the given height and proposer,
// and including the given tx and misbehaviour.
// Essentially a hollowed-out version of CreateProposalBlock in CometBFT, see
// https://github.com/cometbft/cometbft/blob/33d276831843854881e6365b9696ac39dda12922/state/execution.go#L101
func (a *AbciClient) CreateProposalBlock(
proposerApp *AbciCounterpartyClient,
proposerVal *types.Validator,
height int64,
curState state.State,
lastExtCommit *types.ExtendedCommit,
txs *types.Txs,
misbehaviour *[]types.Evidence,
) (*types.Block, error) {
commit := lastExtCommit.ToCommit()
block := curState.MakeBlock(height, *txs, commit, *misbehaviour, proposerVal.Address)
request := &abcitypes.RequestPrepareProposal{
MaxTxBytes: maxDataBytes,
Txs: block.Txs.ToSliceOfBytes(),
LocalLastCommit: utils.BuildExtendedCommitInfo(lastExtCommit, curState.LastValidators, curState.InitialHeight, curState.ConsensusParams.ABCI),
Misbehavior: block.Evidence.Evidence.ToABCI(),
Height: block.Height,
Time: block.Time,
NextValidatorsHash: block.NextValidatorsHash,
ProposerAddress: block.ProposerAddress,
}
ctx, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
response, err := proposerApp.Client.PrepareProposal(ctx, request)
cancel()
if err != nil {
// We panic, since there is no meaninful recovery we can perform here.
panic(err)
}
modifiedTxs := response.GetTxs()
txl := types.ToTxs(modifiedTxs)
if err := txl.Validate(maxDataBytes); err != nil {
return nil, err
}
return curState.MakeBlock(height, txl, commit, *misbehaviour, block.ProposerAddress), nil
}
// RunBlock runs a block with a specified transaction through the ABCI application.
// It calls RunBlockWithTimeAndProposer with the current time and the LastValidators.Proposer.
func (a *AbciClient) RunBlock(tx *[]byte) (*abcitypes.ResponseCheckTx, *abcitypes.ResponseFinalizeBlock, *abcitypes.ResponseCommit, error) {
return a.RunBlockWithTimeAndProposer(tx, time.Now().Add(a.timeOffset), a.CurState.LastValidators.Proposer, make(map[*types.Validator]MisbehaviourType, 0))
}
// RunBlockWithEvidence runs a block with a specified transaction through the ABCI application.
// It also produces the specified evidence for the specified misbehaving validators.
func (a *AbciClient) RunBlockWithEvidence(tx *[]byte, misbehavingValidators map[*types.Validator]MisbehaviourType) (*abcitypes.ResponseCheckTx, *abcitypes.ResponseFinalizeBlock, *abcitypes.ResponseCommit, error) {
return a.RunBlockWithTimeAndProposer(tx, time.Now().Add(a.timeOffset), a.CurState.LastValidators.Proposer, misbehavingValidators)
}
func (a *AbciClient) ConstructDuplicateVoteEvidence(v *types.Validator) (*types.DuplicateVoteEvidence, error) {
privVal := a.Clients[v.Address.String()].PrivValidator
lastBlock := a.LastBlock
blockId, err := utils.GetBlockIdFromBlock(lastBlock)
if err != nil {
return nil, err
}
lastState, err := a.Storage.GetState(lastBlock.Height)
if err != nil {
return nil, err
}
// get the index of the validator in the last state
index, valInLastState := lastState.Validators.GetByAddress(v.Address)
// produce vote A.
voteA := &cmttypes.Vote{
ValidatorAddress: v.Address,
ValidatorIndex: int32(index),
Height: lastBlock.Height,
Round: 1,
Timestamp: time.Now().Add(a.timeOffset),
Type: cmttypes.PrecommitType,
BlockID: blockId.ToProto(),
}
// TODO: remove the two votes/create a real difference
// produce vote B, which just has a different round.
voteB := &cmttypes.Vote{
ValidatorAddress: v.Address,
ValidatorIndex: int32(index),
Height: lastBlock.Height,
Round: 2, // this is what differentiates the votes
Timestamp: time.Now().Add(a.timeOffset),
Type: cmttypes.PrecommitType,
BlockID: blockId.ToProto(),
}
// sign the votes
privVal.SignVote(a.CurState.ChainID, voteA)
privVal.SignVote(a.CurState.ChainID, voteB)
// votes need to pass validation rules
convertedVoteA, err := types.VoteFromProto(voteA)
if err != nil {
a.Logger.Error("Error converting vote A", "error", err)
return nil, err
}
err = convertedVoteA.ValidateBasic()
if err != nil {
a.Logger.Error("Error validating vote A", "error", err)
return nil, err
}
convertedVoteB, err := types.VoteFromProto(voteB)
if err != nil {
a.Logger.Error("Error converting vote B", "error", err)
return nil, err
}
err = convertedVoteB.ValidateBasic()
if err != nil {
a.Logger.Error("Error validating vote B", "error", err)
return nil, err
}
// build the actual evidence
evidence := types.DuplicateVoteEvidence{
VoteA: convertedVoteA,
VoteB: convertedVoteB,
TotalVotingPower: lastState.Validators.TotalVotingPower(),
ValidatorPower: valInLastState.VotingPower,
Timestamp: lastBlock.Time,
}
return &evidence, nil
}
func (a *AbciClient) ConstructLightClientAttackEvidence(
v *types.Validator,
misbehaviourType MisbehaviourType,
) (*types.LightClientAttackEvidence, error) {
lastBlock := a.LastBlock
lastState, err := a.Storage.GetState(lastBlock.Height)
if err != nil {
return nil, err
}
// deepcopy the last block so we can modify it
cp, err := deepcopy.Anything(lastBlock)
if err != nil {
return nil, err
}
// force the type conversion into a block
conflictingBlock := cp.(*types.Block)
switch misbehaviourType {
case Lunatic:
// modify the app hash to be invalid
conflictingBlock.AppHash = []byte("some other app hash")
case Amnesia:
// TODO not sure how to handle this yet, just leave the block intact for now
case Equivocation:
// get another valid block by making it have a different time
conflictingBlock.Time = conflictingBlock.Time.Add(1 * time.Second)
default:
return nil, fmt.Errorf("unknown misbehaviour type %v for light client misbehaviour", misbehaviourType)
}
// make the conflicting block into a light block
signedHeader := types.SignedHeader{
Header: &conflictingBlock.Header,
Commit: a.LastCommit.ToCommit(),
}
conflictingLightBlock := types.LightBlock{
SignedHeader: &signedHeader,
ValidatorSet: a.CurState.Validators,
}
return &types.LightClientAttackEvidence{
TotalVotingPower: lastState.Validators.TotalVotingPower(),
Timestamp: lastBlock.Time,
ByzantineValidators: []*types.Validator{v},
CommonHeight: lastBlock.Height - 1,
ConflictingBlock: &conflictingLightBlock,
}, nil
}
// Calls ProcessProposal on a provided app, with the given block as
// proposed block.
func (a *AbciClient) ProcessProposal(
app *AbciCounterpartyClient,
block *types.Block,
) (bool, error) {
// call the temporary function on the client
timeoutContext, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
defer cancel()
response, err := app.Client.ProcessProposal(timeoutContext, &abcitypes.RequestProcessProposal{
Hash: block.Header.Hash(),
Height: block.Header.Height,
Time: block.Header.Time,
Txs: block.Data.Txs.ToSliceOfBytes(),
ProposedLastCommit: utils.BuildLastCommitInfo(block, a.CurState.Validators, a.CurState.InitialHeight),
Misbehavior: block.Evidence.Evidence.ToABCI(),
ProposerAddress: block.ProposerAddress,
NextValidatorsHash: block.NextValidatorsHash,
})
if err != nil {
return false, err
}
if response.IsStatusUnknown() {
panic(fmt.Sprintf("ProcessProposal responded with status %s", response.Status.String()))
}
return response.IsAccepted(), nil
}
func (a *AbciClient) ExtendAndSignVote(
app *AbciCounterpartyClient,
validator *types.Validator,
valIndex int32,
block *types.Block,
) (*types.Vote, error) {
// get the index of this validator in the current validator set
blockParts, err := block.MakePartSet(types.BlockPartSizeBytes)
if err != nil {
panic(fmt.Sprintf("error making block part set: %v", err))
}
vote := &types.Vote{
ValidatorAddress: validator.Address,
ValidatorIndex: int32(valIndex),
Height: block.Height,
Round: block.LastCommit.Round,
Timestamp: block.Time,
Type: cmttypes.PrecommitType,
BlockID: types.BlockID{
Hash: block.Hash(),
PartSetHeader: blockParts.Header(),
},
}
if a.CurState.ConsensusParams.ABCI.VoteExtensionsEnabled(vote.Height) {
ext, err := app.Client.ExtendVote(context.TODO(), &abcitypes.RequestExtendVote{
Hash: vote.BlockID.Hash,
Height: vote.Height,
Time: block.Time,
Txs: block.Txs.ToSliceOfBytes(),
ProposedLastCommit: utils.BuildLastCommitInfo(block, a.CurState.Validators, a.CurState.InitialHeight),
Misbehavior: block.Evidence.Evidence.ToABCI(),
NextValidatorsHash: block.NextValidatorsHash,
ProposerAddress: block.ProposerAddress,
})
if err != nil {
return nil, fmt.Errorf("error extending vote %v:\n %v", vote.String(), err)
}
vote.Extension = ext.VoteExtension
}
// going through ToProto looks weird but this is
// how signing is done in CometBFT https://github.com/cometbft/cometbft/blob/f63499c82c7defcdd82696f262f5a2eb495a3ac7/types/vote.go#L405
protoVote := vote.ToProto()
err = app.PrivValidator.SignVote(a.CurState.ChainID, protoVote)
vote.Signature = protoVote.Signature
vote.ExtensionSignature = nil
if a.CurState.ConsensusParams.ABCI.VoteExtensionsEnabled(vote.Height) {
vote.ExtensionSignature = protoVote.ExtensionSignature
}
if err != nil {
return nil, fmt.Errorf("error signing vote %v:\n %v", vote.String(), err)
}
return vote, nil
}
// SendFinalizeBlock sends a FinalizeBlock request to all clients and collects the responses.
// The last commit of the AbciClient needs to be set when calling this.
func (a *AbciClient) SendFinalizeBlock(
block *types.Block,
lastCommitInfo *abcitypes.CommitInfo,
) (*abcitypes.ResponseFinalizeBlock, error) {
// build the FinalizeBlock request
request := abcitypes.RequestFinalizeBlock{
Txs: block.Txs.ToSliceOfBytes(),
DecidedLastCommit: *lastCommitInfo,
Misbehavior: block.Evidence.Evidence.ToABCI(),
Height: block.Height,
Hash: block.Hash(),
Time: block.Time,
ProposerAddress: block.ProposerAddress,
NextValidatorsHash: block.NextValidatorsHash,
}
// send FinalizeBlock to all clients and collect the responses
responses := make([]*abcitypes.ResponseFinalizeBlock, 0)
for _, client := range a.Clients {
ctx, cancel := context.WithTimeout(context.Background(), ABCI_TIMEOUT)
response, err := client.Client.FinalizeBlock(ctx, &request)
cancel()
if err != nil {
return nil, err
}
responses = append(responses, response)
}
if a.ErrorOnUnequalResponses {
// return an error if the responses are not all equal
for i := 1; i < len(responses); i++ {
if !reflect.DeepEqual(responses[i], responses[0]) {
return nil, fmt.Errorf("responses are not all equal: %v is not equal to %v", responses[i], responses[0])
}
}
}
return responses[0], nil
}
// RunBlock runs a block with a specified transaction through the ABCI application.
// It calls BeginBlock, DeliverTx, EndBlock, Commit and then
// updates the state.
// RunBlock is safe for use by multiple goroutines simultaneously.
func (a *AbciClient) RunBlockWithTimeAndProposer(
tx *[]byte,
blockTime time.Time,
proposer *types.Validator,
misbehavingValidators map[*types.Validator]MisbehaviourType,
) (*abcitypes.ResponseCheckTx, *abcitypes.ResponseFinalizeBlock, *abcitypes.ResponseCommit, error) {
// lock mutex to avoid running two blocks at the same time
a.Logger.Debug("Locking mutex")
blockMutex.Lock()
defer blockMutex.Unlock()
defer a.Logger.Debug("Unlocking mutex")
a.Logger.Info("Running block")
if verbose {
a.Logger.Info("State at start of block", "state", a.CurState)
}
newHeight := a.CurState.LastBlockHeight + 1
txs := make(types.Txs, 0)
if tx != nil {
txs = append(txs, *tx)
}
var resCheckTx *abcitypes.ResponseCheckTx
var err error
if tx != nil {
resCheckTx, err = a.SendCheckTx(tx)
if err != nil {
return nil, nil, nil, fmt.Errorf("error from CheckTx: %v", err)
}
}
// TODO: handle special case where proposer is nil
var proposerAddress types.Address
if proposer != nil {
proposerAddress = proposer.Address
}
evidences := make([]types.Evidence, 0)
for v, misbehaviourType := range misbehavingValidators {
// match the misbehaviour type to call the correct function
var evidence types.Evidence
var err error
if misbehaviourType == DuplicateVote {
// create double-sign evidence
evidence, err = a.ConstructDuplicateVoteEvidence(v)
} else {
// create light client attack evidence
evidence, err = a.ConstructLightClientAttackEvidence(v, misbehaviourType)
}
if err != nil {
return nil, nil, nil, fmt.Errorf("error constructing evidence: %v", err)
}
evidences = append(evidences, evidence)
}
var proposerApp *AbciCounterpartyClient
for _, c := range a.Clients {
if c.ValidatorAddress == proposerAddress.String() {
proposerApp = &c
break
}
}
if proposerApp == nil {
return nil, nil, nil, fmt.Errorf("could not find proposer app for address %v", proposerAddress)
}
// The proposer runs PrepareProposal
_, block, err := a.decideProposal(
proposerApp,
proposer,
a.CurState.LastBlockHeight+1,
0,
&txs,
evidences,
)
if err != nil {
return nil, nil, nil, fmt.Errorf("error in decideProposal: %v", err)
}
var nonProposers []*AbciCounterpartyClient
for _, val := range a.CurState.Validators.Validators {
client, err := a.GetCounterpartyFromAddress(val.Address.String())
if err != nil {
return nil, nil, nil, fmt.Errorf("error when getting counterparty client from address: address %v, error %v", val.Address.String(), err)
}
if client.ValidatorAddress != proposerAddress.String() {
nonProposers = append(nonProposers, client)
}
}
// non-proposers run ProcessProposal
for _, client := range nonProposers {
accepted, err := a.ProcessProposal(client, block)
if err != nil {
return nil, nil, nil, fmt.Errorf("error in ProcessProposal for block %v, error %v", block.String(), err)
}
if !accepted {
return nil, nil, nil, fmt.Errorf("non-proposer %v did not accept the proposal for block %v", client.ValidatorAddress, block.String())
}
}
votes := []*types.Vote{}
// sign the block with all current validators, and call ExtendVote (if necessary)
for index, val := range a.CurState.Validators.Validators {
shouldSign, err := a.GetSigningStatus(val.Address.String())
if err != nil {
return nil, nil, nil, fmt.Errorf("error getting signing status for validator %v, error %v", val.Address.String(), err)