-
Notifications
You must be signed in to change notification settings - Fork 175
/
fixtures.go
2433 lines (2094 loc) · 65.3 KB
/
fixtures.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 unittest
import (
"bytes"
crand "crypto/rand"
"fmt"
"math/rand"
"net"
"testing"
"time"
blocks "github.com/ipfs/go-block-format"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/stretchr/testify/require"
"github.com/onflow/cadence"
sdk "github.com/onflow/flow-go-sdk"
hotstuff "github.com/onflow/flow-go/consensus/hotstuff/model"
"github.com/onflow/flow-go/crypto"
"github.com/onflow/flow-go/crypto/hash"
"github.com/onflow/flow-go/engine"
"github.com/onflow/flow-go/fvm/storage/snapshot"
"github.com/onflow/flow-go/ledger"
"github.com/onflow/flow-go/ledger/common/bitutils"
"github.com/onflow/flow-go/ledger/common/testutils"
"github.com/onflow/flow-go/model/bootstrap"
"github.com/onflow/flow-go/model/chainsync"
"github.com/onflow/flow-go/model/chunks"
"github.com/onflow/flow-go/model/cluster"
"github.com/onflow/flow-go/model/encoding"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/model/flow/filter"
"github.com/onflow/flow-go/model/flow/order"
"github.com/onflow/flow-go/model/messages"
"github.com/onflow/flow-go/model/verification"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/module/executiondatasync/execution_data"
"github.com/onflow/flow-go/module/mempool/entity"
"github.com/onflow/flow-go/module/signature"
"github.com/onflow/flow-go/module/updatable_configs"
"github.com/onflow/flow-go/network"
"github.com/onflow/flow-go/network/channels"
"github.com/onflow/flow-go/network/p2p/keyutils"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/state/protocol/inmem"
"github.com/onflow/flow-go/utils/dsl"
)
const (
DefaultSeedFixtureLength = 64
DefaultAddress = "localhost:0"
)
// returns a deterministic math/rand PRG that can be used for deterministic randomness in tests only.
// The PRG seed is logged in case the test iteration needs to be reproduced.
func GetPRG(t *testing.T) *rand.Rand {
random := time.Now().UnixNano()
t.Logf("rng seed is %d", random)
rng := rand.New(rand.NewSource(random))
return rng
}
func IPPort(port string) string {
return net.JoinHostPort("localhost", port)
}
func AddressFixture() flow.Address {
return flow.Testnet.Chain().ServiceAddress()
}
func RandomAddressFixture() flow.Address {
// we use a 32-bit index - since the linear address generator uses 45 bits,
// this won't error
addr, err := flow.Testnet.Chain().AddressAtIndex(uint64(rand.Uint32()))
if err != nil {
panic(err)
}
return addr
}
// Uint64InRange returns a uint64 value drawn from the uniform random distribution [min,max].
func Uint64InRange(min, max uint64) uint64 {
return min + uint64(rand.Intn(int(max)+1-int(min)))
}
func RandomSDKAddressFixture() sdk.Address {
addr := RandomAddressFixture()
var sdkAddr sdk.Address
copy(sdkAddr[:], addr[:])
return sdkAddr
}
func InvalidAddressFixture() flow.Address {
addr := AddressFixture()
addr[0] ^= 1 // alter one bit to obtain an invalid address
if flow.Testnet.Chain().IsValid(addr) {
panic("invalid address fixture generated valid address")
}
return addr
}
func InvalidFormatSignature() flow.TransactionSignature {
return flow.TransactionSignature{
Address: AddressFixture(),
SignerIndex: 0,
Signature: make([]byte, crypto.SignatureLenECDSAP256), // zero signature is invalid
KeyIndex: 1,
}
}
func TransactionSignatureFixture() flow.TransactionSignature {
sigLen := crypto.SignatureLenECDSAP256
s := flow.TransactionSignature{
Address: AddressFixture(),
SignerIndex: 0,
Signature: SeedFixture(sigLen),
KeyIndex: 1,
}
// make sure the ECDSA signature passes the format check
s.Signature[sigLen/2] = 0
s.Signature[0] = 0
s.Signature[sigLen/2-1] |= 1
s.Signature[sigLen-1] |= 1
return s
}
func ProposalKeyFixture() flow.ProposalKey {
return flow.ProposalKey{
Address: AddressFixture(),
KeyIndex: 1,
SequenceNumber: 0,
}
}
// AccountKeyDefaultFixture returns a randomly generated ECDSA/SHA3 account key.
func AccountKeyDefaultFixture() (*flow.AccountPrivateKey, error) {
return AccountKeyFixture(crypto.KeyGenSeedMinLen, crypto.ECDSAP256, hash.SHA3_256)
}
// AccountKeyFixture returns a randomly generated account key.
func AccountKeyFixture(
seedLength int,
signingAlgo crypto.SigningAlgorithm,
hashAlgo hash.HashingAlgorithm,
) (*flow.AccountPrivateKey, error) {
seed := make([]byte, seedLength)
_, err := crand.Read(seed)
if err != nil {
return nil, err
}
key, err := crypto.GeneratePrivateKey(signingAlgo, seed)
if err != nil {
return nil, err
}
return &flow.AccountPrivateKey{
PrivateKey: key,
SignAlgo: key.Algorithm(),
HashAlgo: hashAlgo,
}, nil
}
// AccountFixture returns a randomly generated account.
func AccountFixture() (*flow.Account, error) {
key, err := AccountKeyFixture(128, crypto.ECDSAP256, hash.SHA3_256)
if err != nil {
return nil, err
}
contracts := make(map[string][]byte, 2)
contracts["contract1"] = []byte("contract1")
contracts["contract2"] = []byte("contract2")
return &flow.Account{
Address: RandomAddressFixture(),
Balance: 100,
Keys: []flow.AccountPublicKey{key.PublicKey(1000)},
Contracts: contracts,
}, nil
}
func BlockFixture() flow.Block {
header := BlockHeaderFixture()
return *BlockWithParentFixture(header)
}
func FullBlockFixture() flow.Block {
block := BlockFixture()
payload := block.Payload
payload.Seals = Seal.Fixtures(10)
payload.Results = []*flow.ExecutionResult{
ExecutionResultFixture(),
ExecutionResultFixture(),
}
payload.Receipts = []*flow.ExecutionReceiptMeta{
ExecutionReceiptFixture(WithResult(payload.Results[0])).Meta(),
ExecutionReceiptFixture(WithResult(payload.Results[1])).Meta(),
}
header := block.Header
header.PayloadHash = payload.Hash()
return flow.Block{
Header: header,
Payload: payload,
}
}
func BlockFixtures(number int) []*flow.Block {
blocks := make([]*flow.Block, 0, number)
for ; number > 0; number-- {
block := BlockFixture()
blocks = append(blocks, &block)
}
return blocks
}
func ProposalFixture() *messages.BlockProposal {
block := BlockFixture()
return ProposalFromBlock(&block)
}
func ProposalFromBlock(block *flow.Block) *messages.BlockProposal {
return messages.NewBlockProposal(block)
}
func ClusterProposalFromBlock(block *cluster.Block) *messages.ClusterBlockProposal {
return messages.NewClusterBlockProposal(block)
}
// AsSlashable returns the input message T, wrapped as a flow.Slashable instance with a random origin ID.
func AsSlashable[T any](msg T) flow.Slashable[T] {
slashable := flow.Slashable[T]{
OriginID: IdentifierFixture(),
Message: msg,
}
return slashable
}
func ReceiptAndSealForBlock(block *flow.Block) (*flow.ExecutionReceipt, *flow.Seal) {
receipt := ReceiptForBlockFixture(block)
seal := Seal.Fixture(Seal.WithBlock(block.Header), Seal.WithResult(&receipt.ExecutionResult))
return receipt, seal
}
func PayloadFixture(options ...func(*flow.Payload)) flow.Payload {
payload := flow.EmptyPayload()
for _, option := range options {
option(&payload)
}
return payload
}
// WithAllTheFixins ensures a payload contains no empty slice fields. When
// encoding and decoding, nil vs empty slices are not preserved, which can
// result in two models that are semantically equal being considered non-equal
// by our testing framework.
func WithAllTheFixins(payload *flow.Payload) {
payload.Seals = Seal.Fixtures(3)
payload.Guarantees = CollectionGuaranteesFixture(4)
for i := 0; i < 10; i++ {
receipt := ExecutionReceiptFixture()
payload.Receipts = flow.ExecutionReceiptMetaList{receipt.Meta()}
payload.Results = flow.ExecutionResultList{&receipt.ExecutionResult}
}
}
func WithSeals(seals ...*flow.Seal) func(*flow.Payload) {
return func(payload *flow.Payload) {
payload.Seals = append(payload.Seals, seals...)
}
}
func WithGuarantees(guarantees ...*flow.CollectionGuarantee) func(*flow.Payload) {
return func(payload *flow.Payload) {
payload.Guarantees = append(payload.Guarantees, guarantees...)
}
}
func WithReceipts(receipts ...*flow.ExecutionReceipt) func(*flow.Payload) {
return func(payload *flow.Payload) {
for _, receipt := range receipts {
payload.Receipts = append(payload.Receipts, receipt.Meta())
payload.Results = append(payload.Results, &receipt.ExecutionResult)
}
}
}
// WithReceiptsAndNoResults will add receipt to payload only
func WithReceiptsAndNoResults(receipts ...*flow.ExecutionReceipt) func(*flow.Payload) {
return func(payload *flow.Payload) {
for _, receipt := range receipts {
payload.Receipts = append(payload.Receipts, receipt.Meta())
}
}
}
// WithExecutionResults will add execution results to payload
func WithExecutionResults(results ...*flow.ExecutionResult) func(*flow.Payload) {
return func(payload *flow.Payload) {
for _, result := range results {
payload.Results = append(payload.Results, result)
}
}
}
func BlockWithParentFixture(parent *flow.Header) *flow.Block {
payload := PayloadFixture()
header := BlockHeaderWithParentFixture(parent)
header.PayloadHash = payload.Hash()
return &flow.Block{
Header: header,
Payload: &payload,
}
}
func BlockWithGuaranteesFixture(guarantees []*flow.CollectionGuarantee) *flow.Block {
payload := PayloadFixture(WithGuarantees(guarantees...))
header := BlockHeaderFixture()
header.PayloadHash = payload.Hash()
return &flow.Block{
Header: header,
Payload: &payload,
}
}
func WithoutGuarantee(payload *flow.Payload) {
payload.Guarantees = nil
}
func StateInteractionsFixture() *snapshot.ExecutionSnapshot {
return &snapshot.ExecutionSnapshot{}
}
func BlockWithParentAndProposerFixture(
t *testing.T,
parent *flow.Header,
proposer flow.Identifier,
) flow.Block {
block := BlockWithParentFixture(parent)
indices, err := signature.EncodeSignersToIndices(
[]flow.Identifier{proposer}, []flow.Identifier{proposer})
require.NoError(t, err)
block.Header.ProposerID = proposer
block.Header.ParentVoterIndices = indices
if block.Header.LastViewTC != nil {
block.Header.LastViewTC.SignerIndices = indices
block.Header.LastViewTC.NewestQC.SignerIndices = indices
}
return *block
}
func BlockWithParentAndSeals(parent *flow.Header, seals []*flow.Header) *flow.Block {
block := BlockWithParentFixture(parent)
payload := flow.Payload{
Guarantees: nil,
}
if len(seals) > 0 {
payload.Seals = make([]*flow.Seal, len(seals))
for i, seal := range seals {
payload.Seals[i] = Seal.Fixture(
Seal.WithBlockID(seal.ID()),
)
}
}
block.SetPayload(payload)
return block
}
func GenesisFixture() *flow.Block {
genesis := flow.Genesis(flow.Emulator)
return genesis
}
func WithHeaderHeight(height uint64) func(header *flow.Header) {
return func(header *flow.Header) {
header.Height = height
}
}
func HeaderWithView(view uint64) func(*flow.Header) {
return func(header *flow.Header) {
header.View = view
}
}
func BlockHeaderFixture(opts ...func(header *flow.Header)) *flow.Header {
height := 1 + uint64(rand.Uint32()) // avoiding edge case of height = 0 (genesis block)
view := height + uint64(rand.Intn(1000))
header := BlockHeaderWithParentFixture(&flow.Header{
ChainID: flow.Emulator,
ParentID: IdentifierFixture(),
Height: height,
View: view,
})
for _, opt := range opts {
opt(header)
}
return header
}
func CidFixture() cid.Cid {
data := make([]byte, 1024)
_, _ = rand.Read(data)
return blocks.NewBlock(data).Cid()
}
func BlockHeaderFixtureOnChain(
chainID flow.ChainID,
opts ...func(header *flow.Header),
) *flow.Header {
height := 1 + uint64(rand.Uint32()) // avoiding edge case of height = 0 (genesis block)
view := height + uint64(rand.Intn(1000))
header := BlockHeaderWithParentFixture(&flow.Header{
ChainID: chainID,
ParentID: IdentifierFixture(),
Height: height,
View: view,
})
for _, opt := range opts {
opt(header)
}
return header
}
func BlockHeaderWithParentFixture(parent *flow.Header) *flow.Header {
height := parent.Height + 1
view := parent.View + 1 + uint64(rand.Intn(10)) // Intn returns [0, n)
var lastViewTC *flow.TimeoutCertificate
if view != parent.View+1 {
newestQC := QuorumCertificateFixture(func(qc *flow.QuorumCertificate) {
qc.View = parent.View
})
lastViewTC = &flow.TimeoutCertificate{
View: view - 1,
NewestQCViews: []uint64{newestQC.View},
NewestQC: newestQC,
SignerIndices: SignerIndicesFixture(4),
SigData: SignatureFixture(),
}
}
return &flow.Header{
ChainID: parent.ChainID,
ParentID: parent.ID(),
Height: height,
PayloadHash: IdentifierFixture(),
Timestamp: time.Now().UTC(),
View: view,
ParentView: parent.View,
ParentVoterIndices: SignerIndicesFixture(4),
ParentVoterSigData: QCSigDataFixture(),
ProposerID: IdentifierFixture(),
ProposerSigData: SignatureFixture(),
LastViewTC: lastViewTC,
}
}
func ClusterPayloadFixture(n int) *cluster.Payload {
transactions := make([]*flow.TransactionBody, n)
for i := 0; i < n; i++ {
tx := TransactionBodyFixture()
transactions[i] = &tx
}
payload := cluster.PayloadFromTransactions(flow.ZeroID, transactions...)
return &payload
}
func ClusterBlockFixture() cluster.Block {
payload := ClusterPayloadFixture(3)
header := BlockHeaderFixture()
header.PayloadHash = payload.Hash()
return cluster.Block{
Header: header,
Payload: payload,
}
}
// ClusterBlockWithParent creates a new cluster consensus block that is valid
// with respect to the given parent block.
func ClusterBlockWithParent(parent *cluster.Block) cluster.Block {
payload := ClusterPayloadFixture(3)
header := BlockHeaderFixture()
header.Height = parent.Header.Height + 1
header.View = parent.Header.View + 1
header.ChainID = parent.Header.ChainID
header.Timestamp = time.Now()
header.ParentID = parent.ID()
header.ParentView = parent.Header.View
header.PayloadHash = payload.Hash()
block := cluster.Block{
Header: header,
Payload: payload,
}
return block
}
func WithCollRef(refID flow.Identifier) func(*flow.CollectionGuarantee) {
return func(guarantee *flow.CollectionGuarantee) {
guarantee.ReferenceBlockID = refID
}
}
func WithCollection(collection *flow.Collection) func(guarantee *flow.CollectionGuarantee) {
return func(guarantee *flow.CollectionGuarantee) {
guarantee.CollectionID = collection.ID()
}
}
func CollectionGuaranteeFixture(options ...func(*flow.CollectionGuarantee)) *flow.CollectionGuarantee {
guarantee := &flow.CollectionGuarantee{
CollectionID: IdentifierFixture(),
SignerIndices: RandomBytes(16),
Signature: SignatureFixture(),
}
for _, option := range options {
option(guarantee)
}
return guarantee
}
func CollectionGuaranteesWithCollectionIDFixture(collections []*flow.Collection) []*flow.CollectionGuarantee {
guarantees := make([]*flow.CollectionGuarantee, 0, len(collections))
for i := 0; i < len(collections); i++ {
guarantee := CollectionGuaranteeFixture(WithCollection(collections[i]))
guarantees = append(guarantees, guarantee)
}
return guarantees
}
func CollectionGuaranteesFixture(
n int,
options ...func(*flow.CollectionGuarantee),
) []*flow.CollectionGuarantee {
guarantees := make([]*flow.CollectionGuarantee, 0, n)
for i := 1; i <= n; i++ {
guarantee := CollectionGuaranteeFixture(options...)
guarantees = append(guarantees, guarantee)
}
return guarantees
}
func BlockSealsFixture(n int) []*flow.Seal {
seals := make([]*flow.Seal, 0, n)
for i := 0; i < n; i++ {
seal := Seal.Fixture()
seals = append(seals, seal)
}
return seals
}
func CollectionListFixture(n int, options ...func(*flow.Collection)) []*flow.Collection {
collections := make([]*flow.Collection, n)
for i := 0; i < n; i++ {
collection := CollectionFixture(1, options...)
collections[i] = &collection
}
return collections
}
func CollectionFixture(n int, options ...func(*flow.Collection)) flow.Collection {
transactions := make([]*flow.TransactionBody, 0, n)
for i := 0; i < n; i++ {
tx := TransactionFixture()
transactions = append(transactions, &tx.TransactionBody)
}
col := flow.Collection{Transactions: transactions}
for _, opt := range options {
opt(&col)
}
return col
}
func FixedReferenceBlockID() flow.Identifier {
blockID := flow.Identifier{}
blockID[0] = byte(1)
return blockID
}
func CompleteCollectionFixture() *entity.CompleteCollection {
txBody := TransactionBodyFixture()
return &entity.CompleteCollection{
Guarantee: &flow.CollectionGuarantee{
CollectionID: flow.Collection{Transactions: []*flow.TransactionBody{&txBody}}.ID(),
Signature: SignatureFixture(),
ReferenceBlockID: FixedReferenceBlockID(),
SignerIndices: SignerIndicesFixture(1),
},
Transactions: []*flow.TransactionBody{&txBody},
}
}
func CompleteCollectionFromTransactions(txs []*flow.TransactionBody) *entity.CompleteCollection {
return &entity.CompleteCollection{
Guarantee: &flow.CollectionGuarantee{
CollectionID: flow.Collection{Transactions: txs}.ID(),
Signature: SignatureFixture(),
ReferenceBlockID: IdentifierFixture(),
SignerIndices: SignerIndicesFixture(3),
},
Transactions: txs,
}
}
func ExecutableBlockFixture(
collectionsSignerIDs [][]flow.Identifier,
startState *flow.StateCommitment,
) *entity.ExecutableBlock {
header := BlockHeaderFixture()
return ExecutableBlockFixtureWithParent(collectionsSignerIDs, header, startState)
}
func ExecutableBlockFixtureWithParent(
collectionsSignerIDs [][]flow.Identifier,
parent *flow.Header,
startState *flow.StateCommitment,
) *entity.ExecutableBlock {
completeCollections := make(map[flow.Identifier]*entity.CompleteCollection, len(collectionsSignerIDs))
block := BlockWithParentFixture(parent)
block.Payload.Guarantees = nil
for range collectionsSignerIDs {
completeCollection := CompleteCollectionFixture()
block.Payload.Guarantees = append(block.Payload.Guarantees, completeCollection.Guarantee)
completeCollections[completeCollection.Guarantee.CollectionID] = completeCollection
}
block.Header.PayloadHash = block.Payload.Hash()
executableBlock := &entity.ExecutableBlock{
Block: block,
CompleteCollections: completeCollections,
StartState: startState,
}
return executableBlock
}
func ExecutableBlockFromTransactions(
chain flow.ChainID,
txss [][]*flow.TransactionBody,
) *entity.ExecutableBlock {
completeCollections := make(map[flow.Identifier]*entity.CompleteCollection, len(txss))
blockHeader := BlockHeaderFixtureOnChain(chain)
block := *BlockWithParentFixture(blockHeader)
block.Payload.Guarantees = nil
for _, txs := range txss {
cc := CompleteCollectionFromTransactions(txs)
block.Payload.Guarantees = append(block.Payload.Guarantees, cc.Guarantee)
completeCollections[cc.Guarantee.CollectionID] = cc
}
block.Header.PayloadHash = block.Payload.Hash()
executableBlock := &entity.ExecutableBlock{
Block: &block,
CompleteCollections: completeCollections,
}
// Preload the id
executableBlock.ID()
return executableBlock
}
func WithExecutorID(executorID flow.Identifier) func(*flow.ExecutionReceipt) {
return func(er *flow.ExecutionReceipt) {
er.ExecutorID = executorID
}
}
func WithResult(result *flow.ExecutionResult) func(*flow.ExecutionReceipt) {
return func(receipt *flow.ExecutionReceipt) {
receipt.ExecutionResult = *result
}
}
func ExecutionReceiptFixture(opts ...func(*flow.ExecutionReceipt)) *flow.ExecutionReceipt {
receipt := &flow.ExecutionReceipt{
ExecutorID: IdentifierFixture(),
ExecutionResult: *ExecutionResultFixture(),
Spocks: nil,
ExecutorSignature: SignatureFixture(),
}
for _, apply := range opts {
apply(receipt)
}
return receipt
}
func ReceiptForBlockFixture(block *flow.Block) *flow.ExecutionReceipt {
return ReceiptForBlockExecutorFixture(block, IdentifierFixture())
}
func ReceiptForBlockExecutorFixture(
block *flow.Block,
executor flow.Identifier,
) *flow.ExecutionReceipt {
result := ExecutionResultFixture(WithBlock(block))
receipt := ExecutionReceiptFixture(WithResult(result), WithExecutorID(executor))
return receipt
}
func ReceiptsForBlockFixture(
block *flow.Block,
ids []flow.Identifier,
) []*flow.ExecutionReceipt {
result := ExecutionResultFixture(WithBlock(block))
var ers []*flow.ExecutionReceipt
for _, id := range ids {
ers = append(ers, ExecutionReceiptFixture(WithResult(result), WithExecutorID(id)))
}
return ers
}
func WithPreviousResult(prevResult flow.ExecutionResult) func(*flow.ExecutionResult) {
return func(result *flow.ExecutionResult) {
result.PreviousResultID = prevResult.ID()
finalState, err := prevResult.FinalStateCommitment()
if err != nil {
panic("missing final state commitment")
}
result.Chunks[0].StartState = finalState
}
}
func WithBlock(block *flow.Block) func(*flow.ExecutionResult) {
chunks := 1 // tailing chunk is always system chunk
var previousResultID flow.Identifier
if block.Payload != nil {
chunks += len(block.Payload.Guarantees)
}
blockID := block.ID()
return func(result *flow.ExecutionResult) {
startState := result.Chunks[0].StartState // retain previous start state in case it was user-defined
result.BlockID = blockID
result.Chunks = ChunkListFixture(uint(chunks), blockID)
result.Chunks[0].StartState = startState // set start state to value before update
result.PreviousResultID = previousResultID
}
}
func WithChunks(n uint) func(*flow.ExecutionResult) {
return func(result *flow.ExecutionResult) {
result.Chunks = ChunkListFixture(n, result.BlockID)
}
}
func ExecutionResultListFixture(
n int,
opts ...func(*flow.ExecutionResult),
) []*flow.ExecutionResult {
results := make([]*flow.ExecutionResult, 0, n)
for i := 0; i < n; i++ {
results = append(results, ExecutionResultFixture(opts...))
}
return results
}
func WithExecutionResultBlockID(blockID flow.Identifier) func(*flow.ExecutionResult) {
return func(result *flow.ExecutionResult) {
result.BlockID = blockID
for _, chunk := range result.Chunks {
chunk.BlockID = blockID
}
}
}
func WithFinalState(commit flow.StateCommitment) func(*flow.ExecutionResult) {
return func(result *flow.ExecutionResult) {
result.Chunks[len(result.Chunks)-1].EndState = commit
}
}
func WithServiceEvents(n int) func(result *flow.ExecutionResult) {
return func(result *flow.ExecutionResult) {
result.ServiceEvents = ServiceEventsFixture(n)
}
}
func WithExecutionDataID(id flow.Identifier) func(result *flow.ExecutionResult) {
return func(result *flow.ExecutionResult) {
result.ExecutionDataID = id
}
}
func ServiceEventsFixture(n int) flow.ServiceEventList {
sel := make(flow.ServiceEventList, n)
for i := 0; i < n; i++ {
switch i % 3 {
case 0:
sel[i] = EpochCommitFixture().ServiceEvent()
case 1:
sel[i] = EpochSetupFixture().ServiceEvent()
case 2:
sel[i] = VersionBeaconFixture().ServiceEvent()
}
}
return sel
}
func ExecutionResultFixture(opts ...func(*flow.ExecutionResult)) *flow.ExecutionResult {
blockID := IdentifierFixture()
result := &flow.ExecutionResult{
PreviousResultID: IdentifierFixture(),
BlockID: IdentifierFixture(),
Chunks: ChunkListFixture(2, blockID),
ExecutionDataID: IdentifierFixture(),
}
for _, apply := range opts {
apply(result)
}
return result
}
func WithApproverID(approverID flow.Identifier) func(*flow.ResultApproval) {
return func(ra *flow.ResultApproval) {
ra.Body.ApproverID = approverID
}
}
func WithAttestationBlock(block *flow.Block) func(*flow.ResultApproval) {
return func(ra *flow.ResultApproval) {
ra.Body.Attestation.BlockID = block.ID()
}
}
func WithExecutionResultID(id flow.Identifier) func(*flow.ResultApproval) {
return func(ra *flow.ResultApproval) {
ra.Body.ExecutionResultID = id
}
}
func WithBlockID(id flow.Identifier) func(*flow.ResultApproval) {
return func(ra *flow.ResultApproval) {
ra.Body.BlockID = id
}
}
func WithChunk(chunkIdx uint64) func(*flow.ResultApproval) {
return func(approval *flow.ResultApproval) {
approval.Body.ChunkIndex = chunkIdx
}
}
func ResultApprovalFixture(opts ...func(*flow.ResultApproval)) *flow.ResultApproval {
attestation := flow.Attestation{
BlockID: IdentifierFixture(),
ExecutionResultID: IdentifierFixture(),
ChunkIndex: uint64(0),
}
approval := flow.ResultApproval{
Body: flow.ResultApprovalBody{
Attestation: attestation,
ApproverID: IdentifierFixture(),
AttestationSignature: SignatureFixture(),
Spock: nil,
},
VerifierSignature: SignatureFixture(),
}
for _, apply := range opts {
apply(&approval)
}
return &approval
}
func AttestationFixture() *flow.Attestation {
return &flow.Attestation{
BlockID: IdentifierFixture(),
ExecutionResultID: IdentifierFixture(),
ChunkIndex: uint64(0),
}
}
func StateCommitmentFixture() flow.StateCommitment {
var state flow.StateCommitment
_, _ = crand.Read(state[:])
return state
}
func StateCommitmentPointerFixture() *flow.StateCommitment {
state := StateCommitmentFixture()
return &state
}
func HashFixture(size int) hash.Hash {
hash := make(hash.Hash, size)
for i := 0; i < size; i++ {
hash[i] = byte(i)
}
return hash
}
func IdentifierListFixture(n int) flow.IdentifierList {
list := make([]flow.Identifier, n)
for i := 0; i < n; i++ {
list[i] = IdentifierFixture()
}
return list
}
func IdentifierFixture() flow.Identifier {
var id flow.Identifier
_, _ = crand.Read(id[:])
return id
}
func SignerIndicesFixture(n int) []byte {
indices := bitutils.MakeBitVector(10)
for i := 0; i < n; i++ {
bitutils.SetBit(indices, 1)
}
return indices
}
func SignerIndicesByIndices(n int, indices []int) []byte {
signers := bitutils.MakeBitVector(n)
for _, i := range indices {
bitutils.SetBit(signers, i)
}
return signers
}
// WithRole adds a role to an identity fixture.
func WithRole(role flow.Role) func(*flow.Identity) {
return func(identity *flow.Identity) {
identity.Role = role
}
}
// WithWeight sets the weight on an identity fixture.
func WithWeight(weight uint64) func(*flow.Identity) {
return func(identity *flow.Identity) {
identity.Weight = weight
}
}
func WithEjected(ejected bool) func(*flow.Identity) {
return func(identity *flow.Identity) {
identity.Ejected = ejected
}
}
// WithAddress sets the network address of identity fixture.
func WithAddress(address string) func(*flow.Identity) {
return func(identity *flow.Identity) {
identity.Address = address
}
}
// WithNetworkingKey sets the networking public key of identity fixture.
func WithNetworkingKey(key crypto.PublicKey) func(*flow.Identity) {
return func(identity *flow.Identity) {
identity.NetworkPubKey = key
}
}
func RandomBytes(n int) []byte {
b := make([]byte, n)
read, err := crand.Read(b)
if err != nil {
panic("cannot read random bytes")
}
if read != n {
panic(fmt.Errorf("cannot read enough random bytes (got %d of %d)", read, n))