-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
836 lines (735 loc) · 23.8 KB
/
main.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
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
package main
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/sha256"
"crypto/tls"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"math/big"
"net/http"
"os"
"os/signal"
"strings"
"sync"
"time"
"github.com/edgelesssys/ego/attestation"
"github.com/edgelesssys/ego/enclave"
gethcmn "github.com/ethereum/go-ethereum/common"
gethmath "github.com/ethereum/go-ethereum/common/math"
gethcrypto "github.com/ethereum/go-ethereum/crypto"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"github.com/vechain/go-ecvrf"
"github.com/smartbch/egvm/keygrantor"
"github.com/elfinguard/elfinguard/authorizer/constants"
"github.com/elfinguard/elfinguard/authorizer/request"
"github.com/elfinguard/elfinguard/authorizer/router"
"github.com/elfinguard/elfinguard/certs"
"github.com/elfinguard/elfinguard/types"
)
var (
ListenAddr string // IP address and port
EnableTLS bool // Enable TLS (serve https instead of http)
AllowedAddressesFilePath string // The file path for json file brought in and read when authorizer starts
JsonFileProvided bool
ChainId *big.Int // Which blockchain does this enclave support?
RpcUrlList []string // This enclave queries these RPC servers for on-chain state
KeyGrantor string // The key grantor's hostname(or ip) and port, seperated by colon
RecryptorSignerID []byte // The recryptor enclaves' SignerID
RecryptorUniqueID []byte // The recryptor enclaves' UniqueID
PrivKey *ecdsa.PrivateKey // This key is generated by hardware, used for signing, VRF and ECDH
PubKeyBz []byte // Compressed pubkey for PrivKey
MyAddress gethcmn.Address // EVM address calculated from PrivKey
AllowedToAccounts []gethcmn.Address
AllowedSourceContracts []gethcmn.Address
AllowedTargetContracts []gethcmn.Address
AllowedApis string
AvailableApis = []string{
constants.APIPing, constants.APIGetTx, constants.APIGetLog,
constants.APIGetCall, constants.APIGrantCode, constants.APISGXReport, constants.APIAzureToken, constants.APICert, constants.APICertReport, constants.APIPubkey, constants.APIPubkeyReport,
}
EcdhCache *types.EcdhCache
AttestationProviderURL string // An attestation provider wraps an attestation report to a JWT
RequiredConfirmations int // When should we take a transaction as finalized?
)
const (
HttpsCertFile = "./key/cert.pem"
EncryptedHttpsKeyFile = "./key/encryptedKey.txt"
DecryptedHttpsKeyFile = "./key/decryptedKey.pem"
IsEnclaveMode = true
TotalRpcTimeoutTime = 10 * time.Second
MaxTimeDifference = int64(600) // time difference between requestor and authorizer must be less than 10 minutes
MaxMemForParsing = 2 * 1024 * 1024 // maximum DRAM ParseMultipartForm can use
)
type VerifyRemoteReportFn func(reportBytes []byte) (attestation.Report, error)
type GetRemoteReportFn func(reportBytes []byte) (report []byte, err error)
var httpGet func(url string, usingHttps bool) []byte = simpleHttpGet
var verifyRemoteReportFn VerifyRemoteReportFn = enclave.VerifyRemoteReport
var getRemoteReport GetRemoteReportFn = enclave.GetRemoteReport
var _rpcClient = &rpcClient{
dialContext: ethDialContext,
addressCheckFunc: isInAddressList,
requiredConfirmations: RequiredConfirmations,
totalRpcTimeoutTime: TotalRpcTimeoutTime,
}
func main() {
if len(os.Args) > 1 && os.Args[1] == "gen-cert-files" {
certs.GenCertFiles(IsEnclaveMode)
return
}
initLogger()
parseFlags()
getAddresses()
genKeys()
if EnableTLS {
createAndStartHttpsServer()
return
}
createAndStartHttpServer()
}
func parseFlags() {
flag.BoolVar(&EnableTLS, "tls", true, "use TLS or not")
flag.StringVar(&ListenAddr, "listen-addr", "0.0.0.0:8882", "listen address")
flag.StringVar(&AllowedAddressesFilePath, "allowed-address", "", "allowed addresses file path")
flag.StringVar(&AllowedApis, "apis", "*", "allowed apis")
cacheSize := flag.Int("cache", 2000, "size of the ecdh cache")
chainId := flag.String("chainid", "10000", "Chain Id")
requiredConfirmationNumberArg := flag.Int("conformation", 10, "required confirmation number")
rpcUrlListArg := flag.String("rpc-addrs", "", "RPC server address list, seperated by comma")
attestationProviderURLArg := flag.String("attestation", "https://shareduks.uks.attest.azure.net", "attestation provider's URL")
recryptorSignerArg := flag.String("recryptor-signerid", "", "recryptor signer ID")
recryptorUniqIDArg := flag.String("recryptor-uniqueid", "", "recryptor unique ID")
keyGrantor := flag.String("key-grantor", "", "key grantor's hostname(or ip) and port, seperated by colon")
flag.Parse()
var ok bool
ChainId, ok = new(big.Int).SetString(*chainId, 0)
if !ok {
panic("invalid chainid")
}
KeyGrantor = *keyGrantor
RequiredConfirmations = *requiredConfirmationNumberArg
RpcUrlList = strings.Split(*rpcUrlListArg, ",")
AttestationProviderURL = *attestationProviderURLArg
EcdhCache = types.NewEcdhCache(*cacheSize)
var err error
RecryptorSignerID, err = hex.DecodeString(*recryptorSignerArg)
if err != nil {
panic(err)
}
RecryptorUniqueID, err = hex.DecodeString(*recryptorUniqIDArg)
if err != nil {
panic(err)
}
log.Infof("listen addr: %v", ListenAddr)
}
func genKeys() {
PrivKey = getKeyFromKG(KeyGrantor)
PubKeyBz = gethcrypto.CompressPubkey(&PrivKey.PublicKey)
MyAddress = gethcrypto.PubkeyToAddress(PrivKey.PublicKey)
log.Infof("Authorizer PubKeyBz: %v", gethcmn.Bytes2Hex(PubKeyBz))
log.Infof("Authorizer Address: %v", MyAddress.String())
}
func getKeyFromKG(keyGrantor string) *ecdsa.PrivateKey {
log.Info("get key from:", keyGrantor)
bip32Key, err := keygrantor.GetKeyFromKeyGrantor(keyGrantor, [32]byte{})
if err != nil {
log.Fatal("failed to get key from grantor", err)
}
ecdsaKey, err := gethcrypto.ToECDSA(bip32Key.Key)
if err != nil {
log.Fatal("failed to convert key", err)
}
return ecdsaKey
}
func initLogger() {
log.SetFormatter(&log.TextFormatter{
ForceQuote: true,
TimestampFormat: "2006-01-02 15:04:05",
FullTimestamp: true,
})
}
func createAndStartHttpServer() {
ginRouter := router.SetupRouter(MaxMemForParsing)
initHttpHandlers(ginRouter)
server := &http.Server{
Addr: ListenAddr,
Handler: ginRouter,
}
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Errorf("listen error: %v", err)
}
}()
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt, os.Kill)
<-quit
log.Println("shutdown server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Errorf("shutdown err: %v", err)
}
}
func createAndStartHttpsServer() {
ginRouter := router.SetupRouter(MaxMemForParsing)
initHttpHandlers(ginRouter)
certificate, err := certs.LoadCertAndDecryptedKey(HttpsCertFile, DecryptedHttpsKeyFile)
if err != nil {
log.Errorf("Failed to load encrypted https key and certificate: %v", err)
return
}
server := &http.Server{
Addr: ListenAddr,
Handler: ginRouter,
TLSConfig: &tls.Config{Certificates: []tls.Certificate{certificate}},
}
go func() {
if err := server.ListenAndServeTLS("", ""); err != nil && err != http.ErrServerClosed {
log.Errorf("listen error: %v", err)
}
}()
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt, os.Kill)
<-quit
log.Println("shutdown server ...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Errorf("shutdown err: %v", err)
}
}
func initHttpHandlers(router gin.IRouter) {
for _, handler := range getApis() {
switch handler {
case constants.APIPing:
router.GET("/eg_ping", pingFunc)
case constants.APIGetTx:
router.GET("/eg_tx", getTxFunc)
case constants.APIGetLog:
router.GET("/eg_log", getLogFunc)
case constants.APIGetCall:
router.GET("/eg_call", getCallFunc)
case constants.APIGrantCode:
router.GET("/eg_grantcode", getGrantcodeFunc)
case constants.APISGXReport:
router.GET("/sgx_report", getSgxReportFunc)
case constants.APIAzureToken:
router.GET("/azure_token", getAzureTokenFunc)
case constants.APICert:
router.GET("/cert", getCertFunc)
case constants.APICertReport:
router.GET("/cert_report", getCertReportFunc)
case constants.APIPubkey:
router.GET("/pubkey", getPubkeyFunc)
case constants.APIPubkeyReport:
router.GET("/pubkey_report", getPubkeyReportFunc)
default:
continue
}
}
}
func pingFunc(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"isSuccess": true,
"message": "pong",
})
}
func getTxFunc(c *gin.Context) {
req := &request.GetTxReq{}
err := req.Bind(c)
if err != nil {
log.Errorf("bind request err: %v", err)
c.String(http.StatusBadRequest, "bind request err: %v", err)
return
}
bz, err := getFromAllServers(func(rpcUrl string) ([]byte, error) {
return _rpcClient.getTxInfo(rpcUrl, req.TxCommonHash)
})
result := finishSigning(bz, err)
c.JSON(http.StatusOK, result)
}
func getLogFunc(c *gin.Context) {
req := &request.GetLogReq{}
err := req.Bind(c)
if err != nil {
log.Errorf("bind request err: %v", err)
c.String(http.StatusBadRequest, "bind request err: %v", err)
return
}
if !isInAddressList(req.ContractAddrCmn, AllowedSourceContracts) {
c.String(http.StatusBadRequest, "source contract not found in provided json file")
}
bz, err := getFromAllServers(func(rpcUrl string) ([]byte, error) {
return _rpcClient.getLogInfo(rpcUrl, req.BlockHashCmn, req.ContractAddrCmn, req.TopicsCmn)
})
result := finishSigning(bz, err)
c.JSON(http.StatusOK, result)
}
func getCallFunc(c *gin.Context) {
req := &request.GetCallReq{}
err := req.Bind(c)
if err != nil {
log.Errorf("bind request err: %v", err)
c.String(http.StatusBadRequest, "bind request err: %v", err)
return
}
// if !isInAddressList(req.ContractAddrCmn, AllowedTargetContracts) {
if !isInAddressList(req.ContractAddrCmn, AllowedTargetContracts) {
c.String(http.StatusBadRequest, "target contract not found in provided json file")
}
bz, err := getFromAllServers(func(rpcUrl string) ([]byte, error) {
return _rpcClient.getEthCallInfo(rpcUrl, req.ContractAddrCmn, req.FromAddrCmn, req.CallDataBz)
})
result := finishSigning(bz, err)
c.JSON(http.StatusOK, result)
}
func getGrantcodeFunc(c *gin.Context) {
// recryptor needs AuthResult response
var errResult *types.AuthResult
req := &request.GetGrantcodeReq{}
err := req.Bind(c)
if err != nil {
log.Errorf("bind request err: %v", err)
errResult = &types.AuthResult{
Succeeded: false,
Message: fmt.Sprintf("bind request err: %v", err),
}
c.JSON(http.StatusBadRequest, errResult)
return
}
now := time.Now().Unix()
if req.Time < now-MaxTimeDifference || now+MaxTimeDifference < req.Time {
errResult = &types.AuthResult{
Succeeded: false,
Message: "time difference is too large",
}
c.JSON(http.StatusBadRequest, errResult)
return
}
var secret []byte
// if the requestor is a recryptor enclave, it must attach its public key and attestation report
if len(req.RecryptorPubkeyBz) != 0 {
log.Infof("recryptor pubkey: %v", gethcmn.Bytes2Hex(req.RecryptorPubkeyBz))
secret, errResult = CheckRecryptor(req.RecryptorPubkeyBz, req.ReportBz)
if errResult != nil {
c.JSON(http.StatusBadRequest, errResult)
return
}
}
result := GetGrantCode(req.Time, req.ContractAddrCmn, req.CallDataList, req.CallDataBzList, req.Nth, req.OutDataBz, req.SigBz, secret)
c.JSON(http.StatusOK, result)
}
func getSgxReportFunc(c *gin.Context) {
if len(PubKeyBz) == 0 {
return
}
hash := sha256.Sum256(PubKeyBz)
report, err := enclave.GetRemoteReport(hash[:])
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
// c.String(http.StatusOK, hex.EncodeToString(PubKeyBz)+","+hex.EncodeToString(report))
c.String(http.StatusOK, hex.EncodeToString(PubKeyBz)+","+hex.EncodeToString(report))
}
func getAzureTokenFunc(c *gin.Context) {
if len(PubKeyBz) == 0 {
return
}
token, err := enclave.CreateAzureAttestationToken(PubKeyBz, AttestationProviderURL)
if err != nil {
c.String(http.StatusInternalServerError, err.Error())
return
}
c.String(http.StatusOK, token)
}
func getCertFunc(c *gin.Context) {
cert, err := certs.LoadCertAndDecryptedKey(HttpsCertFile, DecryptedHttpsKeyFile)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
"error": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"result": "0x" + hex.EncodeToString(cert.Certificate[0]),
})
}
func getCertReportFunc(c *gin.Context) {
cert, err := certs.LoadCertAndDecryptedKey(HttpsCertFile, DecryptedHttpsKeyFile)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
"error": err.Error(),
})
return
}
certHash := sha256.Sum256(cert.Certificate[0])
// report, err := enclave.GetRemoteReport(certHash[:])
report, err := getRemoteReport(certHash[:])
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
"error": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"result": "0x" + hex.EncodeToString(report),
})
}
func getPubkeyFunc(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"success": true,
"result": "0x" + hex.EncodeToString(PubKeyBz),
})
}
func getPubkeyReportFunc(c *gin.Context) {
pbkHash := sha256.Sum256(PubKeyBz)
// report, err := enclave.GetRemoteReport(pbkHash[:])
report, err := getRemoteReport(pbkHash[:])
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"success": false,
"error": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"result": "0x" + hex.EncodeToString(report),
})
}
// ----------------------------------------------------------------
func simpleHttpGet(url string, usingHttps bool) []byte {
client := http.Client{Timeout: 3 * time.Second}
if usingHttps {
client.Transport =
&http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
}
resp, err := client.Get(url)
if err != nil {
fmt.Println(err)
return nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
fmt.Println(resp.Status)
return nil
}
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println(err)
return nil
}
return body
}
func verifyKeyReceiver(url string, signer, uniqueID []byte) []byte {
pubkeyAndReport := strings.Split(string(httpGet(url+"/sgx_report", true)), ",")
log.Infof("pubkeyAndReport: %v", pubkeyAndReport)
if len(pubkeyAndReport) != 2 {
panic("Invalid Peer Report")
}
peerPubkeyBytes, err := hex.DecodeString(pubkeyAndReport[0])
if err != nil {
panic(err)
}
reportBytes, err := hex.DecodeString(pubkeyAndReport[1])
if err != nil {
panic(err)
}
if err := verifyReport(reportBytes, peerPubkeyBytes, signer, uniqueID); err != nil {
panic(err)
}
log.Infof("verify receiver: %v passed", url)
return peerPubkeyBytes
}
func verifyReport(reportBytes, peerPubkeyBytes, signer, uniqueID []byte) error {
// report, err := enclave.VerifyRemoteReport(reportBytes)
report, err := verifyRemoteReportFn(reportBytes)
if err != nil {
return err
}
hash := sha256.Sum256(peerPubkeyBytes)
if !bytes.Equal(report.Data[:len(hash)], hash[:]) {
return errors.New("report data does not match the pubkey's hash")
}
if !bytes.Equal(report.UniqueID, uniqueID) {
return errors.New("invalid unique id")
}
if report.SecurityVersion < 2 {
return errors.New("invalid security version")
}
if binary.LittleEndian.Uint16(report.ProductID) != 0x001 {
return errors.New("invalid product")
}
if !bytes.Equal(report.SignerID, signer) {
return errors.New("invalid signer")
}
if report.Debug {
return errors.New("should not open debug")
}
return nil
}
// Ensures the recryptor enclave can be trusted
func CheckRecryptor(pubkey, reportBz []byte) (secret []byte, errResult *types.AuthResult) {
var recryptorPubkey [33]byte
copy(recryptorPubkey[:], pubkey)
secret, ok := EcdhCache.GetSecret(recryptorPubkey)
if ok {
return secret, nil
}
report, err := enclave.VerifyRemoteReport(reportBz)
if err != nil {
return nil, &types.AuthResult{Message: err.Error()}
}
hash := sha256.Sum256(pubkey)
if !bytes.Equal(report.Data[:len(hash)], hash[:]) {
return nil, &types.AuthResult{Message: "report data does not match the pubkey's hash"}
}
if !bytes.Equal(report.UniqueID, RecryptorUniqueID) {
return nil, &types.AuthResult{Message: "invalid unique id"}
}
if report.SecurityVersion < 2 {
return nil, &types.AuthResult{Message: "invalid security version"}
}
if binary.LittleEndian.Uint16(report.ProductID) != 0x001 {
return nil, &types.AuthResult{Message: "invalid product"}
}
if !bytes.Equal(report.SignerID, RecryptorSignerID) {
return nil, &types.AuthResult{Message: "invalid signer"}
}
if report.Debug {
return nil, &types.AuthResult{Message: "should not open debug"}
}
secret, err = EcdhCache.PeerKeyToSecret(PrivKey, recryptorPubkey, types.EncapsulateSecret)
if err != nil {
return nil, &types.AuthResult{Message: err.Error()}
}
return secret, nil
}
// Recover from-address using 'sig', then call the 'contractAddr' with 'callData' and use the output to generate grantcode
// If the requestor is a recryptor enclave, then 'secret' is not nil and the result must be encrypted
func GetGrantCode(timestamp int64, contractAddr gethcmn.Address, callDataListStr string, callDataList [][]byte, nth int, outData, sig, secret []byte) types.AuthResult {
if nth >= len(callDataList) {
return types.AuthResult{Message: "invalid nth value"}
}
callData := callDataList[nth]
if len(callData) < 4 {
return types.AuthResult{Message: "calldata too short"}
}
if len(outData) != 0 && len(secret) == 0 {
return types.AuthResult{Message: "only a Recryptor can specify output directly"}
}
var from gethcmn.Address
if len(sig) > 0 {
log.Infof("callDataListStr: %v", callDataListStr)
callDataHash := gethcrypto.Keccak256([]byte(callDataListStr))
log.Infof("callDataHash: %v", hex.EncodeToString(callDataHash))
txt := fmt.Sprintf("To Authorizer: timestamp=%d, contract=%s, data=0x%s", timestamp, contractAddr, hex.EncodeToString(callDataHash))
log.Infof("txt: %v", txt)
ethMsg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(txt), txt) //EIP191 prefix
ethMsgHash := gethcrypto.Keccak256([]byte(ethMsg))
pubkey, err := gethcrypto.SigToPub(ethMsgHash, sig)
if err != nil {
return types.AuthResult{Message: err.Error()}
}
from = gethcrypto.PubkeyToAddress(*pubkey)
log.Infof("from address: %v", from)
}
if len(outData) == 0 {
if len(callData) >= 36 {
copy(callData[4+12:], MyAddress[:]) // fill my address into callData
}
var err error
outData, err = getFromAllServers(func(rpcUrl string) ([]byte, error) {
return _rpcClient.ethCallForGrantCode(rpcUrl, contractAddr, from, callData)
})
if err != nil {
return types.AuthResult{Message: err.Error()}
}
}
packedBz := make([]byte, 32, 32+4+20+len(outData))
// copy(packedBz, gethmath.PaddedBigBytes(ChainId, 32))
copy(packedBz, gethmath.PaddedBigBytes(ChainId, 32))
packedBz = append(packedBz, callData[:4]...)
packedBz = append(packedBz, contractAddr[:]...)
packedBz = append(packedBz, outData...)
var hashBytes [32]byte
if len(secret) != 0 { // for recryptor
hashBytes = sha256.Sum256(packedBz)
} else { // for non-recryptor
copy(hashBytes[:], gethcrypto.Keccak256(packedBz))
}
beta, pi, err := ecvrf.Secp256k1Sha256Tai.Prove(PrivKey, hashBytes[:])
if err != nil {
return types.AuthResult{Message: err.Error()}
}
var salt [32]byte
binary.LittleEndian.PutUint64(salt[:8], uint64(time.Now().Unix()))
if _, err := types.NewRandReader().Read(salt[8:]); err != nil {
panic(err)
}
if len(secret) != 0 {
cryptor := types.NewCryptor(salt[:], secret)
beta, err = cryptor.EncryptAesGcm(beta)
if err != nil {
return types.AuthResult{Message: err.Error()}
}
}
authResult := types.AuthResult{
Succeeded: true,
Result: append(from[:], beta...),
Proof: pi,
Salt: salt[:],
PubKey: PubKeyBz,
}
return authResult
}
// Endorse a message by signing it with privKey
func signBytes(message []byte, privKey *ecdsa.PrivateKey) (sig []byte, err error) {
if privKey == nil {
return nil, errors.New("has no private key")
}
msgHash := gethcrypto.Keccak256Hash(message)
ethMsg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(msgHash[:]), msgHash[:])
ethMsgHash := gethcrypto.Keccak256Hash([]byte(ethMsg))
sig, err = gethcrypto.Sign(ethMsgHash[:], privKey)
if err == nil {
// v=27|28 instead of 0|1...
sig[len(sig)-1] += 27
}
return
}
func finishSigning(bz []byte, err error) types.AuthResult {
if err != nil {
return types.AuthResult{
Succeeded: false,
Message: err.Error(),
}
}
sig, err := signBytes(bz, PrivKey)
res := types.AuthResult{
Succeeded: err == nil,
Proof: sig,
Result: bz,
}
copy(res.PubKey[:], PubKeyBz)
if err != nil {
res.Message = err.Error()
}
return res
}
// Query multiple RPC servers and ensure they all return the same information
func getFromAllServers(getter func(rpcUrl string) ([]byte, error)) ([]byte, error) {
if len(RpcUrlList) == 0 {
panic("empty rpcUrlList")
}
resList := make([][]byte, len(RpcUrlList))
errList := make([]error, len(RpcUrlList))
wg := sync.WaitGroup{}
wg.Add(len(RpcUrlList))
for i, rpcUrl := range RpcUrlList {
go func(idx int, url string) {
resList[idx], errList[idx] = getter(url)
wg.Done()
}(i, rpcUrl)
}
wg.Wait()
// fail if one of nodes return error
for idx, err := range errList {
if err != nil {
return nil, fmt.Errorf("failed to query %s: %s", RpcUrlList[idx], err.Error())
}
}
// the results must be all equal
firstRes := resList[0]
for i := 1; i < len(resList); i++ {
if !bytes.Equal(firstRes, resList[i]) {
return nil, fmt.Errorf("result mismatch between %s and %s", RpcUrlList[0], RpcUrlList[i])
}
}
return firstRes, nil
}
func getApis() []string {
if len(AllowedApis) == 0 {
panic("invalid APIs specified")
}
if AllowedApis == "*" {
return AvailableApis
}
return findMatchingApis(strings.Split(AllowedApis, ","), AvailableApis)
}
func findMatchingApis(allowedApis, availableApis []string) []string {
if len(allowedApis) > len(availableApis) {
panic("too many APIs inputted")
}
availableApisSet := make(map[string]struct{}, len(availableApis))
for _, x := range availableApis {
availableApisSet[x] = struct{}{}
}
match := make([]string, 0, len(availableApis))
for _, x := range allowedApis {
if _, found := availableApisSet[x]; found {
match = append(match, x)
continue
}
// panic if mismatch found
panic("one or more APIs inputted is/are not available")
}
return match
}
func getAddresses() {
JsonFileProvided = true
// json file not provided
if AllowedAddressesFilePath == "" {
JsonFileProvided = false
return
}
jsonFile, err := os.ReadFile(AllowedAddressesFilePath)
if err != nil {
panic(err)
}
var result map[string]string
err = json.Unmarshal(jsonFile, &result)
if err != nil {
panic(err)
}
// TxInfo's toAccounts
stringToAccounts := strings.Split(result["toAccounts"], ",")
for _, address := range stringToAccounts {
AllowedToAccounts = append(AllowedToAccounts, gethcmn.HexToAddress(address))
}
// LogInfo's sourceContracts
stringSourceContracts := strings.Split(result["sourceContracts"], ",")
for _, address := range stringSourceContracts {
AllowedSourceContracts = append(AllowedSourceContracts, gethcmn.HexToAddress(address))
}
// EthCallInfo's targetContracts
stringTargetContracts := strings.Split(result["targetContracts"], ",")
for _, address := range stringTargetContracts {
AllowedTargetContracts = append(AllowedTargetContracts, gethcmn.HexToAddress(address))
}
}
func isInAddressList(address gethcmn.Address, list []gethcmn.Address) bool {
// continue on if no json file provided
if !JsonFileProvided {
return true
}
for _, l := range list {
if address == l {
return true
}
}
return false
}