-
Notifications
You must be signed in to change notification settings - Fork 4
/
construction_impl.go
647 lines (529 loc) · 16.3 KB
/
construction_impl.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
/*******************************************************************************
* (c) 2020-2023 Zondax GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
package rosettaFilecoinLib
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-state-types/builtin"
"github.com/filecoin-project/lotus/api"
"github.com/filecoin-project/lotus/api/client"
"github.com/zondax/rosetta-filecoin-lib/actors"
"go.uber.org/zap"
filAddr "github.com/filecoin-project/go-address"
gocrypto "github.com/filecoin-project/go-crypto"
"github.com/filecoin-project/go-state-types/abi"
multisigV10 "github.com/filecoin-project/go-state-types/builtin/v10/multisig"
"github.com/filecoin-project/go-state-types/crypto"
"github.com/filecoin-project/lotus/chain/types"
"github.com/filecoin-project/lotus/chain/types/ethtypes"
"github.com/ipfs/go-cid"
"github.com/minio/blake2b-simd"
cbg "github.com/whyrusleeping/cbor-gen"
)
type RosettaConstructionFilecoin struct {
networkName string
online bool
BuiltinActors actors.BuiltinActors
}
type LotusRpcV1 api.FullNode
const EthAddressLength = 20
// NewFilecoinRPCClient creates a new lotus rpc client
func NewFilecoinRPCClient(url string, token string) (LotusRpcV1, error) {
ctx := context.Background()
headers := http.Header{}
if len(token) > 0 {
headers.Add("Authorization", "Bearer "+token)
}
lotusAPI, _, err := client.NewFullNodeRPCV1(ctx, url, headers)
if err != nil {
return nil, err
}
return lotusAPI, nil
}
func NewRosettaConstructionFilecoin(lotusApi api.FullNode) *RosettaConstructionFilecoin {
if lotusApi == nil {
zap.S().Warn("library running in offline mode")
return &RosettaConstructionFilecoin{
online: false,
}
}
networkVersion, err := lotusApi.StateNetworkVersion(context.Background(), types.EmptyTSK)
if err != nil {
zap.S().Errorf("could not get lotus network version!: %s", err.Error())
return nil
}
networkName, err := lotusApi.StateNetworkName(context.Background())
if err != nil {
zap.S().Errorf("could not get lotus network name!: %s", err.Error())
return nil
}
actorCids, err := lotusApi.StateActorCodeCIDs(context.Background(), networkVersion)
if err != nil {
zap.S().Errorf("could not get actors cids!: %s", err.Error())
return nil
}
zap.S().Infof("Got actors CIDs for network: '%s' version: '%d'", networkName, networkVersion)
metadata := actors.BuiltinActorsMetadata{
Network: string(networkName),
Version: networkVersion,
ActorsNameCidMap: actorCids,
}
return &RosettaConstructionFilecoin{
networkName: string(networkName),
BuiltinActors: actors.BuiltinActors{Metadata: metadata},
online: true,
}
}
// String returns an address encoded as a string
var filAddrLibMutex sync.Mutex
func formatAddress(network filAddr.Network, addr filAddr.Address) string {
// the address library is unfortunately not thread-safe so we must use a mutex here
// so we only temporarily change the value and use to mutex to avoid issues
filAddrLibMutex.Lock()
defer filAddrLibMutex.Unlock()
oldNetworkValue := filAddr.CurrentNetwork
defer func() { filAddr.CurrentNetwork = oldNetworkValue }()
filAddr.CurrentNetwork = network
return addr.String()
}
func EthereumAddressFromHex(add string) (ethtypes.EthAddress, error) {
ethAdd, err := ethtypes.ParseEthAddress(add)
if err != nil {
return ethtypes.EthAddress{}, err
}
return ethAdd, nil
}
func EthereumAddressToFilecoin(add string) (filAddr.Address, error) {
ethAdd, err := EthereumAddressFromHex(add)
if err != nil {
return address.Undef, err
}
filAdd, err := ethAdd.ToFilecoinAddress()
if err != nil {
return address.Undef, err
}
return filAdd, nil
}
func FilToEthAddress(addr filAddr.Address) (ethtypes.EthAddress, error) {
return ethtypes.EthAddressFromFilecoinAddress(addr)
}
func signSecp256k1(msg []byte, pk []byte) ([]byte, error) {
b2sum := blake2b.Sum256(msg)
sig, err := gocrypto.Sign(pk, b2sum[:])
if err != nil {
return nil, err
}
return sig, nil
}
// Based on https://github.com/filecoin-project/lotus/blob/master/lib/sigs/secp/init.go#L38-L55
func verifySecp256k1(sig []byte, a filAddr.Address, msg []byte) error {
b2sum := blake2b.Sum256(msg)
pubk, err := gocrypto.EcRecover(b2sum[:], sig)
if err != nil {
return err
}
maybeaddr, err := filAddr.NewSecp256k1Address(pubk)
if err != nil {
return err
}
if a != maybeaddr {
return fmt.Errorf("signature did not match")
}
if gocrypto.Verify(pubk, b2sum[:], sig) {
return nil
}
return fmt.Errorf("invalid signature")
}
func (r *RosettaConstructionFilecoin) DeriveFromPublicKey(publicKey []byte, network filAddr.Network) (string, error) {
addr, err := filAddr.NewSecp256k1Address(publicKey)
if err != nil {
return "", err
}
return formatAddress(network, addr), nil
}
func (r *RosettaConstructionFilecoin) SignRaw(message []byte, sk []byte) ([]byte, error) {
return signSecp256k1(message, sk)
}
func (r *RosettaConstructionFilecoin) VerifyRaw(message []byte, publicKey []byte, signature []byte) error {
addr, err := filAddr.NewSecp256k1Address(publicKey)
if err != nil {
return err
}
return verifySecp256k1(signature, addr, message)
}
func (r *RosettaConstructionFilecoin) ConstructPayment(request *PaymentRequest) (string, error) {
to, err := filAddr.NewFromString(request.To)
if err != nil {
return "", err
}
from, err := filAddr.NewFromString(request.From)
if err != nil {
return "", err
}
value, err := types.BigFromString(request.Quantity)
if err != nil {
return "", err
}
gasfeecap, err := types.BigFromString(request.Metadata.GasFeeCap)
if err != nil {
return "", err
}
gaspremium, err := types.BigFromString(request.Metadata.GasPremium)
if err != nil {
return "", err
}
gaslimit := request.Metadata.GasLimit
methodNum := builtin.MethodSend
// check the dest address to set the correct methodNum
if strings.HasPrefix(request.To, "f410") {
methodNum = builtin.MethodsEVM.InvokeContract
}
msg := &types.Message{Version: types.MessageVersion,
To: to,
From: from,
Nonce: request.Metadata.Nonce,
Value: value,
GasFeeCap: gasfeecap,
GasPremium: gaspremium,
GasLimit: gaslimit,
Method: methodNum,
Params: make([]byte, 0),
}
tx, err := json.Marshal(msg)
if err != nil {
return "", err
}
return string(tx), nil
}
func (r *RosettaConstructionFilecoin) ConstructMultisigPayment(request *MultisigPaymentRequest) (string, error) {
actorCid, err := r.BuiltinActors.GetActorCid(actors.ActorMultisigName)
if err != nil {
return "", err
}
return r.ConstructMultisigPaymentV10(request, actorCid)
}
func (r *RosettaConstructionFilecoin) ConstructSwapAuthorizedParty(request *SwapAuthorizedPartyRequest) (string, error) {
actorCid, err := r.BuiltinActors.GetActorCid(actors.ActorMultisigName)
if err != nil {
return "", err
}
return r.ConstructSwapAuthorizedPartyV10(request, actorCid)
}
func (r *RosettaConstructionFilecoin) ConstructRemoveAuthorizedParty(request *RemoveAuthorizedPartyRequest) (string, error) {
actorCid, err := r.BuiltinActors.GetActorCid(actors.ActorMultisigName)
if err != nil {
return "", err
}
return r.ConstructRemoveAuthorizedPartyV10(request, actorCid)
}
func (r *RosettaConstructionFilecoin) unsignedMessageFromCBOR(messageCbor []byte) (*types.Message, error) {
br := cbg.GetPeeker(bytes.NewReader(messageCbor))
scratch := make([]byte, 8)
maj, extra, err := cbg.CborReadHeaderBuf(br, scratch)
if err != nil {
return nil, err
}
if maj != cbg.MajArray {
return nil, fmt.Errorf("cbor input should be of type array")
}
if extra != 10 {
return nil, fmt.Errorf("cbor input had wrong number of fields")
}
msg, err := types.DecodeMessage(messageCbor)
if err != nil {
return nil, err
}
return msg, nil
}
func (r *RosettaConstructionFilecoin) unsignedMessageFromJSON(unsignedTxJson string) (*types.Message, error) {
rawIn := json.RawMessage(unsignedTxJson)
txBytes, err := rawIn.MarshalJSON()
if err != nil {
return nil, err
}
var msg types.Message
err = json.Unmarshal(txBytes, &msg)
if err != nil {
return nil, err
}
return &msg, nil
}
func (r *RosettaConstructionFilecoin) EncodeTx(unsignedTxJson string) ([]byte, error) {
msg, err := r.unsignedMessageFromJSON(unsignedTxJson)
if err != nil {
return nil, err
}
response, err := msg.Serialize()
if err != nil {
return nil, err
}
return response, nil
}
func (r *RosettaConstructionFilecoin) SignTx(unsignedTx []byte, privateKey []byte) ([]byte, error) {
msg, err := r.unsignedMessageFromCBOR(unsignedTx)
if err != nil {
return nil, err
}
digest := msg.Cid().Bytes()
sig, err := r.SignRaw(digest, privateKey)
if err != nil {
return nil, err
}
signature := crypto.Signature{
Type: crypto.SigTypeSecp256k1,
Data: sig,
}
sm := &types.SignedMessage{
Message: *msg,
Signature: signature,
}
m, err := json.Marshal(sm)
if err != nil {
return nil, err
}
return m, nil
}
func (r *RosettaConstructionFilecoin) SignTxJSON(unsignedTxJson string, privateKey []byte) (string, error) {
msg, err := r.unsignedMessageFromJSON(unsignedTxJson)
if err != nil {
return "", err
}
digest := msg.Cid().Bytes()
sig, err := r.SignRaw(digest, privateKey)
if err != nil {
return "", err
}
signature := crypto.Signature{
Type: crypto.SigTypeSecp256k1,
Data: sig,
}
sm := &types.SignedMessage{
Message: *msg,
Signature: signature,
}
m, err := json.Marshal(sm)
if err != nil {
return "", err
}
return string(m), nil
}
func (r *RosettaConstructionFilecoin) ParseTx(messageCbor []byte) (string, error) {
br := cbg.GetPeeker(bytes.NewReader(messageCbor))
scratch := make([]byte, 8)
maj, extra, err := cbg.CborReadHeaderBuf(br, scratch)
if err != nil {
return "", err
}
if maj != cbg.MajArray {
return "", fmt.Errorf("cbor input should be of type array")
}
var msg interface{}
switch extra {
case 10:
// Unsigned message
msg, err = types.DecodeMessage(messageCbor)
if err != nil {
return "", err
}
case 2:
// Signed message
msg, err = types.DecodeSignedMessage(messageCbor)
if err != nil {
return "", err
}
default:
return "", fmt.Errorf("cbor input had wrong number of fields")
}
msgJson, err := json.Marshal(msg)
if err != nil {
return "", err
}
return string(msgJson), nil
}
func (r *RosettaConstructionFilecoin) ParseProposeTxParams(unsignedMultisigTx string, destinationActorId cid.Cid) (string, string, error) {
rawIn := json.RawMessage(unsignedMultisigTx)
txBytes, err := rawIn.MarshalJSON()
if err != nil {
return "", "", err
}
var msg types.Message
err = json.Unmarshal(txBytes, &msg)
if err != nil {
return "", "", err
}
meta, ok := multisigV10.Methods[msg.Method]
if !ok || meta.Name != "Propose" {
return "", "", fmt.Errorf("method does not correspond to a 'Propose' transaction")
}
reader := bytes.NewReader(msg.Params)
var proposeParams multisigV10.ProposeParams
err = proposeParams.UnmarshalCBOR(reader)
if err != nil {
return "", "", err
}
innerMethod, err := getMsigMethodString(proposeParams.Method)
if err != nil {
return "", "", err
}
innerParams, err := r.ParseParamsMultisigTx(unsignedMultisigTx, destinationActorId)
if err != nil {
return "", "", err
}
return innerMethod, innerParams, nil
}
func (r *RosettaConstructionFilecoin) GetInnerProposeTxParams(unsignedMultisigTx string) (*multisigV10.ProposeParams, error) {
rawIn := json.RawMessage(unsignedMultisigTx)
txBytes, err := rawIn.MarshalJSON()
if err != nil {
return nil, err
}
var msg types.Message
err = json.Unmarshal(txBytes, &msg)
if err != nil {
return nil, err
}
meta, ok := multisigV10.Methods[msg.Method]
if !ok || meta.Name != "Propose" {
return nil, fmt.Errorf("method does not correspond to a 'Propose' transaction")
}
reader := bytes.NewReader(msg.Params)
var proposeParams multisigV10.ProposeParams
err = proposeParams.UnmarshalCBOR(reader)
if err != nil {
return nil, err
}
return &proposeParams, nil
}
func (r *RosettaConstructionFilecoin) GetProposedMethod(proposeParams *multisigV10.ProposeParams, targetActorId cid.Cid) (string, error) {
actorName, err := r.BuiltinActors.GetActorNameFromCid(targetActorId)
if err != nil {
return "", err
}
switch actorName {
case actors.ActorAccountName, actors.ActorMultisigName:
innerMethod, err := getMsigMethodString(proposeParams.Method)
return innerMethod, err
case actors.ActorStorageMinerName:
innerMethod, err := getMinerMethodString(proposeParams.Method)
return innerMethod, err
case actors.ActorVerifiedRegistryName:
innerMethod, err := getVerifRegMethodString(proposeParams.Method)
return innerMethod, err
default:
return "", fmt.Errorf("target actor %v currently not supported inside Propose params", targetActorId)
}
}
func getMsigMethodString(method abi.MethodNum) (string, error) {
switch method {
case builtin.MethodSend:
return "Send", nil
case builtin.MethodsMultisig.Approve:
return "Approve", nil
case builtin.MethodsMultisig.Cancel:
return "Cancel", nil
case builtin.MethodsMultisig.SwapSigner:
return "SwapSigner", nil
case builtin.MethodsMultisig.RemoveSigner:
return "RemoveSigner", nil
case builtin.MethodsMultisig.AddSigner:
return "AddSigner", nil
case builtin.MethodsMultisig.ChangeNumApprovalsThreshold:
return "ChangeNumApprovalsThreshold", nil
case builtin.MethodsMultisig.LockBalance:
return "LockBalance", nil
case builtin.MethodsMultisig.Constructor:
return "Constructor", nil
case builtin.MethodsMultisig.Propose:
return "Propose", nil
default:
return "", fmt.Errorf("multisig method %v not recognized", method)
}
}
func getMinerMethodString(method abi.MethodNum) (string, error) {
switch method {
case builtin.MethodSend:
return "Send", nil
case builtin.MethodsMiner.WithdrawBalance:
return "WithdrawBalance", nil
case builtin.MethodsMiner.ChangeOwnerAddress:
return "ChangeOwnerAddress", nil
case builtin.MethodsMiner.ChangeWorkerAddress:
return "ChangeWorkerAddress", nil
// TODO: complete with all methods
default:
return "", fmt.Errorf("miner method %v not recognized", method)
}
}
func getVerifRegMethodString(method abi.MethodNum) (string, error) {
switch method {
case builtin.MethodsVerifiedRegistry.AddVerifiedClient:
return "AddVerifiedClient", nil
case builtin.MethodsVerifiedRegistry.AddVerifier:
return "AddVerifier", nil
case builtin.MethodsVerifiedRegistry.RemoveVerifier:
return "RemoveVerifier", nil
// TODO: complete with all methods
default:
return "", fmt.Errorf("verified registry method %v not recognized", method)
}
}
func (r *RosettaConstructionFilecoin) ParseParamsMultisigTx(unsignedMultisigTx string, destinationActorId cid.Cid) (string, error) {
// Try the latest version first
msigCid, err := r.BuiltinActors.GetActorCid(actors.ActorMultisigName)
if err != nil {
return "", err
}
if destinationActorId == msigCid {
return r.parseParamsMultisigTxV10(unsignedMultisigTx)
}
// Try legacy actors
if actors.IsLegacyActor(destinationActorId, actors.ActorMultisigName) {
return "", fmt.Errorf("actor id '%s' is a legacy actor and is not supported", destinationActorId.String())
}
return "", fmt.Errorf("actor id '%s' is not supported", destinationActorId.String())
}
func (r *RosettaConstructionFilecoin) Hash(signedMessage string) (string, error) {
rawIn := json.RawMessage(signedMessage)
txBytes, err := rawIn.MarshalJSON()
if err != nil {
return "", err
}
var msg types.SignedMessage
err = json.Unmarshal(txBytes, &msg)
if err != nil {
fmt.Println(err)
return "", err
}
// Verify teh signed message is valid to avoid generating wrong CID
// see https://github.com/Zondax/rosetta-filecoin-lib/issues/21
digest := msg.Message.Cid().Bytes()
if err != nil {
fmt.Println(err)
return "", err
}
err = verifySecp256k1(msg.Signature.Data, msg.Message.From, digest)
if err != nil {
fmt.Println(err)
return "", err
}
return msg.Cid().String(), nil
}