/
mockrt.go
1152 lines (997 loc) · 33.2 KB
/
mockrt.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 mock
import (
"bytes"
"context"
"fmt"
"reflect"
goruntime "runtime"
"runtime/debug"
"strings"
"testing"
addr "github.com/chenjianmei111/go-address"
"github.com/chenjianmei111/go-state-types/abi"
"github.com/chenjianmei111/go-state-types/big"
"github.com/chenjianmei111/go-state-types/cbor"
"github.com/chenjianmei111/go-state-types/crypto"
"github.com/chenjianmei111/go-state-types/exitcode"
"github.com/chenjianmei111/go-state-types/network"
"github.com/chenjianmei111/go-state-types/rt"
cid "github.com/ipfs/go-cid"
mh "github.com/multiformats/go-multihash"
"github.com/chenjianmei111/specs-actors/v2/actors/builtin"
"github.com/chenjianmei111/specs-actors/v2/actors/builtin/exported"
"github.com/chenjianmei111/specs-actors/v2/actors/runtime"
"github.com/chenjianmei111/specs-actors/v2/actors/runtime/proof"
"github.com/chenjianmei111/specs-actors/v2/actors/util/adt"
"github.com/chenjianmei111/specs-actors/v2/support/ipld"
)
// A mock runtime for unit testing of actors in isolation.
// The mock allows direct specification of the runtime context as observable by an actor, supports
// the storage interface, and mocks out side-effect-inducing calls.
type Runtime struct {
// Execution context
ctx context.Context
epoch abi.ChainEpoch
networkVersion network.Version
receiver addr.Address
caller addr.Address
callerType cid.Cid
miner addr.Address
valueReceived abi.TokenAmount
idAddresses map[addr.Address]addr.Address
actorCodeCIDs map[addr.Address]cid.Cid
newActorAddr addr.Address
circulatingSupply abi.TokenAmount
// Actor state
state cid.Cid
balance abi.TokenAmount
// VM implementation
store map[cid.Cid][]byte
inCall bool
inTransaction bool
// Maps (references to) loaded state objs to their expected cid.
// Used for detecting modifications to state outside of transactions.
stateUsedObjs map[cbor.Marshaler]cid.Cid
// Syscalls
hashfunc func(data []byte) [32]byte
// Expectations
t testing.TB
expectValidateCallerAny bool
expectValidateCallerAddr []addr.Address
expectValidateCallerType []cid.Cid
expectRandomnessBeacon []*expectRandomness
expectRandomnessTickets []*expectRandomness
expectSends []*expectedMessage
expectVerifySigs []*expectVerifySig
expectCreateActor *expectCreateActor
expectVerifySeal *expectVerifySeal
expectComputeUnsealedSectorCID *expectComputeUnsealedSectorCID
expectVerifyPoSt *expectVerifyPoSt
expectVerifyConsensusFault *expectVerifyConsensusFault
expectDeleteActor *addr.Address
expectBatchVerifySeals *expectBatchVerifySeals
logs []string
// Gas charged explicitly through rt.ChargeGas. Note: most charges are implicit
gasCharged int64
}
type expectBatchVerifySeals struct {
in map[addr.Address][]proof.SealVerifyInfo
out map[addr.Address][]bool
err error
}
type expectRandomness struct {
// Expected parameters.
tag crypto.DomainSeparationTag
epoch abi.ChainEpoch
entropy []byte
// Result.
out abi.Randomness
}
type expectedMessage struct {
// expectedMessage values
to addr.Address
method abi.MethodNum
params cbor.Marshaler
value abi.TokenAmount
// returns from applying expectedMessage
sendReturn cbor.Er
exitCode exitcode.ExitCode
}
type expectVerifySig struct {
// Expected arguments
sig crypto.Signature
signer addr.Address
plaintext []byte
// Result
result error
}
type expectVerifySeal struct {
seal proof.SealVerifyInfo
result error
}
type expectComputeUnsealedSectorCID struct {
reg abi.RegisteredSealProof
pieces []abi.PieceInfo
cid cid.Cid
resultErr error
}
type expectVerifyPoSt struct {
post proof.WindowPoStVerifyInfo
result error
}
func (m *expectedMessage) Equal(to addr.Address, method abi.MethodNum, params cbor.Marshaler, value abi.TokenAmount) bool {
// avoid nil vs. zero/empty discrepancies that would disappear in serialization
paramBuf1 := new(bytes.Buffer)
if m.params != nil {
m.params.MarshalCBOR(paramBuf1) // nolint: errcheck
}
paramBuf2 := new(bytes.Buffer)
if params != nil {
params.MarshalCBOR(paramBuf2) // nolint: errcheck
}
return m.to == to && m.method == method && m.value.Equals(value) && bytes.Equal(paramBuf1.Bytes(), paramBuf2.Bytes())
}
func (m *expectedMessage) String() string {
return fmt.Sprintf("to: %v method: %v value: %v params: %v sendReturn: %v exitCode: %v", m.to, m.method, m.value, m.params, m.sendReturn, m.exitCode)
}
type expectCreateActor struct {
// Expected parameters
codeId cid.Cid
address addr.Address
}
type expectVerifyConsensusFault struct {
requireCorrectInput bool
BlockHeader1 []byte
BlockHeader2 []byte
BlockHeaderExtra []byte
Fault *runtime.ConsensusFault
Err error
}
var _ runtime.Runtime = &Runtime{}
var _ runtime.StateHandle = &Runtime{}
var typeOfRuntimeInterface = reflect.TypeOf((*runtime.Runtime)(nil)).Elem()
var typeOfCborUnmarshaler = reflect.TypeOf((*cbor.Unmarshaler)(nil)).Elem()
var typeOfCborMarshaler = reflect.TypeOf((*cbor.Marshaler)(nil)).Elem()
///// Implementation of the runtime API /////
func (rt *Runtime) NetworkVersion() network.Version {
return rt.networkVersion
}
func (rt *Runtime) CurrEpoch() abi.ChainEpoch {
rt.requireInCall()
return rt.epoch
}
func (rt *Runtime) ValidateImmediateCallerAcceptAny() {
rt.requireInCall()
if !rt.expectValidateCallerAny {
rt.failTest("unexpected validate-caller-any")
}
rt.expectValidateCallerAny = false
}
func (rt *Runtime) ValidateImmediateCallerIs(addrs ...addr.Address) {
rt.requireInCall()
rt.checkArgument(len(addrs) > 0, "addrs must be non-empty")
// Check and clear expectations.
if len(rt.expectValidateCallerAddr) == 0 {
rt.failTest("unexpected validate caller addrs")
return
}
if !reflect.DeepEqual(rt.expectValidateCallerAddr, addrs) {
rt.failTest("unexpected validate caller addrs %v, expected %+v", addrs, rt.expectValidateCallerAddr)
return
}
defer func() {
rt.expectValidateCallerAddr = nil
}()
// Implement method.
for _, expected := range addrs {
if rt.caller == expected {
return
}
}
rt.Abortf(exitcode.SysErrForbidden, "caller address %v forbidden, allowed: %v", rt.caller, addrs)
}
func (rt *Runtime) ValidateImmediateCallerType(types ...cid.Cid) {
rt.requireInCall()
rt.checkArgument(len(types) > 0, "types must be non-empty")
// Check and clear expectations.
if len(rt.expectValidateCallerType) == 0 {
rt.failTest("unexpected validate caller code")
}
if !reflect.DeepEqual(rt.expectValidateCallerType, types) {
rt.failTest("unexpected validate caller code %v, expected %+v", types, rt.expectValidateCallerType)
}
defer func() {
rt.expectValidateCallerType = nil
}()
// Implement method.
for _, expected := range types {
if rt.callerType.Equals(expected) {
return
}
}
rt.Abortf(exitcode.SysErrForbidden, "caller type %v forbidden, allowed: %v", rt.callerType, types)
}
func (rt *Runtime) CurrentBalance() abi.TokenAmount {
rt.requireInCall()
return rt.balance
}
func (rt *Runtime) ResolveAddress(address addr.Address) (ret addr.Address, ok bool) {
rt.requireInCall()
if address.Protocol() == addr.ID {
return address, true
}
resolved, ok := rt.idAddresses[address]
return resolved, ok
}
func (rt *Runtime) GetIdAddr(raw addr.Address) (addr.Address, bool) {
if raw.Protocol() == addr.ID {
return raw, true
}
a, found := rt.idAddresses[raw]
return a, found
}
func (rt *Runtime) GetActorCodeCID(addr addr.Address) (ret cid.Cid, ok bool) {
rt.requireInCall()
ret, ok = rt.actorCodeCIDs[addr]
return
}
func (rt *Runtime) GetRandomnessFromBeacon(tag crypto.DomainSeparationTag, epoch abi.ChainEpoch, entropy []byte) abi.Randomness {
rt.requireInCall()
if len(rt.expectRandomnessBeacon) == 0 {
rt.failTestNow("unexpected call to get randomness for tag %v, epoch %v", tag, epoch)
}
if epoch > rt.epoch {
rt.failTestNow("attempt to get randomness from future\n"+
" requested epoch: %d greater than current epoch %d\n", epoch, rt.epoch)
}
exp := rt.expectRandomnessBeacon[0]
if tag != exp.tag || epoch != exp.epoch || !bytes.Equal(entropy, exp.entropy) {
rt.failTest("unexpected get randomness\n"+
" tag: %d, epoch: %d, entropy: %v\n"+
"expected tag: %d, epoch: %d, entropy: %v", tag, epoch, entropy, exp.tag, exp.epoch, exp.entropy)
}
defer func() {
rt.expectRandomnessBeacon = rt.expectRandomnessBeacon[1:]
}()
return exp.out
}
func (rt *Runtime) GetRandomnessFromTickets(tag crypto.DomainSeparationTag, epoch abi.ChainEpoch, entropy []byte) abi.Randomness {
rt.requireInCall()
if len(rt.expectRandomnessTickets) == 0 {
rt.failTestNow("unexpected call to get randomness for tag %v, epoch %v", tag, epoch)
}
if epoch > rt.epoch {
rt.failTestNow("attempt to get randomness from future\n"+
" requested epoch: %d greater than current epoch %d\n", epoch, rt.epoch)
}
exp := rt.expectRandomnessTickets[0]
if tag != exp.tag || epoch != exp.epoch || !bytes.Equal(entropy, exp.entropy) {
rt.failTest("unexpected get randomness\n"+
" tag: %d, epoch: %d, entropy: %v\n"+
"expected tag: %d, epoch: %d, entropy: %v", tag, epoch, entropy, exp.tag, exp.epoch, exp.entropy)
}
defer func() {
rt.expectRandomnessTickets = rt.expectRandomnessTickets[1:]
}()
return exp.out
}
func (rt *Runtime) Send(toAddr addr.Address, methodNum abi.MethodNum, params cbor.Marshaler, value abi.TokenAmount, out cbor.Er) exitcode.ExitCode {
rt.requireInCall()
if rt.inTransaction {
rt.Abortf(exitcode.SysErrorIllegalActor, "side-effect within transaction")
}
if len(rt.expectSends) == 0 {
rt.failTestNow("unexpected send to: %v method: %v, value: %v, params: %v", toAddr, methodNum, value, params)
}
exp := rt.expectSends[0]
if !exp.Equal(toAddr, methodNum, params, value) {
toName := "unknown"
toMeth := "unknown"
expToName := "unknown"
expToMeth := "unknown"
if code, ok := rt.GetActorCodeCID(toAddr); ok && builtin.IsBuiltinActor(code) {
toName = builtin.ActorNameByCode(code)
toMeth = getMethodName(code, methodNum)
}
if code, ok := rt.GetActorCodeCID(exp.to); ok && builtin.IsBuiltinActor(code) {
expToName = builtin.ActorNameByCode(code)
expToMeth = getMethodName(code, exp.method)
}
rt.failTestNow("unexpected send\n"+
" to: %s (%s) method: %d (%s) value: %v params: %v\n"+
"Expected to: %s (%s) method: %d (%s) value: %v params: %v",
toAddr, toName, methodNum, toMeth, value, params, exp.to, expToName, exp.method, expToMeth, exp.value, exp.params)
}
if value.GreaterThan(rt.balance) {
rt.Abortf(exitcode.SysErrSenderStateInvalid, "cannot send value: %v exceeds balance: %v", value, rt.balance)
}
// pop the expectedMessage from the queue and modify the mockrt balance to reflect the send.
defer func() {
rt.expectSends = rt.expectSends[1:]
rt.balance = big.Sub(rt.balance, value)
}()
// populate the output argument
var buf bytes.Buffer
err := exp.sendReturn.MarshalCBOR(&buf)
if err != nil {
rt.failTestNow("error serializing expected send return: %v", err)
}
err = out.UnmarshalCBOR(&buf)
if err != nil {
rt.failTestNow("error deserializing send return bytes to output param: %v", err)
}
return exp.exitCode
}
func (rt *Runtime) NewActorAddress() addr.Address {
rt.requireInCall()
if rt.newActorAddr == addr.Undef {
rt.failTestNow("unexpected call to new actor address")
}
defer func() { rt.newActorAddr = addr.Undef }()
return rt.newActorAddr
}
func (rt *Runtime) CreateActor(codeId cid.Cid, address addr.Address) {
rt.requireInCall()
if rt.inTransaction {
rt.Abortf(exitcode.SysErrorIllegalActor, "side-effect within transaction")
}
exp := rt.expectCreateActor
if exp != nil {
if !exp.codeId.Equals(codeId) || exp.address != address {
rt.failTest("unexpected create actor, code: %s, address: %s; expected code: %s, address: %s",
codeId, address, exp.codeId, exp.address)
}
defer func() {
rt.expectCreateActor = nil
}()
return
}
rt.failTestNow("unexpected call to create actor")
}
func (rt *Runtime) DeleteActor(addr addr.Address) {
rt.requireInCall()
if rt.inTransaction {
rt.Abortf(exitcode.SysErrorIllegalActor, "side-effect within transaction")
}
if rt.expectDeleteActor == nil {
rt.failTestNow("unexpected call to delete actor %s", addr.String())
}
if *rt.expectDeleteActor != addr {
rt.failTestNow("attempt to delete wrong actor. Expected %s, got %s.", rt.expectDeleteActor.String(), addr.String())
}
rt.expectDeleteActor = nil
}
func (rt *Runtime) TotalFilCircSupply() abi.TokenAmount {
return rt.circulatingSupply
}
func (rt *Runtime) Abortf(errExitCode exitcode.ExitCode, msg string, args ...interface{}) {
rt.requireInCall()
rt.t.Logf("Mock Runtime Abort ExitCode: %v Reason: %s", errExitCode, fmt.Sprintf(msg, args...))
panic(abort{errExitCode, fmt.Sprintf(msg, args...)})
}
func (rt *Runtime) Context() context.Context {
// requireInCall omitted because it makes using this mock runtime as a store awkward.
return rt.ctx
}
func (rt *Runtime) StartSpan(_ string) func() {
rt.requireInCall()
return func() {}
}
func (rt *Runtime) checkArgument(predicate bool, msg string, args ...interface{}) {
if !predicate {
rt.Abortf(exitcode.SysErrorIllegalArgument, msg, args...)
}
}
///// Store implementation /////
// Gets raw data from the state. This function will extract inline data from the
// CID to better mimic what filecoin implementations should do.
func (rt *Runtime) get(c cid.Cid) ([]byte, bool) {
prefix := c.Prefix()
if prefix.Codec != cid.DagCBOR {
rt.Abortf(exitcode.ErrSerialization, "tried to fetch a non-cbor object: %s", c)
}
var data []byte
if prefix.MhType == mh.IDENTITY {
decoded, err := mh.Decode(c.Hash())
if err != nil {
rt.Abortf(exitcode.ErrSerialization, "failed to parse identity cid %s: %s", c, err)
}
data = decoded.Digest
} else if stored, found := rt.store[c]; found {
data = stored
} else {
return nil, false
}
return data, true
}
// Puts raw data into the state, but only if it's not "inlined" into the CID.
func (rt *Runtime) put(c cid.Cid, data []byte) {
if c.Prefix().MhType != mh.IDENTITY {
rt.store[c] = data
}
}
func (rt *Runtime) StoreGet(c cid.Cid, o cbor.Unmarshaler) bool {
// requireInCall omitted because it makes using this mock runtime as a store awkward.
data, found := rt.get(c)
if found {
err := o.UnmarshalCBOR(bytes.NewReader(data))
if err != nil {
rt.Abortf(exitcode.ErrSerialization, err.Error())
}
}
return found
}
func (rt *Runtime) StorePut(o cbor.Marshaler) cid.Cid {
// requireInCall omitted because it makes using this mock runtime as a store awkward.
key, data, err := ipld.MarshalCBOR(o)
if err != nil {
rt.Abortf(exitcode.ErrSerialization, err.Error())
}
rt.put(key, data)
return key
}
///// Message implementation /////
func (rt *Runtime) BlockMiner() addr.Address {
return rt.miner
}
func (rt *Runtime) Caller() addr.Address {
return rt.caller
}
func (rt *Runtime) Receiver() addr.Address {
return rt.receiver
}
func (rt *Runtime) ValueReceived() abi.TokenAmount {
return rt.valueReceived
}
///// State handle implementation /////
func (rt *Runtime) StateCreate(obj cbor.Marshaler) {
if rt.state.Defined() {
rt.Abortf(exitcode.SysErrorIllegalActor, "state already constructed")
}
rt.state = rt.StorePut(obj)
// Track the expected CID of the object.
rt.stateUsedObjs[obj] = rt.state
}
func (rt *Runtime) StateReadonly(st cbor.Unmarshaler) {
found := rt.StoreGet(rt.state, st)
if !found {
panic(fmt.Sprintf("actor state not found: %v", rt.state))
}
// Track the expected CID of the object.
rt.stateUsedObjs[st.(cbor.Marshaler)] = rt.state
}
func (rt *Runtime) StateTransaction(st cbor.Er, f func()) {
if rt.inTransaction {
rt.Abortf(exitcode.SysErrorIllegalActor, "nested transaction")
}
rt.checkStateObjectsUnmodified()
rt.StateReadonly(st)
rt.inTransaction = true
defer func() { rt.inTransaction = false }()
f()
rt.state = rt.StorePut(st)
// Track the expected CID of the object.
rt.stateUsedObjs[st] = rt.state
}
///// Syscalls implementation /////
func (rt *Runtime) VerifySignature(sig crypto.Signature, signer addr.Address, plaintext []byte) error {
if len(rt.expectVerifySigs) == 0 {
rt.failTest("unexpected signature verification sig: %v, signer: %s, plaintext: %v", sig, signer, plaintext)
}
exp := rt.expectVerifySigs[0]
if exp != nil {
if !exp.sig.Equals(&sig) || exp.signer != signer || !bytes.Equal(exp.plaintext, plaintext) {
rt.failTest("unexpected signature verification\n"+
" sig: %v, signer: %s, plaintext: %v\n"+
"expected sig: %v, signer: %s, plaintext: %v",
sig, signer, plaintext, exp.sig, exp.signer, exp.plaintext)
}
defer func() {
rt.expectVerifySigs = rt.expectVerifySigs[1:]
}()
return exp.result
}
rt.failTestNow("unexpected syscall to verify signature %v, signer %s, plaintext %v", sig, signer, plaintext)
return nil
}
func (rt *Runtime) HashBlake2b(data []byte) [32]byte {
return rt.hashfunc(data)
}
func (rt *Runtime) ComputeUnsealedSectorCID(reg abi.RegisteredSealProof, pieces []abi.PieceInfo) (cid.Cid, error) {
exp := rt.expectComputeUnsealedSectorCID
if exp != nil {
if !reflect.DeepEqual(exp.reg, reg) {
rt.failTest("unexpected ComputeUnsealedSectorCID proof, expected: %v, got: %v", exp.reg, reg)
}
if !reflect.DeepEqual(exp.pieces, pieces) {
rt.failTest("unexpected ComputeUnsealedSectorCID pieces, expected: %v, got: %v", exp.pieces, pieces)
}
defer func() {
rt.expectComputeUnsealedSectorCID = nil
}()
return exp.cid, exp.resultErr
}
rt.failTestNow("unexpected syscall to ComputeUnsealedSectorCID %v", reg)
return cid.Cid{}, nil
}
func (rt *Runtime) VerifySeal(seal proof.SealVerifyInfo) error {
exp := rt.expectVerifySeal
if exp != nil {
if !reflect.DeepEqual(exp.seal, seal) {
rt.failTest("unexpected seal verification\n"+
" : %v\n"+
"expected: %v",
seal, exp.seal)
}
defer func() {
rt.expectVerifySeal = nil
}()
return exp.result
}
rt.failTestNow("unexpected syscall to verify seal %v", seal)
return nil
}
func (rt *Runtime) ExpectBatchVerifySeals(in map[addr.Address][]proof.SealVerifyInfo, out map[addr.Address][]bool, err error) {
rt.expectBatchVerifySeals = &expectBatchVerifySeals{
in, out, err,
}
}
func (rt *Runtime) BatchVerifySeals(vis map[addr.Address][]proof.SealVerifyInfo) (map[addr.Address][]bool, error) {
exp := rt.expectBatchVerifySeals
if exp != nil {
if len(vis) != len(exp.in) {
rt.failTest("length mismatch, expected: %v, actual: %v", exp.in, vis)
}
for key, value := range exp.in { //nolint:nomaprange
v, ok := vis[key]
if !ok {
rt.failTest("address %v expected but not found", key)
}
if len(v) != len(value) {
rt.failTest("sector info length mismatch for address %v, \n expected: %v, \n actual: %v", key, value, v)
}
for i, info := range value {
if v[i].SealedCID != info.SealedCID {
rt.failTest("sealed cid does not match for address %v", key)
}
if v[i].UnsealedCID != info.UnsealedCID {
rt.failTest("unsealed cid does not match for address %v", key)
}
}
delete(exp.in, key)
}
if len(exp.in) != 0 {
rt.failTest("addresses in expected map absent in actual: %v", exp.in)
}
defer func() {
rt.expectBatchVerifySeals = nil
}()
return exp.out, exp.err
}
rt.failTestNow("unexpected syscall to batch verify seals with %v", vis)
return nil, nil
}
func (rt *Runtime) VerifyPoSt(vi proof.WindowPoStVerifyInfo) error {
exp := rt.expectVerifyPoSt
if exp != nil {
if !reflect.DeepEqual(exp.post, vi) {
rt.failTest("unexpected PoSt verification\n"+
" : %v\n"+
"expected: %v",
vi, exp.post)
}
defer func() {
rt.expectVerifyPoSt = nil
}()
return exp.result
}
rt.failTestNow("unexpected syscall to verify PoSt %v", vi)
return nil
}
func (rt *Runtime) VerifyConsensusFault(h1, h2, extra []byte) (*runtime.ConsensusFault, error) {
if rt.expectVerifyConsensusFault == nil {
rt.failTestNow("Unexpected syscall VerifyConsensusFault")
return nil, nil
}
if rt.expectVerifyConsensusFault.requireCorrectInput {
if !bytes.Equal(h1, rt.expectVerifyConsensusFault.BlockHeader1) {
rt.failTest("block header 1 does not equal expected block header 1 (%v != %v)", h1, rt.expectVerifyConsensusFault.BlockHeader1)
}
if !bytes.Equal(h2, rt.expectVerifyConsensusFault.BlockHeader2) {
rt.failTest("block header 2 does not equal expected block header 2 (%v != %v)", h2, rt.expectVerifyConsensusFault.BlockHeader2)
}
if !bytes.Equal(extra, rt.expectVerifyConsensusFault.BlockHeaderExtra) {
rt.failTest("block header extra does not equal expected block header extra (%v != %v)", extra, rt.expectVerifyConsensusFault.BlockHeaderExtra)
}
}
fault := rt.expectVerifyConsensusFault.Fault
err := rt.expectVerifyConsensusFault.Err
rt.expectVerifyConsensusFault = nil
return fault, err
}
func (rt *Runtime) Log(level rt.LogLevel, msg string, args ...interface{}) {
rt.logs = append(rt.logs, fmt.Sprintf(msg, args...))
}
///// Trace span implementation /////
type TraceSpan struct {
}
func (t TraceSpan) End() {
// no-op
}
type abort struct {
code exitcode.ExitCode
msg string
}
func (a abort) String() string {
return fmt.Sprintf("abort(%v): %s", a.code, a.msg)
}
///// Inspection facilities /////
func (rt *Runtime) AdtStore() adt.Store {
return adt.AsStore(rt)
}
func (rt *Runtime) StateRoot() cid.Cid {
return rt.state
}
func (rt *Runtime) GetState(o cbor.Unmarshaler) {
data, found := rt.get(rt.state)
if !found {
rt.failTestNow("can't find state at root %v", rt.state) // something internal is messed up
}
err := o.UnmarshalCBOR(bytes.NewReader(data))
if err != nil {
rt.failTestNow("error loading state: %v", err)
}
}
func (rt *Runtime) Balance() abi.TokenAmount {
return rt.balance
}
func (rt *Runtime) Epoch() abi.ChainEpoch {
return rt.epoch
}
///// Mocking facilities /////
func (rt *Runtime) SetCaller(address addr.Address, actorType cid.Cid) {
rt.caller = address
rt.callerType = actorType
rt.actorCodeCIDs[address] = actorType
}
func (rt *Runtime) SetAddressActorType(address addr.Address, actorType cid.Cid) {
rt.actorCodeCIDs[address] = actorType
}
func (rt *Runtime) SetBalance(amt abi.TokenAmount) {
rt.balance = amt
}
func (rt *Runtime) SetReceived(amt abi.TokenAmount) {
rt.valueReceived = amt
}
func (rt *Runtime) SetNetworkVersion(v network.Version) {
rt.networkVersion = v
}
func (rt *Runtime) SetEpoch(epoch abi.ChainEpoch) {
rt.epoch = epoch
}
func (rt *Runtime) ReplaceState(o cbor.Marshaler) {
rt.state = rt.StorePut(o)
}
func (rt *Runtime) SetCirculatingSupply(amt abi.TokenAmount) {
rt.circulatingSupply = amt
}
func (rt *Runtime) AddIDAddress(src addr.Address, target addr.Address) {
rt.require(target.Protocol() == addr.ID, "target must use ID address protocol")
rt.idAddresses[src] = target
}
func (rt *Runtime) SetNewActorAddress(actAddr addr.Address) {
rt.require(actAddr.Protocol() == addr.Actor, "new actor address must be protocol: Actor, got protocol: %v", actAddr.Protocol())
rt.newActorAddr = actAddr
}
func (rt *Runtime) ExpectValidateCallerAny() {
rt.expectValidateCallerAny = true
}
func (rt *Runtime) ExpectValidateCallerAddr(addrs ...addr.Address) {
rt.require(len(addrs) > 0, "addrs must be non-empty")
rt.expectValidateCallerAddr = addrs[:]
}
func (rt *Runtime) ExpectValidateCallerType(types ...cid.Cid) {
rt.require(len(types) > 0, "types must be non-empty")
rt.expectValidateCallerType = types[:]
}
func (rt *Runtime) ExpectGetRandomnessBeacon(tag crypto.DomainSeparationTag, epoch abi.ChainEpoch, entropy []byte, out abi.Randomness) {
rt.expectRandomnessBeacon = append(rt.expectRandomnessBeacon, &expectRandomness{
tag: tag,
epoch: epoch,
entropy: entropy,
out: out,
})
}
func (rt *Runtime) ExpectGetRandomnessTickets(tag crypto.DomainSeparationTag, epoch abi.ChainEpoch, entropy []byte, out abi.Randomness) {
rt.expectRandomnessTickets = append(rt.expectRandomnessTickets, &expectRandomness{
tag: tag,
epoch: epoch,
entropy: entropy,
out: out,
})
}
func (rt *Runtime) ExpectSend(toAddr addr.Address, methodNum abi.MethodNum, params cbor.Marshaler, value abi.TokenAmount, ret cbor.Er, exitCode exitcode.ExitCode) {
// Adapt nil to Empty as convenience for the caller (otherwise we would require non-nil here).
if ret == nil {
ret = abi.Empty
}
rt.expectSends = append(rt.expectSends, &expectedMessage{
to: toAddr,
method: methodNum,
params: params,
value: value,
sendReturn: ret,
exitCode: exitCode,
})
}
func (rt *Runtime) ExpectVerifySignature(sig crypto.Signature, signer addr.Address, plaintext []byte, result error) {
rt.expectVerifySigs = append(rt.expectVerifySigs, &expectVerifySig{
sig: sig,
signer: signer,
plaintext: plaintext,
result: result,
})
}
func (rt *Runtime) ExpectCreateActor(codeId cid.Cid, address addr.Address) {
rt.expectCreateActor = &expectCreateActor{
codeId: codeId,
address: address,
}
}
func (rt *Runtime) ExpectDeleteActor(beneficiary addr.Address) {
rt.expectDeleteActor = &beneficiary
}
func (rt *Runtime) SetHasher(f func(data []byte) [32]byte) {
rt.hashfunc = f
}
func (rt *Runtime) ExpectVerifySeal(seal proof.SealVerifyInfo, result error) {
rt.expectVerifySeal = &expectVerifySeal{
seal: seal,
result: result,
}
}
func (rt *Runtime) ExpectComputeUnsealedSectorCID(reg abi.RegisteredSealProof, pieces []abi.PieceInfo, cid cid.Cid, err error) {
rt.expectComputeUnsealedSectorCID = &expectComputeUnsealedSectorCID{
reg, pieces, cid, err,
}
}
func (rt *Runtime) ExpectVerifyPoSt(post proof.WindowPoStVerifyInfo, result error) {
rt.expectVerifyPoSt = &expectVerifyPoSt{
post: post,
result: result,
}
}
func (rt *Runtime) ExpectVerifyConsensusFault(h1, h2, extra []byte, result *runtime.ConsensusFault, resultErr error) {
rt.expectVerifyConsensusFault = &expectVerifyConsensusFault{
requireCorrectInput: true,
BlockHeader1: h1,
BlockHeader2: h2,
BlockHeaderExtra: extra,
Fault: result,
Err: resultErr,
}
}
// Verifies that expected calls were received, and resets all expectations.
func (rt *Runtime) Verify() {
rt.t.Helper()
if rt.expectValidateCallerAny {
rt.failTest("expected ValidateCallerAny, not received")
}
if len(rt.expectValidateCallerAddr) > 0 {
rt.failTest("missing expected ValidateCallerAddr %v", rt.expectValidateCallerAddr)
}
if len(rt.expectValidateCallerType) > 0 {
rt.failTest("missing expected ValidateCallerType %v", rt.expectValidateCallerType)
}
if len(rt.expectRandomnessBeacon) > 0 {
rt.failTest("missing expected beacon randomness %v", rt.expectRandomnessBeacon)
}
if len(rt.expectRandomnessTickets) > 0 {
rt.failTest("missing expected ticket randomness %v", rt.expectRandomnessTickets)
}
if len(rt.expectSends) > 0 {
rt.failTest("missing expected send %v", rt.expectSends)
}
if len(rt.expectVerifySigs) > 0 {
rt.failTest("missing expected verify signature %v", rt.expectVerifySigs)
}
if rt.expectCreateActor != nil {
rt.failTest("missing expected create actor with code %s, address %s",
rt.expectCreateActor.codeId, rt.expectCreateActor.address)
}
if rt.expectVerifySeal != nil {
rt.failTest("missing expected verify seal with %v", rt.expectVerifySeal.seal)
}
if rt.expectBatchVerifySeals != nil {
rt.failTest("missing expected batch verify seals with %v", rt.expectBatchVerifySeals)
}
if rt.expectComputeUnsealedSectorCID != nil {
rt.failTest("missing expected ComputeUnsealedSectorCID with %v", rt.expectComputeUnsealedSectorCID)
}
if rt.expectVerifyConsensusFault != nil {
rt.failTest("missing expected verify consensus fault")
}
if rt.expectDeleteActor != nil {
rt.failTest("missing expected delete actor with address %s", rt.expectDeleteActor.String())
}
rt.Reset()
}
// Resets expectations
func (rt *Runtime) Reset() {
rt.expectValidateCallerAny = false
rt.expectValidateCallerAddr = nil
rt.expectValidateCallerType = nil
rt.expectRandomnessBeacon = nil
rt.expectRandomnessTickets = nil
rt.expectSends = nil
rt.expectCreateActor = nil
rt.expectVerifySigs = nil
rt.expectVerifySeal = nil
rt.expectBatchVerifySeals = nil
rt.expectComputeUnsealedSectorCID = nil
}
// Calls f() expecting it to invoke Runtime.Abortf() with a specified exit code.
func (rt *Runtime) ExpectAbort(expected exitcode.ExitCode, f func()) {
rt.ExpectAbortContainsMessage(expected, "", f)
}
// Calls f() expecting it to invoke Runtime.Abortf() with a specified exit code and message.
func (rt *Runtime) ExpectAbortContainsMessage(expected exitcode.ExitCode, substr string, f func()) {
rt.t.Helper()
prevState := rt.state
defer func() {
rt.t.Helper()
r := recover()
if r == nil {
rt.failTest("expected abort with code %v but call succeeded", expected)
return
}
a, ok := r.(abort)
if !ok {
panic(r)
}
if a.code != expected {
rt.failTest("abort expected code %v, got %v %s", expected, a.code, a.msg)
}
if substr != "" {
if !strings.Contains(a.msg, substr) {
rt.failTest("abort expected message\n'%s'\nto contain\n'%s'\n", a.msg, substr)
}
}
// Roll back state change.
rt.state = prevState