-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathevm.go
537 lines (459 loc) · 13.7 KB
/
evm.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
package cli
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"fmt"
"os"
"github.com/urfave/cli/v2"
cbg "github.com/whyrusleeping/cbor-gen"
"golang.org/x/xerrors"
"github.com/filecoin-project/go-address"
amt4 "github.com/filecoin-project/go-amt-ipld/v4"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
builtintypes "github.com/filecoin-project/go-state-types/builtin"
"github.com/filecoin-project/go-state-types/builtin/v10/eam"
"github.com/filecoin-project/lotus/api/v0api"
"github.com/filecoin-project/lotus/chain/actors"
"github.com/filecoin-project/lotus/chain/actors/builtin"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/types/ethtypes"
)
var EvmCmd = &cli.Command{
Name: "evm",
Usage: "Commands related to the Filecoin EVM runtime",
Subcommands: []*cli.Command{
EvmDeployCmd,
EvmInvokeCmd,
EvmGetInfoCmd,
EvmCallSimulateCmd,
EvmGetContractAddress,
EvmGetBytecode,
},
}
var EvmGetInfoCmd = &cli.Command{
Name: "stat",
Usage: "Print eth/filecoin addrs and code cid",
ArgsUsage: "address",
Action: func(cctx *cli.Context) error {
if cctx.NArg() != 1 {
return IncorrectNumArgs(cctx)
}
api, closer, err := GetFullNodeAPI(cctx)
if err != nil {
return err
}
defer closer()
ctx := ReqContext(cctx)
addrString := cctx.Args().Get(0)
var faddr address.Address
var eaddr ethtypes.EthAddress
addr, err := address.NewFromString(addrString)
if err != nil { // This isn't a filecoin address
eaddr, err = ethtypes.ParseEthAddress(addrString)
if err != nil { // This isn't an Eth address either
return xerrors.Errorf("address is not a filecoin or eth address")
}
faddr, err = eaddr.ToFilecoinAddress()
if err != nil {
return err
}
} else {
eaddr, faddr, err = ethAddrFromFilecoinAddress(ctx, addr, api)
if err != nil {
return err
}
}
actor, err := api.StateGetActor(ctx, faddr, types.EmptyTSK)
fmt.Println("Filecoin address: ", faddr)
fmt.Println("Eth address: ", eaddr)
if err != nil {
fmt.Printf("Actor lookup failed for faddr %s with error: %s\n", faddr, err)
} else {
idAddr, err := api.StateLookupID(ctx, faddr, types.EmptyTSK)
if err == nil {
fmt.Println("ID address: ", idAddr)
fmt.Println("Code cid: ", actor.Code.String())
fmt.Println("Actor Type: ", builtin.ActorNameByCode(actor.Code))
}
}
return nil
},
}
var EvmCallSimulateCmd = &cli.Command{
Name: "call",
Usage: "Simulate an eth contract call",
ArgsUsage: "[from] [to] [params]",
Action: func(cctx *cli.Context) error {
if cctx.NArg() != 3 {
return IncorrectNumArgs(cctx)
}
fromEthAddr, err := ethtypes.ParseEthAddress(cctx.Args().Get(0))
if err != nil {
return err
}
toEthAddr, err := ethtypes.ParseEthAddress(cctx.Args().Get(1))
if err != nil {
return err
}
params, err := ethtypes.DecodeHexStringTrimSpace(cctx.Args().Get(2))
if err != nil {
return err
}
api, closer, err := GetFullNodeAPIV1(cctx)
if err != nil {
return err
}
defer closer()
ctx := ReqContext(cctx)
res, err := api.EthCall(ctx, ethtypes.EthCall{
From: &fromEthAddr,
To: &toEthAddr,
Data: params,
}, ethtypes.NewEthBlockNumberOrHashFromPredefined("latest"))
if err != nil {
fmt.Println("Eth call fails, return val: ", res)
return err
}
fmt.Println("Result: ", res)
return nil
},
}
var EvmGetContractAddress = &cli.Command{
Name: "contract-address",
Usage: "Generate contract address from smart contract code",
ArgsUsage: "[senderEthAddr] [salt] [contractHexPath]",
Action: func(cctx *cli.Context) error {
if cctx.NArg() != 3 {
return IncorrectNumArgs(cctx)
}
sender, err := ethtypes.ParseEthAddress(cctx.Args().Get(0))
if err != nil {
return err
}
salt, err := ethtypes.DecodeHexStringTrimSpace(cctx.Args().Get(1))
if err != nil {
return xerrors.Errorf("Could not decode salt: %w", err)
}
if len(salt) > 32 {
return xerrors.Errorf("Len of salt bytes greater than 32")
}
var fsalt [32]byte
copy(fsalt[:], salt[:])
contractBin := cctx.Args().Get(2)
if err != nil {
return err
}
contractHex, err := os.ReadFile(contractBin)
if err != nil {
return err
}
contract, err := ethtypes.DecodeHexStringTrimSpace(string(contractHex))
if err != nil {
return xerrors.Errorf("Could not decode contract file: %w", err)
}
contractAddr, err := ethtypes.GetContractEthAddressFromCode(sender, fsalt, contract)
if err != nil {
return err
}
fmt.Println("Contract Eth address: ", contractAddr)
return nil
},
}
var EvmDeployCmd = &cli.Command{
Name: "deploy",
Usage: "Deploy an EVM smart contract and return its address",
ArgsUsage: "contract",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "from",
Usage: "optionally specify the account to use for sending the creation message",
},
&cli.BoolFlag{
Name: "hex",
Usage: "use when input contract is in hex",
},
},
Action: func(cctx *cli.Context) error {
afmt := NewAppFmt(cctx.App)
api, closer, err := GetFullNodeAPI(cctx)
if err != nil {
return err
}
defer closer()
ctx := ReqContext(cctx)
if argc := cctx.Args().Len(); argc != 1 {
return xerrors.Errorf("must pass the contract init code")
}
contract, err := os.ReadFile(cctx.Args().First())
if err != nil {
return xerrors.Errorf("failed to read contract: %w", err)
}
if cctx.Bool("hex") {
contract, err = ethtypes.DecodeHexStringTrimSpace(string(contract))
if err != nil {
return xerrors.Errorf("failed to decode contract: %w", err)
}
}
var fromAddr address.Address
if from := cctx.String("from"); from == "" {
fromAddr, err = api.WalletDefaultAddress(ctx)
} else {
fromAddr, err = address.NewFromString(from)
}
if err != nil {
return err
}
initcode := abi.CborBytes(contract)
params, err := actors.SerializeParams(&initcode)
if err != nil {
return fmt.Errorf("failed to serialize Create params: %w", err)
}
msg := &types.Message{
To: builtintypes.EthereumAddressManagerActorAddr,
From: fromAddr,
Value: big.Zero(),
Method: builtintypes.MethodsEAM.CreateExternal,
Params: params,
}
// TODO: On Jan 11th, we decided to add an `EAM#create_external` method
// that uses the nonce of the caller instead of taking a user-supplied nonce.
// Track: https://github.com/filecoin-project/ref-fvm/issues/1255
// When that's implemented, we should migrate the CLI to use that,
// as `EAM#create` will be reserved for the EVM runtime actor.
// TODO: this is very racy. It may assign a _different_ nonce than the expected one.
afmt.Println("sending message...")
smsg, err := api.MpoolPushMessage(ctx, msg, nil)
if err != nil {
return xerrors.Errorf("failed to push message: %w", err)
}
afmt.Println("waiting for message to execute...")
wait, err := api.StateWaitMsg(ctx, smsg.Cid(), 0)
if err != nil {
return xerrors.Errorf("error waiting for message: %w", err)
}
// check it executed successfully
if wait.Receipt.ExitCode != 0 {
return xerrors.Errorf("actor execution failed")
}
var result eam.CreateReturn
r := bytes.NewReader(wait.Receipt.Return)
if err := result.UnmarshalCBOR(r); err != nil {
return xerrors.Errorf("error unmarshaling return value: %w", err)
}
addr, err := address.NewIDAddress(result.ActorID)
if err != nil {
return err
}
afmt.Printf("Actor ID: %d\n", result.ActorID)
afmt.Printf("ID Address: %s\n", addr)
afmt.Printf("Robust Address: %s\n", result.RobustAddress)
afmt.Printf("Eth Address: %s\n", "0x"+hex.EncodeToString(result.EthAddress[:]))
ea, err := ethtypes.CastEthAddress(result.EthAddress[:])
if err != nil {
return fmt.Errorf("failed to create ethereum address: %w", err)
}
delegated, err := ea.ToFilecoinAddress()
if err != nil {
return fmt.Errorf("failed to calculate f4 address: %w", err)
}
afmt.Printf("f4 Address: %s\n", delegated)
if len(wait.Receipt.Return) > 0 {
result := base64.StdEncoding.EncodeToString(wait.Receipt.Return)
afmt.Printf("Return: %s\n", result)
}
return nil
},
}
var EvmInvokeCmd = &cli.Command{
Name: "invoke",
Usage: "Invoke an EVM smart contract using the specified CALLDATA",
ArgsUsage: "address calldata",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "from",
Usage: "optionally specify the account to use for sending the exec message",
}, &cli.IntFlag{
Name: "value",
Usage: "optionally specify the value to be sent with the invocation message",
},
},
Action: func(cctx *cli.Context) error {
afmt := NewAppFmt(cctx.App)
api, closer, err := GetFullNodeAPI(cctx)
if err != nil {
return err
}
defer closer()
ctx := ReqContext(cctx)
if argc := cctx.Args().Len(); argc != 2 {
return xerrors.Errorf("must pass the address and calldata")
}
addr, err := address.NewFromString(cctx.Args().Get(0))
if err != nil {
return xerrors.Errorf("failed to decode address: %w", err)
}
var calldata []byte
calldata, err = ethtypes.DecodeHexStringTrimSpace(cctx.Args().Get(1))
if err != nil {
return xerrors.Errorf("decoding hex input data: %w", err)
}
var buffer bytes.Buffer
if err := cbg.WriteByteArray(&buffer, calldata); err != nil {
return xerrors.Errorf("failed to encode evm params as cbor: %w", err)
}
calldata = buffer.Bytes()
var fromAddr address.Address
if from := cctx.String("from"); from == "" {
defaddr, err := api.WalletDefaultAddress(ctx)
if err != nil {
return err
}
fromAddr = defaddr
} else {
addr, err := address.NewFromString(from)
if err != nil {
return err
}
fromAddr = addr
}
val := abi.NewTokenAmount(cctx.Int64("value"))
msg := &types.Message{
To: addr,
From: fromAddr,
Value: val,
Method: builtintypes.MethodsEVM.InvokeContract,
Params: calldata,
}
afmt.Println("sending message...")
smsg, err := api.MpoolPushMessage(ctx, msg, nil)
if err != nil {
return xerrors.Errorf("failed to push message: %w", err)
}
afmt.Println("waiting for message to execute...")
wait, err := api.StateWaitMsg(ctx, smsg.Cid(), 0)
if err != nil {
return xerrors.Errorf("error waiting for message: %w", err)
}
// check it executed successfully
if wait.Receipt.ExitCode != 0 {
return xerrors.Errorf("actor execution failed")
}
afmt.Println("Gas used: ", wait.Receipt.GasUsed)
result, err := cbg.ReadByteArray(bytes.NewBuffer(wait.Receipt.Return), uint64(len(wait.Receipt.Return)))
if err != nil {
return xerrors.Errorf("evm result not correctly encoded: %w", err)
}
if len(result) > 0 {
afmt.Println(hex.EncodeToString(result))
} else {
afmt.Println("OK")
}
if eventsRoot := wait.Receipt.EventsRoot; eventsRoot != nil {
afmt.Println("Events emitted:")
s := &apiIpldStore{ctx, api}
amt, err := amt4.LoadAMT(ctx, s, *eventsRoot, amt4.UseTreeBitWidth(types.EventAMTBitwidth))
if err != nil {
return err
}
var evt types.Event
err = amt.ForEach(ctx, func(u uint64, deferred *cbg.Deferred) error {
fmt.Printf("%x\n", deferred.Raw)
if err := evt.UnmarshalCBOR(bytes.NewReader(deferred.Raw)); err != nil {
return err
}
if err != nil {
return err
}
fmt.Printf("\tEmitter ID: %s\n", evt.Emitter)
for _, e := range evt.Entries {
value, err := cbg.ReadByteArray(bytes.NewBuffer(e.Value), uint64(len(e.Value)))
if err != nil {
return err
}
fmt.Printf("\t\tKey: %s, Value: 0x%x, Flags: b%b\n", e.Key, value, e.Flags)
}
return nil
})
}
if err != nil {
return err
}
return nil
},
}
func ethAddrFromFilecoinAddress(ctx context.Context, addr address.Address, fnapi v0api.FullNode) (ethtypes.EthAddress, address.Address, error) {
var faddr address.Address
var err error
switch addr.Protocol() {
case address.BLS, address.SECP256K1:
faddr, err = fnapi.StateLookupID(ctx, addr, types.EmptyTSK)
if err != nil {
return ethtypes.EthAddress{}, addr, err
}
case address.Actor, address.ID:
faddr, err = fnapi.StateLookupID(ctx, addr, types.EmptyTSK)
if err != nil {
return ethtypes.EthAddress{}, addr, err
}
fAct, err := fnapi.StateGetActor(ctx, faddr, types.EmptyTSK)
if err != nil {
return ethtypes.EthAddress{}, addr, err
}
if fAct.DelegatedAddress != nil && (*fAct.DelegatedAddress).Protocol() == address.Delegated {
faddr = *fAct.DelegatedAddress
}
case address.Delegated:
faddr = addr
default:
return ethtypes.EthAddress{}, addr, xerrors.Errorf("Filecoin address doesn't match known protocols")
}
ethAddr, err := ethtypes.EthAddressFromFilecoinAddress(faddr)
if err != nil {
return ethtypes.EthAddress{}, addr, err
}
return ethAddr, faddr, nil
}
var EvmGetBytecode = &cli.Command{
Name: "bytecode",
Usage: "Write the bytecode of a smart contract to a file",
ArgsUsage: "[contract-address] [file-name]",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "bin",
Usage: "write the bytecode as raw binary and don't hex-encode",
},
},
Action: func(cctx *cli.Context) error {
if cctx.NArg() != 2 {
return IncorrectNumArgs(cctx)
}
contractAddr, err := ethtypes.ParseEthAddress(cctx.Args().Get(0))
if err != nil {
return err
}
fileName := cctx.Args().Get(1)
api, closer, err := GetFullNodeAPIV1(cctx)
if err != nil {
return err
}
defer closer()
ctx := ReqContext(cctx)
code, err := api.EthGetCode(ctx, contractAddr, ethtypes.NewEthBlockNumberOrHashFromPredefined("latest"))
if err != nil {
return err
}
if !cctx.Bool("bin") {
newCode := make([]byte, hex.EncodedLen(len(code)))
hex.Encode(newCode, code)
code = newCode
}
if err := os.WriteFile(fileName, code, 0o666); err != nil {
return xerrors.Errorf("failed to write bytecode to file %s: %w", fileName, err)
}
fmt.Printf("Code for %s written to %s\n", contractAddr, fileName)
return nil
},
}