This repository has been archived by the owner on Jun 6, 2023. It is now read-only.
/
vm.go
711 lines (604 loc) · 18.5 KB
/
vm.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
package vm
import (
"bytes"
"context"
"fmt"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/go-state-types/cbor"
"github.com/filecoin-project/go-state-types/exitcode"
"github.com/filecoin-project/go-state-types/network"
"github.com/filecoin-project/go-state-types/rt"
vm2 "github.com/filecoin-project/specs-actors/v2/support/vm"
"github.com/ipfs/go-cid"
"golang.org/x/xerrors"
"github.com/filecoin-project/specs-actors/v6/actors/builtin"
init_ "github.com/filecoin-project/specs-actors/v6/actors/builtin/init"
"github.com/filecoin-project/specs-actors/v6/actors/runtime"
"github.com/filecoin-project/specs-actors/v6/actors/states"
"github.com/filecoin-project/specs-actors/v6/actors/util/adt"
)
// VM is a simplified message execution framework for the purposes of testing inter-actor communication.
// The VM maintains actor state and can be used to simulate message validation for a single block or tipset.
// The VM does not track gas charges, provide working syscalls, validate message nonces and many other things
// that a compliant VM needs to do.
type VM struct {
ctx context.Context
store adt.Store
currentEpoch abi.ChainEpoch
networkVersion network.Version
ActorImpls ActorImplLookup
stateRoot cid.Cid // The last committed root.
actors *adt.Map // The current (not necessarily committed) root node.
actorsDirty bool
emptyObject cid.Cid
logs []string
invocationStack []*Invocation
invocations []*Invocation
statsSource StatsSource
statsByMethod StatsByCall
circSupply abi.TokenAmount
gasPrices Pricelist
}
// VM types
// type ActorImplLookup map[cid.Cid]runtime.VMActor
type ActorImplLookup vm2.ActorImplLookup
type InternalMessage struct {
from address.Address
to address.Address
value abi.TokenAmount
method abi.MethodNum
params interface{}
}
type ChainMessage struct {
Version uint64
To address.Address
From address.Address
Nonce uint64
Value abi.TokenAmount
GasLimit int64
GasFeeCap abi.TokenAmount
GasPremium abi.TokenAmount
Method abi.MethodNum
Params []byte
}
func makeChainMessage(from, to address.Address, nonce uint64, value abi.TokenAmount, method abi.MethodNum, params interface{}) (*ChainMessage, error) {
var buf bytes.Buffer
if params == nil {
if err := abi.Empty.MarshalCBOR(&buf); err != nil {
return nil, err
}
} else {
if err := params.(cbor.Er).MarshalCBOR(&buf); err != nil {
return nil, err
}
}
return &ChainMessage{
Version: 0,
From: from,
To: to,
Nonce: nonce,
Value: value,
GasLimit: defaultGasLimit,
GasFeeCap: big.Zero(),
GasPremium: big.Zero(),
Method: method,
Params: buf.Bytes(),
}, nil
}
type Invocation struct {
Msg *InternalMessage
Exitcode exitcode.ExitCode
Ret cbor.Marshaler
SubInvocations []*Invocation
}
// NewVM creates a new runtime for executing messages.
func NewVM(ctx context.Context, actorImpls ActorImplLookup, store adt.Store) *VM {
actors, err := adt.MakeEmptyMap(store, builtin.DefaultHamtBitwidth)
if err != nil {
panic(err)
}
actorRoot, err := actors.Root()
if err != nil {
panic(err)
}
emptyObject, err := store.Put(context.TODO(), []struct{}{})
if err != nil {
panic(err)
}
return &VM{
ctx: ctx,
ActorImpls: actorImpls,
store: store,
actors: actors,
stateRoot: actorRoot,
actorsDirty: false,
emptyObject: emptyObject,
networkVersion: network.VersionMax,
statsByMethod: make(StatsByCall),
circSupply: big.Mul(big.NewInt(1e9), big.NewInt(1e18)),
gasPrices: &v13PriceList,
}
}
// NewVM creates a new runtime for executing messages.
func NewVMAtEpoch(ctx context.Context, actorImpls ActorImplLookup, store adt.Store, stateRoot cid.Cid, epoch abi.ChainEpoch) (*VM, error) {
actors, err := adt.AsMap(store, stateRoot, builtin.DefaultHamtBitwidth)
if err != nil {
return nil, err
}
emptyObject, err := store.Put(context.TODO(), []struct{}{})
if err != nil {
panic(err)
}
return &VM{
ctx: ctx,
ActorImpls: actorImpls,
currentEpoch: epoch,
store: store,
actors: actors,
stateRoot: stateRoot,
actorsDirty: false,
emptyObject: emptyObject,
networkVersion: network.VersionMax,
statsByMethod: make(StatsByCall),
circSupply: big.Mul(big.NewInt(1e9), big.NewInt(1e18)),
gasPrices: &v13PriceList,
}, nil
}
func (vm *VM) WithEpoch(epoch abi.ChainEpoch) (*VM, error) {
_, err := vm.checkpoint()
if err != nil {
return nil, err
}
actors, err := adt.AsMap(vm.store, vm.stateRoot, builtin.DefaultHamtBitwidth)
if err != nil {
return nil, err
}
return &VM{
ctx: vm.ctx,
ActorImpls: vm.ActorImpls,
store: vm.store,
actors: actors,
stateRoot: vm.stateRoot,
actorsDirty: false,
emptyObject: vm.emptyObject,
currentEpoch: epoch,
networkVersion: vm.networkVersion,
statsSource: vm.statsSource,
statsByMethod: make(StatsByCall),
circSupply: vm.circSupply,
gasPrices: &v13PriceList,
}, nil
}
func (vm *VM) WithNetworkVersion(nv network.Version) (*VM, error) {
_, err := vm.checkpoint()
if err != nil {
return nil, err
}
actors, err := adt.AsMap(vm.store, vm.stateRoot, builtin.DefaultHamtBitwidth)
if err != nil {
return nil, err
}
return &VM{
ctx: vm.ctx,
ActorImpls: vm.ActorImpls,
store: vm.store,
actors: actors,
stateRoot: vm.stateRoot,
actorsDirty: false,
emptyObject: vm.emptyObject,
currentEpoch: vm.currentEpoch,
networkVersion: nv,
statsSource: vm.statsSource,
statsByMethod: make(StatsByCall),
circSupply: vm.circSupply,
gasPrices: &v13PriceList,
}, nil
}
func (vm *VM) rollback(root cid.Cid) error {
var err error
vm.actors, err = adt.AsMap(vm.store, root, builtin.DefaultHamtBitwidth)
if err != nil {
return xerrors.Errorf("failed to load node for %s: %w", root, err)
}
// reset the root node
vm.stateRoot = root
vm.actorsDirty = false
return nil
}
func (vm *VM) GetActor(a address.Address) (*states.Actor, bool, error) {
na, found := vm.NormalizeAddress(a)
if !found {
return nil, false, nil
}
var act states.Actor
found, err := vm.actors.Get(abi.AddrKey(na), &act)
return &act, found, err
}
// SetActor sets the the actor to the given value whether it previously existed or not.
//
// This method will not check if the actor previously existed, it will blindly overwrite it.
func (vm *VM) setActor(_ context.Context, key address.Address, a *states.Actor) error {
if err := vm.actors.Put(abi.AddrKey(key), a); err != nil {
return xerrors.Errorf("setting actor in state tree failed: %w", err)
}
vm.actorsDirty = true
return nil
}
// SetActorState stores the state and updates the addressed actor
func (vm *VM) SetActorState(ctx context.Context, key address.Address, state cbor.Marshaler) error {
stateCid, err := vm.store.Put(ctx, state)
if err != nil {
return err
}
a, found, err := vm.GetActor(key)
if err != nil {
return err
}
if !found {
return xerrors.Errorf("could not find actor %s to set state", key)
}
a.Head = stateCid
return vm.setActor(ctx, key, a)
}
// deleteActor remove the actor from the storage.
//
// This method will NOT return an error if the actor was not found.
// This behaviour is based on a principle that some store implementations might not be able to determine
// whether something exists before deleting it.
func (vm *VM) deleteActor(_ context.Context, key address.Address) error {
found, err := vm.actors.TryDelete(abi.AddrKey(key))
vm.actorsDirty = found
return err
}
func (vm *VM) checkpoint() (cid.Cid, error) {
// commit the vm state
root, err := vm.actors.Root()
if err != nil {
return cid.Undef, err
}
vm.stateRoot = root
vm.actorsDirty = false
return root, nil
}
func (vm *VM) NormalizeAddress(addr address.Address) (address.Address, bool) {
// short-circuit if the address is already an ID address
if addr.Protocol() == address.ID {
return addr, true
}
// resolve the target address via the InitActor, and attempt to load state.
initActorEntry, found, err := vm.GetActor(builtin.InitActorAddr)
if err != nil {
panic(xerrors.Errorf("failed to load init actor: %w", err))
}
if !found {
panic(xerrors.Errorf("no init actor: %w", err))
}
// get a view into the actor state
var state init_.State
if err := vm.store.Get(vm.ctx, initActorEntry.Head, &state); err != nil {
panic(err)
}
idAddr, found, err := state.ResolveAddress(vm.store, addr)
if err != nil {
panic(err)
}
return idAddr, found
}
type MessageResult struct {
Ret cbor.Marshaler
Code exitcode.ExitCode
GasCharged int64
}
// ApplyMessage applies the message to the current state. It returns result of message application and any internal vm errors.
// If test-vector environment variables are set this method generates tests-vectors as a side effect
func (vm *VM) ApplyMessage(from, to address.Address, value abi.TokenAmount, method abi.MethodNum, params interface{}, info string) (MessageResult, error) {
vectorGen := newVectorGen()
if err := vectorGen.before(vm, info); err != nil {
return MessageResult{}, err
}
result, callSeq, fakesAccessed, err := vm.applyMessageInternal(from, to, value, method, params)
if err != nil {
return MessageResult{}, err
}
if err := vectorGen.after(vm, from, to, value, method, params, callSeq, result, fakesAccessed, info); err != nil {
return MessageResult{}, err
}
return result, nil
}
func (vm *VM) applyMessageInternal(from, to address.Address, value abi.TokenAmount, method abi.MethodNum, params interface{}) (MessageResult, uint64, bool, error) {
// This method does not actually execute the message itself,
// but rather deals with the pre/post processing of a message.
// (see: `invocationContext.invoke()` for the dispatch and execution)
gasCharged := int64(0)
// load actor from global state
fromID, ok := vm.NormalizeAddress(from)
if !ok {
return MessageResult{nil, exitcode.SysErrSenderInvalid, gasCharged}, 0, false, nil
}
fromActor, found, err := vm.GetActor(fromID)
if err != nil {
return MessageResult{}, 0, false, err
}
if !found {
// Execution error; sender does not exist at time of message execution.
return MessageResult{nil, exitcode.SysErrSenderInvalid, gasCharged}, 0, false, nil
}
// send
// 1. update state tree nonce
// 2. checkpoint state with updated nonce
// 3. build chain message and charge gas
// 4. build internal message
// 5. build invocation context
// 6. process the msg
callSeq := fromActor.CallSeqNum
fromActor.CallSeqNum = callSeq + 1
if err := vm.setActor(context.Background(), fromID, fromActor); err != nil {
return MessageResult{}, 0, false, err
}
// checkpoint state
// Even if the message fails, the following accumulated changes will be applied:
// - CallSeqNumber increment
priorRoot, err := vm.checkpoint()
if err != nil {
return MessageResult{}, 0, false, err
}
msg, err := makeChainMessage(from, to, callSeq, value, method, params)
if err != nil {
return MessageResult{}, 0, false, err
}
var msgBuf bytes.Buffer
if err := msg.MarshalCBOR(&msgBuf); err != nil {
return MessageResult{}, 0, false, err
}
bs := msgBuf.Bytes()
charge := vm.gasPrices.OnChainMessage(len(bs))
msgGasCharge := charge.Total()
topLevel := topLevelContext{
originatorStableAddress: from,
originatorCallSeq: callSeq,
newActorAddressCount: 0,
statsSource: vm.statsSource,
circSupply: vm.circSupply,
gasUsed: msgGasCharge,
gasPrices: vm.gasPrices,
gasAvailable: defaultGasLimit,
fakeSyscallsAccessed: false,
}
// build internal msg
imsg := InternalMessage{
from: fromID,
to: to,
value: value,
method: method,
params: params,
}
// build invocation context
ctx := newInvocationContext(vm, &topLevel, imsg, fromActor, vm.emptyObject)
// 3. invoke
ret, exitCode := ctx.invoke()
// record stats
vm.statsByMethod.MergeStats(ctx.toActor.Code, imsg.method, ctx.stats)
// Roll back all state if the receipt's exit code is not ok.
// This is required in addition to rollback within the invocation context since top level messages can fail for
// more reasons than internal ones. Invocation context still needs its own rollback so actors can recover and
// proceed from a nested call failure.
if exitCode != exitcode.Ok {
if err := vm.rollback(priorRoot); err != nil {
return MessageResult{}, 0, false, err
}
} else {
// persist changes from final invocation if call is ok
if _, err := vm.checkpoint(); err != nil {
return MessageResult{}, 0, false, err
}
}
// serialize return and charge gas
var retBuf bytes.Buffer
if err := ret.inner.MarshalCBOR(&retBuf); err != nil {
return MessageResult{}, 0, false, err
}
retGasCharge := vm.gasPrices.OnChainReturnValue(len(retBuf.Bytes()))
gasCharged = retGasCharge.Total() + ctx.topLevel.gasUsed
return MessageResult{ret.inner, exitCode, gasCharged}, callSeq, ctx.topLevel.fakeSyscallsAccessed, nil
}
func (vm *VM) StateRoot() cid.Cid {
return vm.stateRoot
}
func (vm *VM) GetState(addr address.Address, out cbor.Unmarshaler) error {
act, found, err := vm.GetActor(addr)
if err != nil {
return err
}
if !found {
return xerrors.Errorf("actor %v not found", addr)
}
return vm.store.Get(vm.ctx, act.Head, out)
}
func (vm *VM) GetStateTree() (*states.Tree, error) {
root, err := vm.checkpoint()
if err != nil {
return nil, err
}
return states.LoadTree(vm.store, root)
}
func (vm *VM) GetTotalActorBalance() (abi.TokenAmount, error) {
tree, err := vm.GetStateTree()
if err != nil {
return big.Zero(), err
}
total := big.Zero()
err = tree.ForEach(func(_ address.Address, actor *states.Actor) error {
total = big.Add(total, actor.Balance)
return nil
})
if err != nil {
return big.Zero(), err
}
return total, nil
}
func (vm *VM) Store() adt.Store {
return vm.store
}
// Get the chain epoch for this vm
func (vm *VM) GetEpoch() abi.ChainEpoch {
return vm.currentEpoch
}
// Get call stats
func (vm *VM) GetCallStats() map[MethodKey]*CallStats {
return vm.statsByMethod
}
// Set the FIL circulating supply passed to actors through runtime
func (vm *VM) SetCirculatingSupply(supply abi.TokenAmount) {
vm.circSupply = supply
}
// Set the FIL circulating supply passed to actors through runtime
func (vm *VM) GetCirculatingSupply() abi.TokenAmount {
return vm.circSupply
}
func (vm *VM) GetActorImpls() map[cid.Cid]rt.VMActor {
return vm.ActorImpls
}
// transfer debits money from one account and credits it to another.
// avoid calling this method with a zero amount else it will perform unnecessary actor loading.
//
// WARNING: this method will panic if the the amount is negative, accounts dont exist, or have insufficient funds.
//
// Note: this is not idiomatic, it follows the Spec expectations for this method.
func (vm *VM) transfer(debitFrom address.Address, creditTo address.Address, amount abi.TokenAmount) (*states.Actor, *states.Actor) {
// allow only for positive amounts
if amount.LessThan(abi.NewTokenAmount(0)) {
panic("unreachable: negative funds transfer not allowed")
}
ctx := context.Background()
// retrieve debit account
fromActor, found, err := vm.GetActor(debitFrom)
if err != nil {
panic(err)
}
if !found {
panic(fmt.Errorf("unreachable: debit account not found. %s", err))
}
// check that account has enough balance for transfer
if fromActor.Balance.LessThan(amount) {
panic("unreachable: insufficient balance on debit account")
}
// debit funds
fromActor.Balance = big.Sub(fromActor.Balance, amount)
if err := vm.setActor(ctx, debitFrom, fromActor); err != nil {
panic(err)
}
// retrieve credit account
toActor, found, err := vm.GetActor(creditTo)
if err != nil {
panic(err)
}
if !found {
panic(fmt.Errorf("unreachable: credit account not found. %s", err))
}
// credit funds
toActor.Balance = big.Add(toActor.Balance, amount)
if err := vm.setActor(ctx, creditTo, toActor); err != nil {
panic(err)
}
return toActor, fromActor
}
func (vm *VM) getActorImpl(code cid.Cid) runtime.VMActor {
actorImpl, ok := vm.ActorImpls[code]
if !ok {
vm.Abortf(exitcode.SysErrInvalidReceiver, "actor implementation not found for Exitcode %v", code)
}
return actorImpl
}
//
// stats
//
func (vm *VM) SetStatsSource(s StatsSource) {
vm.statsSource = s
}
func (vm *VM) GetStatsSource() StatsSource {
return vm.statsSource
}
func (vm *VM) StoreReads() uint64 {
if vm.statsSource != nil {
return vm.statsSource.ReadCount()
}
return 0
}
func (vm *VM) StoreWrites() uint64 {
if vm.statsSource != nil {
return vm.statsSource.WriteCount()
}
return 0
}
func (vm *VM) StoreReadBytes() uint64 {
if vm.statsSource != nil {
return vm.statsSource.ReadSize()
}
return 0
}
func (vm *VM) StoreWriteBytes() uint64 {
if vm.statsSource != nil {
return vm.statsSource.WriteSize()
}
return 0
}
//
// invocation tracking
//
func (vm *VM) startInvocation(msg *InternalMessage) {
invocation := Invocation{Msg: msg}
if len(vm.invocationStack) > 0 {
parent := vm.invocationStack[len(vm.invocationStack)-1]
parent.SubInvocations = append(parent.SubInvocations, &invocation)
} else {
vm.invocations = append(vm.invocations, &invocation)
}
vm.invocationStack = append(vm.invocationStack, &invocation)
}
func (vm *VM) endInvocation(code exitcode.ExitCode, ret cbor.Marshaler) {
curIndex := len(vm.invocationStack) - 1
current := vm.invocationStack[curIndex]
current.Exitcode = code
current.Ret = ret
vm.invocationStack = vm.invocationStack[:curIndex]
}
func (vm *VM) Invocations() []*Invocation {
return vm.invocations
}
func (vm *VM) LastInvocation() *Invocation {
return vm.invocations[len(vm.invocations)-1]
}
//
// implement runtime.Runtime for VM
//
func (vm *VM) Log(_ rt.LogLevel, msg string, args ...interface{}) {
vm.logs = append(vm.logs, fmt.Sprintf(msg, args...))
}
func (vm *VM) GetLogs() []string {
return vm.logs
}
type abort struct {
code exitcode.ExitCode
msg string
}
func (vm *VM) Abortf(errExitCode exitcode.ExitCode, msg string, args ...interface{}) {
panic(abort{errExitCode, fmt.Sprintf(msg, args...)})
}
//
// implement runtime.MessageInfo for InternalMessage
//
var _ runtime.Message = (*InternalMessage)(nil)
// ValueReceived implements runtime.MessageInfo.
func (msg InternalMessage) ValueReceived() abi.TokenAmount {
return msg.value
}
// Caller implements runtime.MessageInfo.
func (msg InternalMessage) Caller() address.Address {
return msg.from
}
// Receiver implements runtime.MessageInfo.
func (msg InternalMessage) Receiver() address.Address {
return msg.to
}