-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
vm.go
703 lines (581 loc) · 17.4 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
package vm
import (
"bytes"
"context"
"fmt"
"math/big"
block "github.com/ipfs/go-block-format"
cid "github.com/ipfs/go-cid"
hamt "github.com/ipfs/go-hamt-ipld"
blockstore "github.com/ipfs/go-ipfs-blockstore"
logging "github.com/ipfs/go-log/v2"
cbg "github.com/whyrusleeping/cbor-gen"
"go.opencensus.io/trace"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/lotus/build"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/aerrors"
"github.com/filecoin-project/lotus/chain/state"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/lib/bufbstore"
"github.com/filecoin-project/lotus/lib/sigs"
)
var log = logging.Logger("vm")
const (
gasFundTransfer = 10
gasInvoke = 5
gasGetObj = 10
gasGetPerByte = 1
gasPutObj = 20
gasPutPerByte = 2
gasCommit = 50
gasPerMessageByte = 2
)
const (
outOfGasErrCode = 200
)
type VMContext struct {
ctx context.Context
vm *VM
state *state.StateTree
msg *types.Message
height uint64
cst *hamt.CborIpldStore
gasAvailable types.BigInt
gasUsed types.BigInt
sys *types.VMSyscalls
// root cid of the state of the actor this invocation will be on
sroot cid.Cid
// address that started invoke chain
origin address.Address
}
// Message is the message that kicked off the current invocation
func (vmc *VMContext) Message() *types.Message {
return vmc.msg
}
func (vmc *VMContext) GetRandomness(height uint64) ([]byte, aerrors.ActorError) {
res, err := vmc.vm.rand.GetRandomness(vmc.ctx, int64(height))
if err != nil {
return nil, aerrors.Escalate(err, "could not get randomness")
}
return res, nil
}
func (vmc *VMContext) Sys() *types.VMSyscalls {
return vmc.sys
}
// Storage interface
func (vmc *VMContext) Put(i cbg.CBORMarshaler) (cid.Cid, aerrors.ActorError) {
c, err := vmc.cst.Put(context.TODO(), i)
if err != nil {
return cid.Undef, aerrors.HandleExternalError(err, fmt.Sprintf("putting object %T", i))
}
return c, nil
}
func (vmc *VMContext) Get(c cid.Cid, out cbg.CBORUnmarshaler) aerrors.ActorError {
err := vmc.cst.Get(context.TODO(), c, out)
if err != nil {
return aerrors.HandleExternalError(err, "getting cid")
}
return nil
}
func (vmc *VMContext) GetHead() cid.Cid {
return vmc.sroot
}
func (vmc *VMContext) Commit(oldh, newh cid.Cid) aerrors.ActorError {
if err := vmc.ChargeGas(gasCommit); err != nil {
return aerrors.Wrap(err, "out of gas")
}
if vmc.sroot != oldh {
return aerrors.New(1, "failed to update, inconsistent base reference")
}
vmc.sroot = newh
return nil
}
// End of storage interface
// Storage provides access to the VM storage layer
func (vmc *VMContext) Storage() types.Storage {
return vmc
}
func (vmc *VMContext) Ipld() *hamt.CborIpldStore {
return vmc.cst
}
func (vmc *VMContext) Origin() address.Address {
return vmc.origin
}
// Send allows the current execution context to invoke methods on other actors in the system
func (vmc *VMContext) Send(to address.Address, method uint64, value types.BigInt, params []byte) ([]byte, aerrors.ActorError) {
ctx, span := trace.StartSpan(vmc.ctx, "vmc.Send")
defer span.End()
if span.IsRecordingEvents() {
span.AddAttributes(
trace.StringAttribute("to", to.String()),
trace.Int64Attribute("method", int64(method)),
trace.StringAttribute("value", value.String()),
)
}
msg := &types.Message{
From: vmc.msg.To,
To: to,
Method: method,
Value: value,
Params: params,
GasLimit: vmc.gasAvailable,
}
ret, err, _ := vmc.vm.send(ctx, msg, vmc, 0)
return ret, err
}
// BlockHeight returns the height of the block this message was added to the chain in
func (vmc *VMContext) BlockHeight() uint64 {
return vmc.height
}
func (vmc *VMContext) GasUsed() types.BigInt {
return vmc.gasUsed
}
func (vmc *VMContext) ChargeGas(amount uint64) aerrors.ActorError {
toUse := types.NewInt(amount)
vmc.gasUsed = types.BigAdd(vmc.gasUsed, toUse)
if vmc.gasUsed.GreaterThan(vmc.gasAvailable) {
return aerrors.Newf(outOfGasErrCode, "not enough gas: used=%s, available=%s", vmc.gasUsed, vmc.gasAvailable)
}
return nil
}
func (vmc *VMContext) StateTree() (types.StateTree, aerrors.ActorError) {
if vmc.msg.To != actors.InitAddress {
return nil, aerrors.Escalate(fmt.Errorf("only init actor can access state tree directly"), "invalid use of StateTree")
}
return vmc.state, nil
}
const GasVerifySignature = 50
func (vmctx *VMContext) VerifySignature(sig *types.Signature, act address.Address, data []byte) aerrors.ActorError {
if err := vmctx.ChargeGas(GasVerifySignature); err != nil {
return err
}
if act.Protocol() == address.ID {
kaddr, err := ResolveToKeyAddr(vmctx.state, vmctx.cst, act)
if err != nil {
return aerrors.Wrap(err, "failed to resolve address to key address")
}
act = kaddr
}
if err := sigs.Verify(sig, act, data); err != nil {
return aerrors.New(2, "signature verification failed")
}
return nil
}
func ResolveToKeyAddr(state types.StateTree, cst *hamt.CborIpldStore, addr address.Address) (address.Address, aerrors.ActorError) {
if addr.Protocol() == address.BLS || addr.Protocol() == address.SECP256K1 {
return addr, nil
}
act, err := state.GetActor(addr)
if err != nil {
return address.Undef, aerrors.Newf(1, "failed to find actor: %s", addr)
}
if act.Code != actors.AccountCodeCid {
return address.Undef, aerrors.New(1, "address was not for an account actor")
}
var aast actors.AccountActorState
if err := cst.Get(context.TODO(), act.Head, &aast); err != nil {
return address.Undef, aerrors.Escalate(err, fmt.Sprintf("failed to get account actor state for %s", addr))
}
return aast.Address, nil
}
func (vmctx *VMContext) GetBalance(a address.Address) (types.BigInt, aerrors.ActorError) {
act, err := vmctx.state.GetActor(a)
switch err {
default:
return types.EmptyInt, aerrors.Escalate(err, "failed to look up actor balance")
case hamt.ErrNotFound:
return types.NewInt(0), nil
case nil:
return act.Balance, nil
}
}
func (vmctx *VMContext) Context() context.Context {
return vmctx.ctx
}
type hBlocks interface {
GetBlock(context.Context, cid.Cid) (block.Block, error)
AddBlock(block.Block) error
}
var _ hBlocks = (*gasChargingBlocks)(nil)
type gasChargingBlocks struct {
chargeGas func(uint64) aerrors.ActorError
under hBlocks
}
func (bs *gasChargingBlocks) GetBlock(ctx context.Context, c cid.Cid) (block.Block, error) {
if err := bs.chargeGas(gasGetObj); err != nil {
return nil, err
}
blk, err := bs.under.GetBlock(ctx, c)
if err != nil {
return nil, aerrors.Escalate(err, "failed to get block from blockstore")
}
if err := bs.chargeGas(uint64(len(blk.RawData())) * gasGetPerByte); err != nil {
return nil, err
}
return blk, nil
}
func (bs *gasChargingBlocks) AddBlock(blk block.Block) error {
if err := bs.chargeGas(gasPutObj + uint64(len(blk.RawData()))*gasPutPerByte); err != nil {
return err
}
if err := bs.under.AddBlock(blk); err != nil {
return aerrors.Escalate(err, "failed to write data to disk")
}
return nil
}
func (vm *VM) makeVMContext(ctx context.Context, sroot cid.Cid, msg *types.Message, origin address.Address, usedGas types.BigInt) *VMContext {
vmc := &VMContext{
ctx: ctx,
vm: vm,
state: vm.cstate,
sroot: sroot,
msg: msg,
origin: origin,
height: vm.blockHeight,
sys: vm.Syscalls,
gasUsed: usedGas,
gasAvailable: msg.GasLimit,
}
vmc.cst = &hamt.CborIpldStore{
Blocks: &gasChargingBlocks{vmc.ChargeGas, vm.cst.Blocks},
Atlas: vm.cst.Atlas,
}
return vmc
}
type VM struct {
cstate *state.StateTree
base cid.Cid
cst *hamt.CborIpldStore
buf *bufbstore.BufferedBS
blockHeight uint64
blockMiner address.Address
inv *invoker
rand Rand
Syscalls *types.VMSyscalls
}
func NewVM(base cid.Cid, height uint64, r Rand, maddr address.Address, cbs blockstore.Blockstore, syscalls *types.VMSyscalls) (*VM, error) {
buf := bufbstore.NewBufferedBstore(cbs)
cst := hamt.CSTFromBstore(buf)
state, err := state.LoadStateTree(cst, base)
if err != nil {
return nil, err
}
return &VM{
cstate: state,
base: base,
cst: cst,
buf: buf,
blockHeight: height,
blockMiner: maddr,
inv: NewInvoker(),
rand: r, // TODO: Probably should be a syscall
Syscalls: syscalls,
}, nil
}
type Rand interface {
GetRandomness(ctx context.Context, h int64) ([]byte, error)
}
type ApplyRet struct {
types.MessageReceipt
ActorErr aerrors.ActorError
}
func (vm *VM) send(ctx context.Context, msg *types.Message, parent *VMContext,
gasCharge uint64) ([]byte, aerrors.ActorError, *VMContext) {
st := vm.cstate
fromActor, err := st.GetActor(msg.From)
if err != nil {
return nil, aerrors.Absorb(err, 1, "could not find source actor"), nil
}
toActor, err := st.GetActor(msg.To)
if err != nil {
if xerrors.Is(err, types.ErrActorNotFound) {
a, err := TryCreateAccountActor(st, msg.To)
if err != nil {
return nil, aerrors.Absorb(err, 1, "could not create account"), nil
}
toActor = a
} else {
return nil, aerrors.Escalate(err, "getting actor"), nil
}
}
gasUsed := types.NewInt(gasCharge)
origin := msg.From
if parent != nil {
gasUsed = types.BigAdd(parent.gasUsed, gasUsed)
origin = parent.origin
}
vmctx := vm.makeVMContext(ctx, toActor.Head, msg, origin, gasUsed)
if parent != nil {
defer func() {
parent.gasUsed = vmctx.gasUsed
}()
}
if types.BigCmp(msg.Value, types.NewInt(0)) != 0 {
if aerr := vmctx.ChargeGas(gasFundTransfer); aerr != nil {
return nil, aerrors.Wrap(aerr, "sending funds"), nil
}
if err := Transfer(fromActor, toActor, msg.Value); err != nil {
return nil, aerrors.Absorb(err, 1, "failed to transfer funds"), nil
}
}
if msg.Method != 0 {
ret, err := vm.Invoke(toActor, vmctx, msg.Method, msg.Params)
if !aerrors.IsFatal(err) {
toActor.Head = vmctx.Storage().GetHead()
}
return ret, err, vmctx
}
return nil, nil, vmctx
}
func checkMessage(msg *types.Message) error {
if msg.GasLimit == types.EmptyInt {
return xerrors.Errorf("message gas no gas limit set")
}
if msg.GasPrice == types.EmptyInt {
return xerrors.Errorf("message gas no gas price set")
}
if msg.Value == types.EmptyInt {
return xerrors.Errorf("message no value set")
}
return nil
}
func (vm *VM) ApplyMessage(ctx context.Context, msg *types.Message) (*ApplyRet, error) {
ctx, span := trace.StartSpan(ctx, "vm.ApplyMessage")
defer span.End()
if span.IsRecordingEvents() {
span.AddAttributes(
trace.StringAttribute("to", msg.To.String()),
trace.Int64Attribute("method", int64(msg.Method)),
trace.StringAttribute("value", msg.Value.String()),
)
}
if err := checkMessage(msg); err != nil {
return nil, err
}
st := vm.cstate
if err := st.Snapshot(ctx); err != nil {
return nil, xerrors.Errorf("snapshot failed: %w", err)
}
fromActor, err := st.GetActor(msg.From)
if err != nil {
return nil, xerrors.Errorf("from actor not found: %w", err)
}
serMsg, err := msg.Serialize()
if err != nil {
return nil, xerrors.Errorf("could not serialize message: %w", err)
}
msgGasCost := uint64(len(serMsg)) * gasPerMessageByte
gascost := types.BigMul(msg.GasLimit, msg.GasPrice)
totalCost := types.BigAdd(gascost, msg.Value)
if fromActor.Balance.LessThan(totalCost) {
return nil, xerrors.Errorf("not enough funds (%s < %s)", fromActor.Balance, totalCost)
}
gasHolder := &types.Actor{Balance: types.NewInt(0)}
if err := Transfer(fromActor, gasHolder, gascost); err != nil {
return nil, xerrors.Errorf("failed to withdraw gas funds: %w", err)
}
if msg.Nonce != fromActor.Nonce {
return nil, xerrors.Errorf("invalid nonce (got %d, expected %d)", msg.Nonce, fromActor.Nonce)
}
fromActor.Nonce++
ret, actorErr, vmctx := vm.send(ctx, msg, nil, msgGasCost)
if aerrors.IsFatal(actorErr) {
return nil, xerrors.Errorf("[from=%s,to=%s,n=%d,m=%d,h=%d] fatal error: %w", msg.From, msg.To, msg.Nonce, msg.Method, vm.blockHeight, actorErr)
}
if actorErr != nil {
log.Warnw("Send actor error", "from", msg.From, "to", msg.To, "nonce", msg.Nonce, "method", msg.Method, "height", vm.blockHeight, "error", fmt.Sprintf("%+v", actorErr))
}
var errcode uint8
var gasUsed types.BigInt
if errcode = aerrors.RetCode(actorErr); errcode != 0 {
gasUsed = msg.GasLimit
// revert all state changes since snapshot
if err := st.Revert(); err != nil {
return nil, xerrors.Errorf("revert state failed: %w", err)
}
} else {
// refund unused gas
gasUsed = vmctx.GasUsed()
refund := types.BigMul(types.BigSub(msg.GasLimit, gasUsed), msg.GasPrice)
if err := Transfer(gasHolder, fromActor, refund); err != nil {
return nil, xerrors.Errorf("failed to refund gas")
}
}
miner, err := st.GetActor(vm.blockMiner)
if err != nil {
return nil, xerrors.Errorf("getting block miner actor (%s) failed: %w", vm.blockMiner, err)
}
// TODO: support multiple blocks in a tipset
// TODO: actually wire this up (miner is undef for now)
gasReward := types.BigMul(msg.GasPrice, gasUsed)
if err := Transfer(gasHolder, miner, gasReward); err != nil {
return nil, xerrors.Errorf("failed to give miner gas reward: %w", err)
}
if types.BigCmp(types.NewInt(0), gasHolder.Balance) != 0 {
return nil, xerrors.Errorf("gas handling math is wrong")
}
return &ApplyRet{
MessageReceipt: types.MessageReceipt{
ExitCode: errcode,
Return: ret,
GasUsed: gasUsed,
},
ActorErr: actorErr,
}, nil
}
func (vm *VM) SetBlockMiner(m address.Address) {
vm.blockMiner = m
}
func (vm *VM) ActorBalance(addr address.Address) (types.BigInt, aerrors.ActorError) {
act, err := vm.cstate.GetActor(addr)
if err != nil {
return types.EmptyInt, aerrors.Absorb(err, 1, "failed to find actor")
}
return act.Balance, nil
}
func (vm *VM) Flush(ctx context.Context) (cid.Cid, error) {
_, span := trace.StartSpan(ctx, "vm.Flush")
defer span.End()
from := vm.buf
to := vm.buf.Read()
root, err := vm.cstate.Flush(ctx)
if err != nil {
return cid.Undef, xerrors.Errorf("flushing vm: %w", err)
}
if err := Copy(from, to, root); err != nil {
return cid.Undef, xerrors.Errorf("copying tree: %w", err)
}
return root, nil
}
func linksForObj(blk block.Block) ([]cid.Cid, error) {
switch blk.Cid().Prefix().Codec {
case cid.DagCBOR:
return cbg.ScanForLinks(bytes.NewReader(blk.RawData()))
default:
return nil, xerrors.Errorf("vm flush copy method only supports dag cbor")
}
}
func Copy(from, to blockstore.Blockstore, root cid.Cid) error {
var batch []block.Block
batchCp := func(blk block.Block) error {
batch = append(batch, blk)
if len(batch) > 100 {
if err := to.PutMany(batch); err != nil {
return xerrors.Errorf("batch put in copy: %w", err)
}
batch = batch[:0]
}
return nil
}
if err := copyRec(from, to, root, batchCp); err != nil {
return err
}
if len(batch) > 0 {
if err := to.PutMany(batch); err != nil {
return xerrors.Errorf("batch put in copy: %w", err)
}
}
return nil
}
func copyRec(from, to blockstore.Blockstore, root cid.Cid, cp func(block.Block) error) error {
if root.Prefix().MhType == 0 {
// identity cid, skip
return nil
}
blk, err := from.Get(root)
if err != nil {
return xerrors.Errorf("get %s failed: %w", root, err)
}
links, err := linksForObj(blk)
if err != nil {
return err
}
for _, link := range links {
if link.Prefix().MhType == 0 {
continue
}
has, err := to.Has(link)
if err != nil {
return err
}
if has {
continue
}
if err := copyRec(from, to, link, cp); err != nil {
return err
}
}
if err := cp(blk); err != nil {
return err
}
return nil
}
func (vm *VM) StateTree() types.StateTree {
return vm.cstate
}
func (vm *VM) SetBlockHeight(h uint64) {
vm.blockHeight = h
}
func (vm *VM) Invoke(act *types.Actor, vmctx *VMContext, method uint64, params []byte) ([]byte, aerrors.ActorError) {
ctx, span := trace.StartSpan(vmctx.ctx, "vm.Invoke")
defer span.End()
if span.IsRecordingEvents() {
span.AddAttributes(
trace.StringAttribute("to", vmctx.Message().To.String()),
trace.Int64Attribute("method", int64(method)),
trace.StringAttribute("value", vmctx.Message().Value.String()),
)
}
var oldCtx context.Context
oldCtx, vmctx.ctx = vmctx.ctx, ctx
defer func() {
vmctx.ctx = oldCtx
}()
if err := vmctx.ChargeGas(gasInvoke); err != nil {
return nil, aerrors.Wrap(err, "invokeing")
}
ret, err := vm.inv.Invoke(act, vmctx, method, params)
if err != nil {
return nil, err
}
return ret, nil
}
func Transfer(from, to *types.Actor, amt types.BigInt) error {
if from == to {
return nil
}
if amt.LessThan(types.NewInt(0)) {
return xerrors.Errorf("attempted to transfer negative value")
}
if err := deductFunds(from, amt); err != nil {
return err
}
depositFunds(to, amt)
return nil
}
func (vm *VM) SetInvoker(i *invoker) {
vm.inv = i
}
func deductFunds(act *types.Actor, amt types.BigInt) error {
if act.Balance.LessThan(amt) {
return fmt.Errorf("not enough funds")
}
act.Balance = types.BigSub(act.Balance, amt)
return nil
}
func depositFunds(act *types.Actor, amt types.BigInt) {
act.Balance = types.BigAdd(act.Balance, amt)
}
var miningRewardTotal = types.FromFil(build.MiningRewardTotal)
var blocksPerEpoch = types.NewInt(build.BlocksPerEpoch)
// MiningReward returns correct mining reward
// coffer is amount of FIL in NetworkAddress
func MiningReward(remainingReward types.BigInt) types.BigInt {
ci := big.NewInt(0).Set(remainingReward.Int)
res := ci.Mul(ci, build.InitialReward)
res = res.Div(res, miningRewardTotal.Int)
res = res.Div(res, blocksPerEpoch.Int)
return types.BigInt{res}
}