-
Notifications
You must be signed in to change notification settings - Fork 209
/
ethereum.go
1216 lines (1095 loc) · 37.4 KB
/
ethereum.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
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
// Copyright © 2022 Kaleido, Inc.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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 ethereum
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/go-resty/resty/v2"
"github.com/hyperledger/firefly-common/pkg/config"
"github.com/hyperledger/firefly-common/pkg/ffresty"
"github.com/hyperledger/firefly-common/pkg/fftypes"
"github.com/hyperledger/firefly-common/pkg/i18n"
"github.com/hyperledger/firefly-common/pkg/log"
"github.com/hyperledger/firefly-common/pkg/wsclient"
"github.com/hyperledger/firefly-signer/pkg/abi"
"github.com/hyperledger/firefly/internal/coremsgs"
"github.com/hyperledger/firefly/internal/metrics"
"github.com/hyperledger/firefly/pkg/blockchain"
"github.com/hyperledger/firefly/pkg/core"
"github.com/santhosh-tekuri/jsonschema/v5"
)
const (
broadcastBatchEventSignature = "BatchPin(address,uint256,string,bytes32,bytes32,string,bytes32[])"
addressType = "address"
boolType = "bool"
booleanType = "boolean"
integerType = "integer"
tupleType = "tuple"
stringType = "string"
arrayType = "array"
objectType = "object"
)
type Ethereum struct {
ctx context.Context
topic string
prefixShort string
prefixLong string
capabilities *blockchain.Capabilities
callbacks callbacks
client *resty.Client
fftmClient *resty.Client
streams *streamManager
streamID string
wsconn wsclient.WSClient
closed chan struct{}
addressResolver *addressResolver
metrics metrics.Manager
ethconnectConf config.Section
subs map[string]subscriptionInfo
}
type subscriptionInfo struct {
namespace string
version int
}
type callbacks struct {
handlers map[string]blockchain.Callbacks
}
func (cb *callbacks) BlockchainOpUpdate(ctx context.Context, plugin blockchain.Plugin, nsOpID string, txState blockchain.TransactionStatus, blockchainTXID, errorMessage string, opOutput fftypes.JSONObject) {
namespace, _, _ := core.ParseNamespacedOpID(ctx, nsOpID)
if handler, ok := cb.handlers[namespace]; ok {
handler.BlockchainOpUpdate(plugin, nsOpID, txState, blockchainTXID, errorMessage, opOutput)
return
}
log.L(ctx).Errorf("No handler found for blockchain operation '%s'", nsOpID)
}
func (cb *callbacks) BatchPinComplete(ctx context.Context, batch *blockchain.BatchPin, signingKey *core.VerifierRef) error {
if handler, ok := cb.handlers[batch.Namespace]; ok {
return handler.BatchPinComplete(batch, signingKey)
}
log.L(ctx).Errorf("No handler found for blockchain batch pin on namespace '%s'", batch.Namespace)
return nil
}
func (cb *callbacks) BlockchainNetworkAction(ctx context.Context, namespace, action string, location *fftypes.JSONAny, event *blockchain.Event, signingKey *core.VerifierRef) error {
if namespace == "" {
// V1 networks don't populate namespace, so deliver the event to every handler
for _, handler := range cb.handlers {
if err := handler.BlockchainNetworkAction(action, location, event, signingKey); err != nil {
return err
}
}
} else {
if handler, ok := cb.handlers[namespace]; ok {
return handler.BlockchainNetworkAction(action, location, event, signingKey)
}
log.L(ctx).Errorf("No handler found for blockchain network action on namespace '%s'", namespace)
}
return nil
}
func (cb *callbacks) BlockchainEvent(event *blockchain.EventWithSubscription) error {
for _, cb := range cb.handlers {
// Send the event to all handlers and let them match it to a contract listener
// TODO: can we push more listener/namespace knowledge down to this layer?
if err := cb.BlockchainEvent(event); err != nil {
return err
}
}
return nil
}
type eventStreamWebsocket struct {
Topic string `json:"topic"`
}
type queryOutput struct {
Output interface{} `json:"output"`
}
type ethWSCommandPayload struct {
Type string `json:"type"`
Topic string `json:"topic,omitempty"`
}
type ethError struct {
Error string `json:"error,omitempty"`
}
type Location struct {
Address string `json:"address"`
}
type paramDetails struct {
Type string `json:"type"`
InternalType string `json:"internalType,omitempty"`
Indexed bool `json:"indexed,omitempty"`
Index *int `json:"index,omitempty"`
}
type Schema struct {
OneOf []SchemaType `json:"oneOf,omitempty"`
Type string `json:"type,omitempty"`
Details *paramDetails `json:"details,omitempty"`
Properties map[string]*Schema `json:"properties,omitempty"`
Items *Schema `json:"items,omitempty"`
Description string `json:"description,omitempty"`
}
type SchemaType struct {
Type string `json:"type"`
}
func (s *Schema) ToJSON() string {
b, _ := json.Marshal(s)
return string(b)
}
type EthconnectMessageRequest struct {
Headers EthconnectMessageHeaders `json:"headers,omitempty"`
To string `json:"to"`
From string `json:"from,omitempty"`
Method *abi.Entry `json:"method"`
Params []interface{} `json:"params"`
}
type EthconnectMessageHeaders struct {
Type string `json:"type,omitempty"`
ID string `json:"id,omitempty"`
}
type FFIGenerationInput struct {
ABI *abi.ABI `json:"abi,omitempty"`
}
var addressVerify = regexp.MustCompile("^[0-9a-f]{40}$")
func (e *Ethereum) Name() string {
return "ethereum"
}
func (e *Ethereum) VerifierType() core.VerifierType {
return core.VerifierTypeEthAddress
}
func (e *Ethereum) Init(ctx context.Context, config config.Section, metrics metrics.Manager) (err error) {
e.InitConfig(config)
ethconnectConf := e.ethconnectConf
addressResolverConf := config.SubSection(AddressResolverConfigKey)
fftmConf := config.SubSection(FFTMConfigKey)
e.ctx = log.WithLogField(ctx, "proto", "ethereum")
e.metrics = metrics
e.capabilities = &blockchain.Capabilities{}
e.callbacks.handlers = make(map[string]blockchain.Callbacks)
if addressResolverConf.GetString(AddressResolverURLTemplate) != "" {
if e.addressResolver, err = newAddressResolver(ctx, addressResolverConf); err != nil {
return err
}
}
if ethconnectConf.GetString(ffresty.HTTPConfigURL) == "" {
return i18n.NewError(ctx, coremsgs.MsgMissingPluginConfig, "url", "blockchain.ethereum.ethconnect")
}
e.client = ffresty.New(e.ctx, ethconnectConf)
if fftmConf.GetString(ffresty.HTTPConfigURL) != "" {
e.fftmClient = ffresty.New(e.ctx, fftmConf)
}
e.topic = ethconnectConf.GetString(EthconnectConfigTopic)
if e.topic == "" {
return i18n.NewError(ctx, coremsgs.MsgMissingPluginConfig, "topic", "blockchain.ethereum.ethconnect")
}
e.prefixShort = ethconnectConf.GetString(EthconnectPrefixShort)
e.prefixLong = ethconnectConf.GetString(EthconnectPrefixLong)
wsConfig := wsclient.GenerateConfig(ethconnectConf)
if wsConfig.WSKeyPath == "" {
wsConfig.WSKeyPath = "/ws"
}
e.wsconn, err = wsclient.New(ctx, wsConfig, nil, e.afterConnect)
if err != nil {
return err
}
e.streams = &streamManager{client: e.client}
batchSize := ethconnectConf.GetUint(EthconnectConfigBatchSize)
batchTimeout := uint(ethconnectConf.GetDuration(EthconnectConfigBatchTimeout).Milliseconds())
stream, err := e.streams.ensureEventStream(e.ctx, e.topic, batchSize, batchTimeout)
if err != nil {
return err
}
e.streamID = stream.ID
e.subs = make(map[string]subscriptionInfo)
log.L(e.ctx).Infof("Event stream: %s (topic=%s)", e.streamID, e.topic)
e.closed = make(chan struct{})
go e.eventLoop()
return nil
}
func (e *Ethereum) SetHandler(namespace string, handler blockchain.Callbacks) {
e.callbacks.handlers[namespace] = handler
}
func (e *Ethereum) Start() (err error) {
return e.wsconn.Connect()
}
func (e *Ethereum) Capabilities() *blockchain.Capabilities {
return e.capabilities
}
func (e *Ethereum) AddFireflySubscription(ctx context.Context, namespace string, location *fftypes.JSONAny, firstEvent string) (string, error) {
ethLocation, err := parseContractLocation(ctx, location)
if err != nil {
return "", err
}
switch firstEvent {
case string(core.SubOptsFirstEventOldest):
firstEvent = "0"
case string(core.SubOptsFirstEventNewest):
firstEvent = "latest"
}
sub, err := e.streams.ensureFireFlySubscription(ctx, namespace, ethLocation.Address, firstEvent, e.streamID, batchPinEventABI)
if err != nil {
return "", err
}
version, err := e.GetNetworkVersion(ctx, location)
if err != nil {
return "", err
}
e.subs[sub.ID] = subscriptionInfo{
namespace: namespace,
version: version,
}
return sub.ID, nil
}
func (e *Ethereum) RemoveFireflySubscription(ctx context.Context, subID string) error {
// Don't actually delete the subscription from ethconnect, as this may be called while processing
// events from the subscription (and handling that scenario cleanly could be difficult for ethconnect).
// TODO: can old subscriptions be somehow cleaned up later?
if _, ok := e.subs[subID]; ok {
delete(e.subs, subID)
return nil
}
return i18n.NewError(ctx, coremsgs.MsgSubscriptionIDInvalid, subID)
}
func (e *Ethereum) afterConnect(ctx context.Context, w wsclient.WSClient) error {
// Send a subscribe to our topic after each connect/reconnect
b, _ := json.Marshal(ðWSCommandPayload{
Type: "listen",
Topic: e.topic,
})
err := w.Send(ctx, b)
if err == nil {
b, _ = json.Marshal(ðWSCommandPayload{
Type: "listenreplies",
})
err = w.Send(ctx, b)
}
return err
}
func ethHexFormatB32(b *fftypes.Bytes32) string {
if b == nil {
return "0x0000000000000000000000000000000000000000000000000000000000000000"
}
return "0x" + hex.EncodeToString(b[0:32])
}
func (e *Ethereum) parseBlockchainEvent(ctx context.Context, msgJSON fftypes.JSONObject) *blockchain.Event {
sBlockNumber := msgJSON.GetString("blockNumber")
sTransactionHash := msgJSON.GetString("transactionHash")
blockNumber := msgJSON.GetInt64("blockNumber")
txIndex := msgJSON.GetInt64("transactionIndex")
logIndex := msgJSON.GetInt64("logIndex")
dataJSON := msgJSON.GetObject("data")
signature := msgJSON.GetString("signature")
name := strings.SplitN(signature, "(", 2)[0]
timestampStr := msgJSON.GetString("timestamp")
timestamp, err := fftypes.ParseTimeString(timestampStr)
if err != nil {
log.L(ctx).Errorf("Blockchain event is not valid - missing timestamp: %+v", msgJSON)
return nil // move on
}
if sBlockNumber == "" || sTransactionHash == "" {
log.L(ctx).Errorf("Blockchain event is not valid - missing data: %+v", msgJSON)
return nil // move on
}
delete(msgJSON, "data")
return &blockchain.Event{
BlockchainTXID: sTransactionHash,
Source: e.Name(),
Name: name,
ProtocolID: fmt.Sprintf("%.12d/%.6d/%.6d", blockNumber, txIndex, logIndex),
Output: dataJSON,
Info: msgJSON,
Timestamp: timestamp,
Location: e.buildEventLocationString(msgJSON),
Signature: signature,
}
}
func (e *Ethereum) handleBatchPinEvent(ctx context.Context, location *fftypes.JSONAny, subInfo *subscriptionInfo, msgJSON fftypes.JSONObject) (err error) {
event := e.parseBlockchainEvent(ctx, msgJSON)
if event == nil {
return nil // move on
}
authorAddress := event.Output.GetString("author")
nsOrAction := event.Output.GetString("namespace")
sUUIDs := event.Output.GetString("uuids")
sBatchHash := event.Output.GetString("batchHash")
sPayloadRef := event.Output.GetString("payloadRef")
sContexts := event.Output.GetStringArray("contexts")
if authorAddress == "" || sUUIDs == "" || sBatchHash == "" {
log.L(ctx).Errorf("BatchPin event is not valid - missing data: %+v", msgJSON)
return nil // move on
}
authorAddress, err = e.NormalizeSigningKey(ctx, authorAddress)
if err != nil {
log.L(ctx).Errorf("BatchPin event is not valid - bad from address (%s): %+v", err, msgJSON)
return nil // move on
}
verifier := &core.VerifierRef{
Type: core.VerifierTypeEthAddress,
Value: authorAddress,
}
// Check if this is actually an operator action
if strings.HasPrefix(nsOrAction, blockchain.FireFlyActionPrefix) {
action := nsOrAction[len(blockchain.FireFlyActionPrefix):]
// For V1 of the FireFly contract, action is sent to all namespaces
// For V2+, namespace is inferred from the subscription
var namespace string
if subInfo.version > 1 {
namespace = subInfo.namespace
}
return e.callbacks.BlockchainNetworkAction(ctx, namespace, action, location, event, verifier)
}
// For V1 of the FireFly contract, namespace is passed explicitly
// For V2+, namespace is inferred from the subscription
var namespace string
if subInfo.version == 1 {
namespace = nsOrAction
} else {
namespace = subInfo.namespace
}
hexUUIDs, err := hex.DecodeString(strings.TrimPrefix(sUUIDs, "0x"))
if err != nil || len(hexUUIDs) != 32 {
log.L(ctx).Errorf("BatchPin event is not valid - bad uuids (%s): %+v", err, msgJSON)
return nil // move on
}
var txnID fftypes.UUID
copy(txnID[:], hexUUIDs[0:16])
var batchID fftypes.UUID
copy(batchID[:], hexUUIDs[16:32])
var batchHash fftypes.Bytes32
err = batchHash.UnmarshalText([]byte(sBatchHash))
if err != nil {
log.L(ctx).Errorf("BatchPin event is not valid - bad batchHash (%s): %+v", err, msgJSON)
return nil // move on
}
contexts := make([]*fftypes.Bytes32, len(sContexts))
for i, sHash := range sContexts {
var hash fftypes.Bytes32
err = hash.UnmarshalText([]byte(sHash))
if err != nil {
log.L(ctx).Errorf("BatchPin event is not valid - bad pin %d (%s): %+v", i, err, msgJSON)
return nil // move on
}
contexts[i] = &hash
}
batch := &blockchain.BatchPin{
Namespace: namespace,
TransactionID: &txnID,
BatchID: &batchID,
BatchHash: &batchHash,
BatchPayloadRef: sPayloadRef,
Contexts: contexts,
Event: *event,
}
// If there's an error dispatching the event, we must return the error and shutdown
return e.callbacks.BatchPinComplete(ctx, batch, verifier)
}
func (e *Ethereum) handleContractEvent(ctx context.Context, msgJSON fftypes.JSONObject) (err error) {
event := e.parseBlockchainEvent(ctx, msgJSON)
if event != nil {
err = e.callbacks.BlockchainEvent(&blockchain.EventWithSubscription{
Event: *event,
Subscription: msgJSON.GetString("subId"),
})
}
return err
}
func (e *Ethereum) handleReceipt(ctx context.Context, reply fftypes.JSONObject) {
l := log.L(ctx)
headers := reply.GetObject("headers")
requestID := headers.GetString("requestId")
replyType := headers.GetString("type")
txHash := reply.GetString("transactionHash")
message := reply.GetString("errorMessage")
if requestID == "" || replyType == "" {
l.Errorf("Reply cannot be processed - missing fields: %+v", reply)
return
}
updateType := core.OpStatusSucceeded
if replyType != "TransactionSuccess" {
updateType = core.OpStatusFailed
}
l.Infof("Ethconnect '%s' reply: request=%s tx=%s message=%s", replyType, requestID, txHash, message)
e.callbacks.BlockchainOpUpdate(ctx, e, requestID, updateType, txHash, message, reply)
}
func (e *Ethereum) buildEventLocationString(msgJSON fftypes.JSONObject) string {
return fmt.Sprintf("address=%s", msgJSON.GetString("address"))
}
func (e *Ethereum) handleMessageBatch(ctx context.Context, messages []interface{}) error {
l := log.L(ctx)
for i, msgI := range messages {
msgMap, ok := msgI.(map[string]interface{})
if !ok {
l.Errorf("Message cannot be parsed as JSON: %+v", msgI)
return nil // Swallow this and move on
}
msgJSON := fftypes.JSONObject(msgMap)
l1 := l.WithField("ethmsgidx", i)
ctx1 := log.WithLogger(ctx, l1)
signature := msgJSON.GetString("signature")
sub := msgJSON.GetString("subId")
l1.Infof("Received '%s' message", signature)
l1.Tracef("Message: %+v", msgJSON)
// Matches one of the active FireFly BatchPin subscriptions
if subInfo, ok := e.subs[sub]; ok {
location, err := encodeContractLocation(ctx, &Location{
Address: msgJSON.GetString("address"),
})
if err != nil {
return err
}
switch signature {
case broadcastBatchEventSignature:
if err := e.handleBatchPinEvent(ctx1, location, &subInfo, msgJSON); err != nil {
return err
}
default:
l.Infof("Ignoring event with unknown signature: %s", signature)
}
} else {
// Subscription not recognized - assume it's from a custom contract listener
// (event manager will reject it if it's not)
if err := e.handleContractEvent(ctx1, msgJSON); err != nil {
return err
}
}
}
return nil
}
func (e *Ethereum) eventLoop() {
defer e.wsconn.Close()
defer close(e.closed)
l := log.L(e.ctx).WithField("role", "event-loop")
ctx := log.WithLogger(e.ctx, l)
ack, _ := json.Marshal(map[string]string{"type": "ack", "topic": e.topic})
for {
select {
case <-ctx.Done():
l.Debugf("Event loop exiting (context cancelled)")
return
case msgBytes, ok := <-e.wsconn.Receive():
if !ok {
l.Debugf("Event loop exiting (receive channel closed)")
return
}
var msgParsed interface{}
err := json.Unmarshal(msgBytes, &msgParsed)
if err != nil {
l.Errorf("Message cannot be parsed as JSON: %s\n%s", err, string(msgBytes))
continue // Swallow this and move on
}
switch msgTyped := msgParsed.(type) {
case []interface{}:
err = e.handleMessageBatch(ctx, msgTyped)
if err == nil {
err = e.wsconn.Send(ctx, ack)
}
case map[string]interface{}:
e.handleReceipt(ctx, fftypes.JSONObject(msgTyped))
default:
l.Errorf("Message unexpected: %+v", msgTyped)
continue
}
// Send the ack - only fails if shutting down
if err != nil {
l.Errorf("Event loop exiting: %s", err)
return
}
}
}
}
func validateEthAddress(ctx context.Context, key string) (string, error) {
keyLower := strings.ToLower(key)
keyNoHexPrefix := strings.TrimPrefix(keyLower, "0x")
if addressVerify.MatchString(keyNoHexPrefix) {
return "0x" + keyNoHexPrefix, nil
}
return "", i18n.NewError(ctx, coremsgs.MsgInvalidEthAddress)
}
func (e *Ethereum) NormalizeSigningKey(ctx context.Context, key string) (string, error) {
resolved, err := validateEthAddress(ctx, key)
if err != nil && e.addressResolver != nil {
resolved, err := e.addressResolver.NormalizeSigningKey(ctx, key)
if err == nil {
log.L(ctx).Infof("Key '%s' resolved to '%s'", key, resolved)
}
return resolved, err
}
return resolved, err
}
func wrapError(ctx context.Context, errRes *ethError, res *resty.Response, err error) error {
if errRes != nil && errRes.Error != "" {
return i18n.WrapError(ctx, err, coremsgs.MsgEthconnectRESTErr, errRes.Error)
}
return ffresty.WrapRestErr(ctx, res, err, coremsgs.MsgEthconnectRESTErr)
}
func (e *Ethereum) buildEthconnectRequestBody(ctx context.Context, messageType, address, signingKey string, abi *abi.Entry, requestID string, input []interface{}, options map[string]interface{}) (map[string]interface{}, error) {
headers := EthconnectMessageHeaders{
Type: messageType,
}
if requestID != "" {
headers.ID = requestID
}
body := map[string]interface{}{
"headers": headers,
"to": address,
"method": abi,
"params": input,
}
if signingKey != "" {
body["from"] = signingKey
}
for k, v := range options {
// Set the new field if it's not already set. Do not allow overriding of existing fields
if _, ok := body[k]; !ok {
body[k] = v
} else {
return nil, i18n.NewError(ctx, coremsgs.MsgOverrideExistingFieldCustomOption, k)
}
}
return body, nil
}
func (e *Ethereum) invokeContractMethod(ctx context.Context, address, signingKey string, abi *abi.Entry, requestID string, input []interface{}, options map[string]interface{}) error {
if e.metrics.IsMetricsEnabled() {
e.metrics.BlockchainTransaction(address, abi.Name)
}
messageType := "SendTransaction"
body, err := e.buildEthconnectRequestBody(ctx, messageType, address, signingKey, abi, requestID, input, options)
if err != nil {
return err
}
client := e.fftmClient
if client == nil {
client = e.client
}
var resErr ethError
res, err := client.R().
SetContext(ctx).
SetBody(body).
SetError(&resErr).
Post("/")
if err != nil || !res.IsSuccess() {
return wrapError(ctx, &resErr, res, err)
}
return nil
}
func (e *Ethereum) queryContractMethod(ctx context.Context, address string, abi *abi.Entry, input []interface{}, options map[string]interface{}) (*resty.Response, error) {
if e.metrics.IsMetricsEnabled() {
e.metrics.BlockchainQuery(address, abi.Name)
}
messageType := "Query"
body, err := e.buildEthconnectRequestBody(ctx, messageType, address, "", abi, "", input, options)
if err != nil {
return nil, err
}
var resErr ethError
res, err := e.client.R().
SetContext(ctx).
SetBody(body).
SetError(&resErr).
Post("/")
if err != nil || !res.IsSuccess() {
return res, wrapError(ctx, &resErr, res, err)
}
return res, nil
}
func (e *Ethereum) SubmitBatchPin(ctx context.Context, nsOpID string, signingKey string, batch *blockchain.BatchPin, location *fftypes.JSONAny) error {
ethHashes := make([]string, len(batch.Contexts))
for i, v := range batch.Contexts {
ethHashes[i] = ethHexFormatB32(v)
}
var uuids fftypes.Bytes32
copy(uuids[0:16], (*batch.TransactionID)[:])
copy(uuids[16:32], (*batch.BatchID)[:])
input := []interface{}{
batch.Namespace,
ethHexFormatB32(&uuids),
ethHexFormatB32(batch.BatchHash),
batch.BatchPayloadRef,
ethHashes,
}
ethLocation, err := parseContractLocation(ctx, location)
if err != nil {
return err
}
return e.invokeContractMethod(ctx, ethLocation.Address, signingKey, batchPinMethodABI, nsOpID, input, nil)
}
func (e *Ethereum) SubmitNetworkAction(ctx context.Context, nsOpID string, signingKey string, action core.NetworkActionType, location *fftypes.JSONAny) error {
input := []interface{}{
blockchain.FireFlyActionPrefix + action,
ethHexFormatB32(nil),
ethHexFormatB32(nil),
"",
[]string{},
}
ethLocation, err := parseContractLocation(ctx, location)
if err != nil {
return err
}
return e.invokeContractMethod(ctx, ethLocation.Address, signingKey, batchPinMethodABI, nsOpID, input, nil)
}
func (e *Ethereum) InvokeContract(ctx context.Context, nsOpID string, signingKey string, location *fftypes.JSONAny, method *core.FFIMethod, input map[string]interface{}, options map[string]interface{}) error {
ethereumLocation, err := parseContractLocation(ctx, location)
if err != nil {
return err
}
abi, orderedInput, err := e.prepareRequest(ctx, method, input)
if err != nil {
return err
}
return e.invokeContractMethod(ctx, ethereumLocation.Address, signingKey, abi, nsOpID, orderedInput, options)
}
func (e *Ethereum) QueryContract(ctx context.Context, location *fftypes.JSONAny, method *core.FFIMethod, input map[string]interface{}, options map[string]interface{}) (interface{}, error) {
ethereumLocation, err := parseContractLocation(ctx, location)
if err != nil {
return nil, err
}
abi, orderedInput, err := e.prepareRequest(ctx, method, input)
if err != nil {
return nil, err
}
res, err := e.queryContractMethod(ctx, ethereumLocation.Address, abi, orderedInput, options)
if err != nil || !res.IsSuccess() {
return nil, err
}
output := &queryOutput{}
if err = json.Unmarshal(res.Body(), output); err != nil {
return nil, err
}
return output, nil
}
func (e *Ethereum) NormalizeContractLocation(ctx context.Context, location *fftypes.JSONAny) (result *fftypes.JSONAny, err error) {
parsed, err := parseContractLocation(ctx, location)
if err != nil {
return nil, err
}
return encodeContractLocation(ctx, parsed)
}
func parseContractLocation(ctx context.Context, location *fftypes.JSONAny) (*Location, error) {
ethLocation := Location{}
if err := json.Unmarshal(location.Bytes(), ðLocation); err != nil {
return nil, i18n.NewError(ctx, coremsgs.MsgContractLocationInvalid, err)
}
if ethLocation.Address == "" {
return nil, i18n.NewError(ctx, coremsgs.MsgContractLocationInvalid, "'address' not set")
}
return ðLocation, nil
}
func encodeContractLocation(ctx context.Context, location *Location) (result *fftypes.JSONAny, err error) {
location.Address, err = validateEthAddress(ctx, location.Address)
if err != nil {
return nil, err
}
normalized, err := json.Marshal(location)
if err == nil {
result = fftypes.JSONAnyPtrBytes(normalized)
}
return result, err
}
func (e *Ethereum) AddContractListener(ctx context.Context, listener *core.ContractListenerInput) error {
location, err := parseContractLocation(ctx, listener.Location)
if err != nil {
return err
}
abi, err := e.FFIEventDefinitionToABI(ctx, &listener.Event.FFIEventDefinition)
if err != nil {
return i18n.WrapError(ctx, err, coremsgs.MsgContractParamInvalid)
}
subName := fmt.Sprintf("ff-sub-%s", listener.ID)
result, err := e.streams.createSubscription(ctx, location, e.streamID, subName, listener.Options.FirstEvent, abi)
if err != nil {
return err
}
listener.BackendID = result.ID
return nil
}
func (e *Ethereum) DeleteContractListener(ctx context.Context, subscription *core.ContractListener) error {
return e.streams.deleteSubscription(ctx, subscription.BackendID)
}
func (e *Ethereum) GetFFIParamValidator(ctx context.Context) (core.FFIParamValidator, error) {
return &FFIParamValidator{}, nil
}
func (e *Ethereum) FFIEventDefinitionToABI(ctx context.Context, event *core.FFIEventDefinition) (*abi.Entry, error) {
abiInputs, err := e.convertFFIParamsToABIParameters(ctx, event.Params)
if err != nil {
return nil, err
}
abiEntry := &abi.Entry{
Name: event.Name,
Type: "event",
Inputs: abiInputs,
}
if event.Details != nil {
abiEntry.Anonymous = event.Details.GetBool("anonymous")
}
return abiEntry, nil
}
func (e *Ethereum) FFIMethodToABI(ctx context.Context, method *core.FFIMethod, input map[string]interface{}) (*abi.Entry, error) {
abiInputs, err := e.convertFFIParamsToABIParameters(ctx, method.Params)
if err != nil {
return nil, err
}
abiOutputs, err := e.convertFFIParamsToABIParameters(ctx, method.Returns)
if err != nil {
return nil, err
}
abiEntry := &abi.Entry{
Name: method.Name,
Type: "function",
Inputs: abiInputs,
Outputs: abiOutputs,
}
if method.Details != nil {
if stateMutability, ok := method.Details.GetStringOk("stateMutability"); ok {
abiEntry.StateMutability = abi.StateMutability(stateMutability)
}
abiEntry.Payable = method.Details.GetBool("payable")
abiEntry.Constant = method.Details.GetBool("constant")
}
return abiEntry, nil
}
func ABIArgumentToTypeString(typeName string, components abi.ParameterArray) string {
if strings.HasPrefix(typeName, "tuple") {
suffix := typeName[5:]
children := make([]string, len(components))
for i, component := range components {
children[i] = ABIArgumentToTypeString(component.Type, nil)
}
return "(" + strings.Join(children, ",") + ")" + suffix
}
return typeName
}
func ABIMethodToSignature(abi *abi.Entry) string {
result := abi.Name + "("
if len(abi.Inputs) > 0 {
types := make([]string, len(abi.Inputs))
for i, param := range abi.Inputs {
types[i] = ABIArgumentToTypeString(param.Type, param.Components)
}
result += strings.Join(types, ",")
}
result += ")"
return result
}
func (e *Ethereum) GenerateEventSignature(ctx context.Context, event *core.FFIEventDefinition) string {
abi, err := e.FFIEventDefinitionToABI(ctx, event)
if err != nil {
return ""
}
return ABIMethodToSignature(abi)
}
func (e *Ethereum) convertFFIParamsToABIParameters(ctx context.Context, params core.FFIParams) (abi.ParameterArray, error) {
abiParamList := make(abi.ParameterArray, len(params))
for i, param := range params {
c := core.NewFFISchemaCompiler()
v, _ := e.GetFFIParamValidator(ctx)
c.RegisterExtension(v.GetExtensionName(), v.GetMetaSchema(), v)
err := c.AddResource(param.Name, strings.NewReader(param.Schema.String()))
if err != nil {
return nil, err
}
s, err := c.Compile(param.Name)
if err != nil {
return nil, err
}
abiParamList[i] = processField(param.Name, s)
}
return abiParamList, nil
}
func processField(name string, schema *jsonschema.Schema) *abi.Parameter {
details := getParamDetails(schema)
parameter := &abi.Parameter{
Name: name,
Type: details.Type,
InternalType: details.InternalType,
Indexed: details.Indexed,
}
if len(schema.Types) > 0 {
switch schema.Types[0] {
case objectType:
parameter.Components = buildABIParameterArrayForObject(schema.Properties)
case arrayType:
parameter.Components = buildABIParameterArrayForObject(schema.Items2020.Properties)
}
}
return parameter
}
func buildABIParameterArrayForObject(properties map[string]*jsonschema.Schema) abi.ParameterArray {
parameters := make(abi.ParameterArray, len(properties))
for propertyName, propertySchema := range properties {
details := getParamDetails(propertySchema)
parameter := processField(propertyName, propertySchema)
parameters[*details.Index] = parameter
}
return parameters
}
func getParamDetails(schema *jsonschema.Schema) *paramDetails {
ext := schema.Extensions["details"]
details := ext.(detailsSchema)
blockchainType := details["type"].(string)
paramDetails := ¶mDetails{
Type: blockchainType,
}
if i, ok := details["index"]; ok {
index, _ := i.(json.Number).Int64()
paramDetails.Index = new(int)
*paramDetails.Index = int(index)
}
if i, ok := details["indexed"]; ok {
paramDetails.Indexed = i.(bool)
}
if i, ok := details["internalType"]; ok {
paramDetails.InternalType = i.(string)
}
return paramDetails
}
func (e *Ethereum) prepareRequest(ctx context.Context, method *core.FFIMethod, input map[string]interface{}) (*abi.Entry, []interface{}, error) {
orderedInput := make([]interface{}, len(method.Params))
abi, err := e.FFIMethodToABI(ctx, method, input)
if err != nil {
return abi, orderedInput, err
}
for i, ffiParam := range method.Params {
orderedInput[i] = input[ffiParam.Name]
}
return abi, orderedInput, nil
}
func (e *Ethereum) getContractAddress(ctx context.Context, instancePath string) (string, error) {
res, err := e.client.R().
SetContext(ctx).
Get(instancePath)
if err != nil || !res.IsSuccess() {
return "", ffresty.WrapRestErr(ctx, res, err, coremsgs.MsgEthconnectRESTErr)
}
var output map[string]string
if err = json.Unmarshal(res.Body(), &output); err != nil {
return "", err
}
return output["address"], nil
}
func (e *Ethereum) GenerateFFI(ctx context.Context, generationRequest *core.FFIGenerationRequest) (*core.FFI, error) {
var input FFIGenerationInput
err := json.Unmarshal(generationRequest.Input.Bytes(), &input)
if err != nil {
return nil, i18n.NewError(ctx, coremsgs.MsgFFIGenerationFailed, "unable to deserialize JSON as ABI")
}
if len(*input.ABI) == 0 {
return nil, i18n.NewError(ctx, coremsgs.MsgFFIGenerationFailed, "ABI is empty")