-
Notifications
You must be signed in to change notification settings - Fork 16.7k
Expand file tree
/
Copy patheth.go
More file actions
2103 lines (1973 loc) · 75.9 KB
/
Copy patheth.go
File metadata and controls
2103 lines (1973 loc) · 75.9 KB
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 rpc
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"net/http"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/canopy-network/canopy/fsm"
"github.com/canopy-network/canopy/lib"
"github.com/canopy-network/canopy/lib/crypto"
"github.com/canopy-network/canopy/store"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
ethCrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/julienschmidt/httprouter"
"google.golang.org/protobuf/types/known/anypb"
)
/* This file wraps Canopy with the Ethereum JSON-RPC interface as specified here: https://ethereum.org/en/developers/docs/apis/json-rpc */
// EthereumHandler is a helper function that abstracts common workflows of ethereum calls using the JSON rpc 2.0 specification
func (s *Server) EthereumHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
var raw json.RawMessage
if ok := unmarshal(w, r, &raw); !ok {
return
}
if strings.HasPrefix(strings.TrimSpace(string(raw)), "[") {
var requests []ethRPCRequest
if err := json.Unmarshal(raw, &requests); err != nil {
write(w, err, http.StatusBadRequest)
return
}
responses := make([]ethRPCResponse, 0, len(requests))
for i := range requests {
responses = append(responses, s.handleEthereumRPCRequest(&requests[i]))
}
write(w, responses, http.StatusOK)
return
}
ptr := new(ethRPCRequest)
if err := json.Unmarshal(raw, ptr); err != nil {
write(w, err, http.StatusBadRequest)
return
}
write(w, s.handleEthereumRPCRequest(ptr), http.StatusOK)
}
func (s *Server) handleEthereumRPCRequest(ptr *ethRPCRequest) ethRPCResponse {
var err error
var args []any
if len(ptr.Params) != 0 && string(ptr.Params) != "null" {
if err = json.Unmarshal(ptr.Params, &args); err != nil {
return ethRPCResponse{
ID: ptr.ID,
JSONRPC: "2.0",
Error: ðereumRPCError{Code: -32603, Message: err.Error()},
}
}
}
var ethResponse any
switch ptr.Method {
case `web3_clientVersion`:
ethResponse, err = s.Web3ClientVersion(args)
case `web3_sha3`:
ethResponse, err = s.Web3Sha3(args)
case `net_version`:
ethResponse, err = s.NetVersion(args)
case `net_listening`:
ethResponse, err = s.NetListening(args)
case `net_peerCount`:
ethResponse, err = s.NetPeerCount(args)
case `eth_protocolVersion`:
ethResponse, err = s.EthProtocolVersion(args)
case `eth_syncing`:
ethResponse, err = s.EthSyncing(args)
case `eth_chainId`:
ethResponse, err = s.EthChainId(args)
case `eth_gasPrice`:
ethResponse, err = s.EthGasPrice(args)
case `eth_accounts`:
ethResponse, err = s.EthAccounts(args)
case `eth_blockNumber`:
ethResponse, err = s.EthBlockNumber(args)
case `eth_getBalance`:
ethResponse, err = s.EthGetBalance(args)
case `eth_getTransactionCount`:
ethResponse, err = s.EthGetTransactionCount(args)
case `eth_getBlockTransactionCountByHash`:
ethResponse, err = s.EthGetBlockTransactionCountByHash(args)
case `eth_getBlockTransactionCountByNumber`:
ethResponse, err = s.EthGetBlockTransactionCountByNumber(args)
case `eth_getUncleCountByBlockHash`:
ethResponse, err = s.EthGetUncleCountByBlockHash(args)
case `eth_getUncleCountByBlockNumber`:
ethResponse, err = s.EthGetUncleCountByBlockNumber(args)
case `eth_getCode`:
ethResponse, err = s.EthGetCode(args)
case `eth_sendRawTransaction`:
ethResponse, err = s.EthSendRawTransaction(args)
case `eth_call`:
ethResponse, err = s.EthCall(args)
case `eth_estimateGas`:
ethResponse, err = s.EthEstimateGas(args)
case `eth_getBlockByHash`:
ethResponse, err = s.EthGetBlockByHash(args)
case `eth_getBlockByNumber`:
ethResponse, err = s.EthGetBlockByNumber(args)
case `eth_getTransactionByHash`:
ethResponse, err = s.EthGetTransactionByHash(args)
case `eth_getTransactionByBlockHashAndIndex`:
ethResponse, err = s.EthGetTransactionByBlockHashAndIndex(args)
case `eth_getTransactionByBlockNumberAndIndex`:
ethResponse, err = s.EthGetTransactionByBlockNumAndIndex(args)
case `eth_getTransactionReceipt`:
ethResponse, err = s.EthGetTransactionReceipt(args)
case `eth_getUncleByBlockHashAndIndex`:
ethResponse, err = s.EthGetUncleByBlockHashAndIndex(args)
case `eth_getUncleByBlockNumberAndIndex`:
ethResponse, err = s.EthGetUncleByBlockNumAndIndex(args)
case `eth_newFilter`:
ethResponse, err = s.EthNewFilter(args)
case `eth_newBlockFilter`:
ethResponse, err = s.EthNewBlockFilter(args)
case `eth_getFilterChanges`:
ethResponse, err = s.EthGetFilterChanges(args)
case `eth_getFilterLogs`:
ethResponse, err = s.EthGetFilterLogs(args)
case `eth_getLogs`:
ethResponse, err = s.EthGetLogs(args)
case `eth_newPendingTransactionFilter`:
ethResponse, err = s.EthNewPendingTxsFilter(args)
case `eth_uninstallFilter`:
ethResponse, err = s.EthUninstallFilter(args)
case `eth_blobBaseFee`:
ethResponse, err = s.EthBlobBaseFee(args)
default:
// purposefully don't support any method that requires private key unlocks
err = ethMethodNotFound(ptr.Method)
}
return ethRPCResponse{
ID: ptr.ID,
JSONRPC: "2.0",
Result: ethResponse,
Error: ethereumRPCErrorFrom(err),
}
}
// startEthRPCService() runs the needed routines for the eth rpc wrapper
func (s *Server) startEthRPCService() {
go s.startEthPendingTxsExpireService()
go s.startEthFilterExpireService()
}
// Web3ClientVersion() return a dummy string for compatibility
func (s *Server) Web3ClientVersion(_ []any) (any, error) { return "Canopy_Eth_Wrapper", nil }
// Web3Sha3() executes the Keccak-256 hash
func (s *Server) Web3Sha3(args []any) (any, error) {
strToHash, err := strFromArgs(args, 0)
if err != nil {
return nil, err
}
// convert from hex string to bytes
bzToHash, err := lib.StringToBytes(cleanHex(strToHash))
if err != nil {
return nil, err
}
// execute the hash
return hexutil.Bytes(ethCrypto.Keccak256(bzToHash)), nil
}
// NetVersion() returns the network id
func (s *Server) NetVersion(_ []any) (any, error) {
return strconv.FormatUint(fsm.CanopyIdsToEVMChainId(s.config.ChainId, s.config.NetworkID), 10), nil
}
// NetListening() canopy is always listening for peers
func (s *Server) NetListening(_ []any) (any, error) { return true, nil }
// NetPeerCount() returns the number of peers
func (s *Server) NetPeerCount(_ []any) (any, error) {
return hexutil.Uint64(s.controller.P2P.PeerCount()), nil
}
// EthProtocolVersion() returns a compatibility protocol version string
func (s *Server) EthProtocolVersion(_ []any) (any, error) { return "0x41", nil }
// EthSyncing() returns the syncing status of the node
func (s *Server) EthSyncing(_ []any) (any, error) {
if !s.controller.Syncing().Load() {
return false, nil
}
currentBlock := s.currentEthBlockNumber()
// return the syncing response
return ethSyncingResponse{
StartingBlock: hexutil.Uint64(1),
CurrentBlock: hexutil.Uint64(currentBlock),
HighestBlock: hexutil.Uint64(currentBlock),
}, nil
}
// EthChainId() returns the chain id of this node
func (s *Server) EthChainId(_ []any) (any, error) {
return hexutil.Uint64(fsm.CanopyIdsToEVMChainId(s.config.ChainId, s.config.NetworkID)), nil
}
// gas = tx.Fee * 100
// gasPrice = 1e10 (10,000,000,000 wei = 0.01 uCNPY)
// fee = gas * gasPrice = tx.Fee * 100 * 1e10 = tx.Fee * 1e12
var ethGasPrice = int64(10_000_000_000)
// EthGasPrice() returns minimum_fee / eth_gas_limit to be compatible with the
func (s *Server) EthGasPrice(_ []any) (any, error) { return hexutil.Big(*big.NewInt(ethGasPrice)), nil }
// EthAccounts() return all keystore addresses
func (s *Server) EthAccounts(_ []any) (any, error) {
keystore, err := crypto.NewKeystoreFromFile(s.config.DataDirPath)
if err != nil {
return nil, err
}
// create a list of ethereum compatible addresses
var ethAddresses []string
for _, account := range keystore.AddressMap {
// convert the public key string to an object
publicKey, e := crypto.NewPublicKeyFromString(account.PublicKey)
if e != nil {
return nil, e
}
// if the key is an ethereum compatible public key
if _, ok := publicKey.(*crypto.ETHSECP256K1PublicKey); ok {
ethAddresses = append(ethAddresses, "0x"+account.KeyAddress)
}
}
return ethAddresses, nil
}
// EthBlobBaseFee() returns the base fee for send transactions
func (s *Server) EthBlobBaseFee(a []any) (any, error) { return s.EthGasPrice(a) }
// EthBlockNumber() returns the height of the chain
func (s *Server) EthBlockNumber(_ []any) (result any, err error) {
// create a read-only state for the latest block
_ = s.readOnlyState(0, func(state *fsm.StateMachine) lib.ErrorI {
result = hexutil.Uint64(state.Height() - 1)
return nil
})
return
}
// EthGetBalance() returns the balance of an address
func (s *Server) EthGetBalance(args []any) (result any, err error) {
// extract the address from the args
address, err := addressFromArgs(args)
if err != nil {
return
}
// handle the block tag
height, err := blockTagFromArgs(args)
if err != nil {
return
}
// create a read-only state for the block tag
err = s.readOnlyState(height, func(state *fsm.StateMachine) (e lib.ErrorI) {
// get the balance for the address
balance, e := state.GetAccountSpendableBalance(address)
if e != nil {
return
}
// upscale to 18 dec in hex string format
result = hexutil.Big(*fsm.UpscaleTo18Decimals(balance))
// exit
return
})
return
}
// EthGetTransactionCount() returns the next nonce for Ethereum accounts and a pseudo-nonce fallback for read-only addresses.
func (s *Server) EthGetTransactionCount(args []any) (any, error) {
address, err := addressFromArgs(args)
if err != nil {
return nil, err
}
blockTag := latestBlockTag
if len(args) >= 2 {
blockTag, err = strFromArgs(args, 1)
if err != nil {
return nil, err
}
}
return s.withStore(func(st *store.Store) (any, error) {
base := s.ethereumNonceFloor(s.currentEthBlockNumber())
hasMinedHistory := false
if minedNonce, ok, nonceErr := s.latestMinedNonceForAddress(st, address); nonceErr != nil {
return nil, nonceErr
} else if ok {
base = minedNonce
hasMinedHistory = true
}
switch blockTag {
case pendingBlockTag:
pending := base
maxNonce := s.maximumAcceptedEthereumNonce()
if highestPending, ok, pendingErr := s.highestPendingNonceForAddress(st, address.String()); pendingErr != nil {
return nil, pendingErr
} else if ok && highestPending >= pending {
if highestPending >= maxNonce {
return nil, ethInvalidParams("no acceptable pending nonce available")
}
if highestPending == math.MaxUint64 {
pending = math.MaxUint64
} else {
pending = highestPending + 1
}
}
if pending > maxNonce {
pending = maxNonce
}
return hexutil.Uint64(pending), nil
case latestBlockTag, safeBlockTag, finalizedBlockTag:
return hexutil.Uint64(base), nil
case earliestBlockTag:
return hexutil.Uint64(0), nil
default:
// Explicit historical block-number queries are compatibility-oriented: validate the tag but
// return the latest confirmed nonce for Ethereum-derived accounts and the height fallback otherwise.
height, parseErr := parseBlockTag(blockTag)
if parseErr != nil {
return nil, parseErr
}
if hasMinedHistory {
return hexutil.Uint64(base), nil
}
return hexutil.Uint64(s.ethereumNonceFloor(height)), nil
}
})
}
// EthGetBlockTransactionCountByHash() returns the number of transactions in a block by hash
func (s *Server) EthGetBlockTransactionCountByHash(args []any) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
blockHash, err := bytesFromArgs(args)
if err != nil {
return nil, err
}
block, err := blockByHashOrNil(st, blockHash)
if err != nil {
return nil, err
}
if block == nil {
return ethNullResult(), nil
}
return hexutil.Uint64(block.BlockHeader.NumTxs), nil
})
}
// EthGetBlockTransactionCountByNumber() returns the number of transactions in a block by height
func (s *Server) EthGetBlockTransactionCountByNumber(args []any) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
blockHeight, err := s.blockHeightFromNumberArg(args, 0)
if err != nil {
return nil, err
}
block, err := blockByHeightOrNil(st, blockHeight)
if err != nil {
return nil, err
}
if block == nil {
return ethNullResult(), nil
}
return hexutil.Uint64(block.BlockHeader.NumTxs), nil
})
}
// EthGetUncleCountByBlockHash() n/a to Canopy as NestBFT doesn't have the concept of 'uncles'
func (s *Server) EthGetUncleCountByBlockHash(_ []any) (any, error) { return "0x0", nil }
// EthGetUncleCountByBlockNumber() n/a to Canopy as NestBFT doesn't have the concept of 'uncles'
func (s *Server) EthGetUncleCountByBlockNumber(_ []any) (any, error) { return "0x0", nil }
// EthGetCode() returns pseudo-ERC20 code for the CNPY contract and echoes the EOA address for everything else
func (s *Server) EthGetCode(args []any) (any, error) {
// get the address from the args
address, err := addressFromArgs(args)
if err != nil {
return nil, err
}
// get the string for the address
addressString := "0x" + address.String()
// if asking about the canopy pseudo-contract address
switch addressString {
case fsm.CNPYContractAddress, fsm.SwapCNPYContractAddress, fsm.StakedCNPYContractAddress:
return CanopyPseudoContractByteCode, nil
}
return "0x", nil
}
// EthSendRawTransaction() converts the RLP transaction into a Canopy compatible transaction and submits it
// - a valid RLP signature is considered a valid signature in Canopy for send transactions
func (s *Server) EthSendRawTransaction(args []any) (any, error) {
// extract the raw transaction bytes
rawTx, err := bytesFromArgs(args)
if err != nil {
return nil, err
}
var ethTx types.Transaction
if err = ethTx.UnmarshalBinary(rawTx); err != nil {
return nil, err
}
// convert it to a Canopy send transaction
transaction, err := fsm.RLPToCanopyTransaction(rawTx)
if err != nil {
return nil, err
}
// ensure created height stays inside Canopy's accepted replay window
if transaction.CreatedHeight < s.minimumAcceptedEthereumNonce() {
return nil, lib.ErrInvalidTxHeight()
}
if transaction.CreatedHeight > s.maximumAcceptedEthereumNonce() {
return nil, lib.ErrInvalidTxHeight()
}
// marshal the transaction to protobuf
bz, err := lib.Marshal(transaction)
if err != nil {
return nil, err
}
// send transaction to controller
if err = s.controller.SendTxMsgs([][]byte{bz}); err != nil {
return nil, err
}
// track the pending transaction using the canonical ethereum tx hash
txHashString := strings.ToLower(ethTx.Hash().Hex())
registerPendingEthTx(txHashString, transaction)
// return the transaction hash
return txHashString, nil
}
// EthCall() simulates a call to a 'smart contract' for Canopy
func (s *Server) EthCall(args []any) (any, error) {
if len(args) < 1 {
return nil, ethInvalidParams("missing call arguments")
}
// handle the block tag
height, err := blockTagFromArgs(args)
if err != nil {
return nil, err
}
// extract the call data
callParams, ok := args[0].(map[string]any)
if !ok {
return nil, ethInvalidParams("invalid call argument format")
}
// get the sender address hex
fromHex, ok := callParams["from"].(string)
if !ok {
fromHex = "0x" + strings.Repeat("0", 20)
}
// parse the `data` field from the call data
dataHex, ok := callParams["data"].(string)
if !ok {
return nil, ethInvalidParams("invalid or missing 'data' field")
}
// parse the `to` field from the call data
toHex, _ := callParams["to"].(string)
switch toHex {
default:
// exit as it's a non-contract call
return "0x", nil
case fsm.CNPYContractAddress, fsm.StakedCNPYContractAddress, fsm.SwapCNPYContractAddress:
// continue
}
// get the sender address
fromAddress, err := crypto.NewAddressFromString(cleanHex(fromHex))
if err != nil {
return nil, err
}
// decode the data from hex
data, err := lib.StringToBytes(cleanHex(dataHex[:]))
if err != nil {
return nil, ethInvalidParams(fmt.Sprintf("invalid hex: %v", err))
}
// validate the data length
if len(data) < 4 {
return nil, ethInvalidParams("insufficient data length")
}
// parse the selector
selector := lib.BytesToString(data[:4])
// create a read-only state for the block tag and write the height
var encoded hexutil.Bytes
return encoded, s.readOnlyState(height, func(state *fsm.StateMachine) lib.ErrorI {
switch selector {
case "95d89b41": // symbol()
switch toHex {
case fsm.CNPYContractAddress:
encoded, err = pack(ABIStringType, "CNPY")
case fsm.StakedCNPYContractAddress:
encoded, err = pack(ABIStringType, "stCNPY")
case fsm.SwapCNPYContractAddress:
encoded, err = pack(ABIStringType, "swCNPY")
}
case "06fdde03": // name()
switch toHex {
case fsm.CNPYContractAddress:
encoded, err = pack(ABIStringType, "Canopy")
case fsm.StakedCNPYContractAddress:
encoded, err = pack(ABIStringType, "Staked Canopy")
case fsm.SwapCNPYContractAddress:
encoded, err = pack(ABIStringType, "Swap Canopy")
}
case "313ce567": // decimals()
encoded, err = pack(ABIUint8Type, uint8(6))
case "18160ddd": // totalSupply()
supply, e := state.GetSupply()
if e != nil {
return e
}
switch toHex {
case fsm.CNPYContractAddress:
encoded, err = pack(ABIUint256Type, new(big.Int).SetUint64(supply.Total))
case fsm.StakedCNPYContractAddress:
encoded, err = pack(ABIUint256Type, new(big.Int).SetUint64(supply.Staked))
case fsm.SwapCNPYContractAddress:
escrowed, er := state.GetTotalEscrowed(nil)
if er != nil {
return er
}
encoded, err = pack(ABIUint256Type, new(big.Int).SetUint64(escrowed))
}
case "70a08231": // balanceOf(address)
address, e := parseAddressFromABI(data)
if e != nil {
return e
}
var balance uint64
switch toHex {
case fsm.CNPYContractAddress:
balance, e = state.GetAccountSpendableBalance(address)
if e != nil {
return e
}
case fsm.StakedCNPYContractAddress:
val, e := state.GetValidator(address)
if e != nil {
return e
}
balance = val.StakedAmount
case fsm.SwapCNPYContractAddress:
balance, e = state.GetTotalEscrowed(address)
if e != nil {
return e
}
}
encoded, err = pack(ABIUint256Type, new(big.Int).SetUint64(balance))
case "a9059cbb": // transfer(address,uint256)
if toHex == fsm.StakedCNPYContractAddress || toHex == fsm.SwapCNPYContractAddress {
return lib.NewError(1, "ethereum", fmt.Sprintf("unsupported selector: 0x%s", selector))
}
_, amount, e := parseAddressAndAmountFromABI(data)
if e != nil {
return e
}
balance, e := state.GetAccountSpendableBalance(fromAddress)
if e != nil {
return e
}
if balance < amount {
encoded, err = revert("ERC20: transfer amount exceeds balance")
break
}
encoded, err = pack(ABIBoolType, true)
case "23b872dd", "095ea7b3", "dd62ed3e", "79cc6790", "42966c68", "40c10f19": // unsupported ERC20 methods
encoded, err = revert("ERC20: method not supported")
default:
return lib.NewError(1, "ethereum", fmt.Sprintf("unsupported selector: 0x%s", selector))
}
if err != nil {
return lib.NewError(1, "ethereum", err.Error())
}
return nil
})
}
// EthEstimateGas() returns the corresponding Canopy fee for the message
func (s *Server) EthEstimateGas(args []any) (any, error) {
if len(args) < 1 {
return nil, errors.New("missing call arguments")
}
// extract the call data
callParams, ok := args[0].(map[string]any)
if !ok {
return nil, errors.New("invalid call argument format")
}
// parse the `data` field from the call data
dataHex, _ := callParams["data"].(string)
// create a txRequest
req, err := new(txRequest), error(nil)
// if invalid selector data return send
if len(dataHex) < 10 {
err = s.getFeeFromState(req, fsm.MessageSendName)
} else {
switch dataHex[2:10] {
case fsm.StakeSelector:
err = s.getFeeFromState(req, fsm.MessageStakeName)
case fsm.EditStakeSelector:
err = s.getFeeFromState(req, fsm.MessageEditStakeName)
case fsm.UnstakeSelector:
err = s.getFeeFromState(req, fsm.MessageUnstakeName)
case fsm.CreateOrderSelector:
err = s.getFeeFromState(req, fsm.MessageCreateOrderName)
case fsm.EditOrderSelector:
err = s.getFeeFromState(req, fsm.MessageEditOrderName)
case fsm.DeleteOrderSelector:
err = s.getFeeFromState(req, fsm.MessageDeleteOrderName)
case fsm.SubsidySelector:
err = s.getFeeFromState(req, fsm.MessageSubsidyName)
default:
err = s.getFeeFromState(req, fsm.MessageSendName)
}
}
if err != nil {
return nil, err
}
return hexutil.Uint64(req.Fee * 100), nil
}
// EthGetBlockByHash() returns a dummy-ish block (based on the actual Canopy block) that is EIP-1559 compatible
func (s *Server) EthGetBlockByHash(args []any) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
blockHash, e := bytesFromArgs(args)
if e != nil {
return nil, e
}
fullTxs := boolFromArgs(args)
block, e := blockByHashOrNil(st, blockHash)
if e != nil {
return nil, e
}
if block == nil {
return ethNullResult(), nil
}
return s.blockToEIP1559Block(block, fullTxs)
})
}
// EthGetBlockByNumber() returns a dummy-ish block (based on the actual Canopy block) that is EIP-1559 compatible
func (s *Server) EthGetBlockByNumber(args []any) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
blockHeight, err := s.blockHeightFromNumberArg(args, 0)
if err != nil {
return nil, err
}
fullTxs := boolFromArgs(args)
block, err := blockByHeightOrNil(st, blockHeight)
if err != nil {
return nil, err
}
if block == nil {
return ethNullResult(), nil
}
return s.blockToEIP1559Block(block, fullTxs)
})
}
// EthGetTransactionByHash() returns a canonical Ethereum transaction object for mined or pending transactions
func (s *Server) EthGetTransactionByHash(args []any) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
hashString, err := normalizedHashFromArgs(args)
if err != nil {
return nil, err
}
tx, block, err := s.findIndexedTxByHash(st, hashString)
if err != nil {
return nil, err
}
if tx != nil {
clearPendingEthTx(hashString)
return s.txToEthTransaction(block, tx, false)
}
if pending := s.findPendingEthTx(hashString); pending != nil {
return s.pendingTxToEthTransaction(pending), nil
}
return ethNullResult(), nil
})
}
// EthGetTransactionByBlockHashAndIndex() returns an EIP-1559 compatible tx + receipt
func (s *Server) EthGetTransactionByBlockHashAndIndex(args []any) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
blockHash, e := bytesFromArgs(args)
if e != nil {
return nil, e
}
index, e := intFromArgs(args, 1)
if e != nil {
return nil, e
}
block, e := blockByHashOrNil(st, blockHash)
if e != nil {
return nil, e
}
tx, ok := txAtBlockIndex(block, index)
if !ok {
return ethNullResult(), nil
}
return s.txToEthTransaction(block, tx, false)
})
}
// EthGetTransactionByBlockNumAndIndex() returns an EIP-1559 compatible tx + receipt
func (s *Server) EthGetTransactionByBlockNumAndIndex(args []any) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
blockHeight, e := s.blockHeightFromNumberArg(args, 0)
if e != nil {
return nil, e
}
index, e := intFromArgs(args, 1)
if e != nil {
return nil, e
}
block, e := blockByHeightOrNil(st, blockHeight)
if e != nil {
return nil, e
}
tx, ok := txAtBlockIndex(block, index)
if !ok {
return ethNullResult(), nil
}
return s.txToEthTransaction(block, tx, false)
})
}
// EthGetTransactionReceipt() returns a canonical Ethereum receipt only for mined transactions
func (s *Server) EthGetTransactionReceipt(args []any) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
hashString, err := normalizedHashFromArgs(args)
if err != nil {
return nil, err
}
tx, block, err := s.findIndexedTxByHash(st, hashString)
if err != nil {
return nil, err
}
if tx == nil {
return ethNullResult(), nil
}
clearPendingEthTx(hashString)
return s.txToEthReceipt(block, tx)
})
}
// EthGetUncleByBlockHashAndIndex() returns null (no uncles) as expected
func (s *Server) EthGetUncleByBlockHashAndIndex(_ []any) (any, error) {
return ethNullResult(), nil
}
// EthGetUncleByBlockNumAndIndex() returns null (no uncles) as expected
func (s *Server) EthGetUncleByBlockNumAndIndex(_ []any) (any, error) {
return ethNullResult(), nil
}
// EthNewFilter() creates a filter object, based on filter options, to notify when the state changes
func (s *Server) EthNewFilter(args []any) (any, error) {
// convert the args to filter params
params, err := filterParamsFromArgs(args)
if err != nil {
return nil, err
}
// create the filter
return s.newEthFilter(params)
}
// EthNewBlockFilter() creates a filter object, updating when a new block is produced
func (s *Server) EthNewBlockFilter(_ []any) (any, error) {
return s.newEthFilter(newFilterParams{filter: ethFilter{Blocks: true}})
}
// EthNewPendingTxsFilter() creates a filter object, updating when a new transaction is processed
func (s *Server) EthNewPendingTxsFilter(_ []any) (any, error) {
return s.newEthFilter(newFilterParams{filter: ethFilter{PendingTxs: true}})
}
// EthUninstallFilter() deletes a filter object
func (s *Server) EthUninstallFilter(args []any) (any, error) {
// get the filter id
id, err := strFromArgs(args, 0)
if err != nil {
return nil, err
}
// delete the filter from the sync.map
_, deleted := ethFilters.LoadAndDelete(id)
return deleted, nil
}
// EthGetFilterChanges() gets the latest logs since the last filter call (simulated using lastReadHeight
func (s *Server) EthGetFilterChanges(args []any) (any, error) {
// get the filter id
id, err := strFromArgs(args, 0)
if err != nil {
return nil, err
}
// get the filter
filter, lastReadHeight, err := s.getEthFilter(id)
if err != nil {
return nil, err
}
// call ethGetLogs
return s.ethGetLogs(filter, lastReadHeight)
}
// EthGetFilterLogs() returns an array of all logs matching a pre-created filter with given id
func (s *Server) EthGetFilterLogs(args []any) (any, error) {
// get the filter id
id, err := strFromArgs(args, 0)
if err != nil {
return nil, err
}
// get the filter
filter, _, err := s.getEthFilter(id)
if err != nil {
return nil, err
}
// call ethGetLogs
return s.ethGetLogs(filter, 0)
}
// EthGetLogs() returns an array of all logs matching the passed filter argument
func (s *Server) EthGetLogs(args []any) (any, error) {
// convert the args to filter params
params, err := filterParamsFromArgs(args)
if err != nil {
return nil, err
}
// call ethGetLogs
return s.ethGetLogs(¶ms.filter, 0)
}
// MAJOR HELPER FUNCTIONS BELOW
// blockToEIP1559Block() attempts to convert a Canopy block to a EIP1559Block for display only
func (s *Server) blockToEIP1559Block(block *lib.BlockResult, fullTx bool) (ethRPCBlock, error) {
// ensure the block exists
if block.BlockHeader.Hash == nil {
return ethRPCBlock{}, errors.New("block not found")
}
// get the minimum send tx fee
tx := new(txRequest)
if err := s.getFeeFromState(tx, fsm.MessageSendName); err != nil {
return ethRPCBlock{}, err
}
// tx.Fee x 100 to ensure always above 21,000
sendFee := big.NewInt(int64(tx.Fee * 100))
// make a structure to capture the EIP-1559 transactions
transactions := make([]interface{}, 0, len(block.Transactions))
for _, tx := range block.Transactions {
if fullTx {
eip1559Tx, e := s.txToEthTransaction(block, tx, false)
if e != nil {
return ethRPCBlock{}, e
}
transactions = append(transactions, eip1559Tx)
} else {
transactions = append(transactions, ethHashStringFromTxResult(tx))
}
}
// create the EIP-1559 block
return ethRPCBlock{
Number: hexutil.Big(*big.NewInt(int64(block.BlockHeader.Height))),
Difficulty: hexutil.Big(*big.NewInt(0)),
Hash: common.BytesToHash(block.BlockHeader.Hash),
ParentHash: common.BytesToHash(block.BlockHeader.LastBlockHash),
Sha3Uncles: types.EmptyUncleHash,
LogsBloom: types.Bloom{},
StateRoot: common.BytesToHash(block.BlockHeader.StateRoot),
Miner: common.BytesToAddress(block.BlockHeader.ProposerAddress),
ExtraData: hexutil.Bytes("Canopy EIP1559 Wrapper is for display only"),
GasLimit: 50_000_000,
GasUsed: hexutil.Uint64(new(big.Int).Mul(sendFee, big.NewInt(int64(len(block.Transactions)))).Uint64()),
Timestamp: hexutil.Uint64(time.UnixMicro(int64(block.BlockHeader.Time)).Unix()),
TransactionsRoot: common.BytesToHash(block.BlockHeader.TransactionRoot),
ReceiptsRoot: common.BytesToHash(block.BlockHeader.TransactionRoot),
BaseFeePerGas: hexutil.Big(*big.NewInt(ethGasPrice)),
WithdrawalsRoot: types.EmptyWithdrawalsHash,
ParentBeaconBlockRoot: common.BytesToHash(block.BlockHeader.ValidatorRoot),
RequestsHash: types.EmptyRequestsHash,
Size: hexutil.Uint64(block.Meta.Size),
Transactions: transactions,
Uncles: make([]common.Hash, 0),
}, nil
}
// txToEthTransaction() converts a Canopy transaction into a canonical Ethereum transaction object
func (s *Server) txToEthTransaction(b *lib.BlockResult, tx *lib.TxResult, pending bool) (any, error) {
if ethTx, ok := ethTransactionFromCanopyTx(tx.Transaction); ok {
return marshalCanonicalEthTransaction(ethTx, common.BytesToAddress(tx.Sender), b, tx, pending)
}
hash := common.HexToHash(ethHashStringFromTxResult(tx))
from := common.BytesToAddress(tx.Sender)
gasPrice := big.NewInt(ethGasPrice)
gasFeeCap := big.NewInt(ethGasPrice)
gasTipCap := big.NewInt(0)
gas := uint64(tx.Transaction.Fee)
nonce := tx.Transaction.CreatedHeight
input := []byte{}
value := fsm.UpscaleTo18Decimals(sendAmountFromTxResult(tx))
chainID := big.NewInt(int64(evmChainIDFromTx(tx.Transaction)))
var to *common.Address
if len(tx.Recipient) != 0 {
recipient := common.BytesToAddress(tx.Recipient)
to = &recipient
}
result := ethRPCTransaction{
BlockHash: nil,
BlockNumber: nil,
From: from,
Gas: hexutil.Uint64(gas),
GasPrice: (*hexutil.Big)(gasPrice),
GasFeeCap: (*hexutil.Big)(gasFeeCap),
GasTipCap: (*hexutil.Big)(gasTipCap),
Hash: hash,
Input: hexutil.Bytes(input),
Nonce: hexutil.Uint64(nonce),
To: to,
TransactionIndex: nil,
Value: hexutil.Big(*value),
Type: types.DynamicFeeTxType,
ChainID: (*hexutil.Big)(chainID),
}
if !pending {
blockHash := common.BytesToHash(b.BlockHeader.Hash)
blockNumber := hexutil.Big(*big.NewInt(int64(tx.Height)))
txIndex := hexutil.Uint64(tx.Index)
result.BlockHash = &blockHash
result.BlockNumber = &blockNumber
result.TransactionIndex = &txIndex
}
return result, nil
}
// ethGetLogs() simulates eth_getLogs call by executing queries over the indexer and mempool
// - canopy only has 1 pseudo-smart contract and only 1 event (transfer) the implementation is simple
// - canopy generates the logs in real-time upon call by using the TxIndexer
func (s *Server) ethGetLogs(filter *ethFilter, lastReadHeight uint64) (any, error) {
return s.withStore(func(st *store.Store) (any, error) {
var strResults []string
// handle pending txs filter
if filter.PendingTxs {
s.controller.Mempool.L.Lock()
transactions := s.controller.Mempool.GetTransactions(math.MaxUint64)
s.controller.Mempool.L.Unlock()
for _, tx := range transactions {
transaction := new(lib.Transaction)
if err := lib.Unmarshal(tx, transaction); err == nil {
if ethHash := ethHashStringFromTransaction(transaction); ethHash != "" {
strResults = append(strResults, ethHash)
continue
}
}
strResults = append(strResults, "0x"+crypto.HashString(tx))
}
return strResults, nil
}
// handle new blocks filter
if filter.Blocks {
// from the last read height to the chain height
for i := lastReadHeight; i < s.controller.ChainHeight(); i++ {
block, e := st.GetBlockHeaderByHeight(i)
if e != nil {
return nil, e
}
strResults = append(strResults, "0x"+lib.BytesToString(block.BlockHeader.Hash))
}
return strResults, nil
}
if !filterSupportsPseudoTransferLogs(filter) {
return make([]ethRPCLog, 0), nil
}
if filter.BlockHash != "" {
if lastReadHeight != 0 {
return make([]ethRPCLog, 0), nil
}
blockHash, err := lib.StringToBytes(cleanHex(filter.BlockHash))
if err != nil {
return nil, ethInvalidParams(err.Error())
}
block, err := st.GetBlockByHash(blockHash)
if err != nil {
if isNotFoundErr(err) {
return make([]ethRPCLog, 0), nil
}