forked from smartcontractkit/chainlink-testing-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
1417 lines (1315 loc) · 44 KB
/
client.go
File metadata and controls
1417 lines (1315 loc) · 44 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 clclient
import (
"crypto/ecdsa"
"crypto/rand"
"crypto/tls"
"fmt"
"math/big"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
"github.com/avast/retry-go/v4"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/crypto"
"github.com/pkg/errors"
"github.com/smartcontractkit/chainlink-testing-framework/framework"
"github.com/smartcontractkit/chainlink-testing-framework/framework/components/clnode"
"github.com/ethereum/go-ethereum/common"
"github.com/go-resty/resty/v2"
"github.com/rs/zerolog/log"
"golang.org/x/sync/errgroup"
)
const (
// ChainlinkKeyPassword used to encrypt exported keys
ChainlinkKeyPassword string = "twochains"
// NodeURL string for logging
NodeURL string = "Node URL"
)
var (
// OneLINK representation of a single LINK token
OneLINK = big.NewFloat(1e18)
mapKeyTypeToChain = map[string]string{
"evm": "eTHKeys",
"solana": "encryptedSolanaKeys",
"starknet": "encryptedStarkNetKeys",
}
)
type ChainlinkClient struct {
APIClient *resty.Client
Config *Config
pageSize int
primaryEthAddress string
ethAddresses []string
}
// NewChainlinkClient creates a new Chainlink model using a provided config
func NewChainlinkClient(c *Config) (*ChainlinkClient, error) {
rc, err := initRestyClient(c.URL, c.Email, c.Password, c.Headers, c.HTTPTimeout)
if err != nil {
return nil, err
}
return &ChainlinkClient{
Config: c,
APIClient: rc,
pageSize: 25,
}, nil
}
func New(outs []*clnode.Output) ([]*ChainlinkClient, error) {
clients := make([]*ChainlinkClient, 0)
for _, out := range outs {
c, err := NewChainlinkClient(&Config{
URL: out.Node.ExternalURL,
Email: out.Node.APIAuthUser,
Password: out.Node.APIAuthPassword,
})
if err != nil {
return nil, err
}
clients = append(clients, c)
}
return clients, nil
}
func initRestyClient(url string, email string, password string, headers map[string]string, timeout *time.Duration) (*resty.Client, error) {
isDebug := os.Getenv("RESTY_DEBUG") == "true"
// G402 - TODO: certificates
//nolint
rc := resty.New().SetBaseURL(url).SetHeaders(headers).SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}).SetDebug(isDebug)
if timeout != nil {
rc.SetTimeout(*timeout)
}
session := &Session{Email: email, Password: password}
// Retry the connection on boot up, sometimes pods can still be starting up and not ready to accept connections
var resp *resty.Response
var err error
retryCount := 20
for i := 0; i < retryCount; i++ {
resp, err = rc.R().SetBody(session).Post("/sessions")
if err != nil {
log.Warn().Err(err).Str("URL", url).Interface("Session Details", session).Msg("Error connecting to Chainlink node, retrying")
time.Sleep(5 * time.Second)
} else {
break
}
}
if err != nil {
return nil, fmt.Errorf("error connecting to chainlink node after %d attempts: %w", retryCount, err)
}
rc.SetCookies(resp.Cookies())
framework.L.Debug().Str("URL", url).Msg("Connected to Chainlink node")
return rc, nil
}
// URL Chainlink instance http url
func (c *ChainlinkClient) URL() string {
return c.Config.URL
}
// Health returns all statuses health info
func (c *ChainlinkClient) Health() (*HealthResponse, *http.Response, error) {
respBody := &HealthResponse{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Requesting health data")
resp, err := c.APIClient.R().
SetResult(&respBody).
Get("/health")
if err != nil {
return nil, nil, err
}
return respBody, resp.RawResponse, err
}
// WaitHealthy waits until all the components (regex) return specified status
func (c *ChainlinkClient) WaitHealthy(pattern, status string, attempts uint) error {
respBody := &HealthResponse{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Check CL node health")
re, err := regexp.Compile(pattern)
if err != nil {
return fmt.Errorf("invalid regex pattern: %w", err)
}
err = retry.Do(
func() error {
framework.L.Debug().Str(NodeURL, c.Config.URL).Uint("Attempts", attempts).Msg("Awaiting Chainlink node health status")
resp, err := c.APIClient.R().
SetResult(&respBody).
Get("/health")
if err != nil {
return fmt.Errorf("error connecting to chainlink node after %d attempts: %w", attempts, err)
}
if resp.StatusCode() >= 400 {
return fmt.Errorf("error connecting to chainlink node after %d attempts: %s", attempts, resp.Status())
}
var foundComponents bool
var notReadyComponents []string
for _, d := range respBody.Data {
framework.L.Debug().Str("Component", d.Attributes.Name).Msg("Checking component")
if re.MatchString(d.Attributes.Name) {
foundComponents = true
if d.Attributes.Status != status {
notReadyComponents = append(notReadyComponents,
fmt.Sprintf("%s Current: %s, Expected: %s",
d.Attributes.Name,
d.Attributes.Status,
status))
}
}
}
if !foundComponents {
return fmt.Errorf("no component found in health response")
}
if len(notReadyComponents) > 0 {
framework.L.Debug().
Strs("Components", notReadyComponents).
Msg("Components not yet ready")
return fmt.Errorf("%d components not ready", len(notReadyComponents))
}
return nil
},
retry.Attempts(attempts),
retry.Delay(1*time.Second),
retry.DelayType(retry.FixedDelay),
retry.OnRetry(func(n uint, err error) {
framework.L.Debug().
Uint("Attempt", n+1).
Uint("MaxAttempts", attempts).
Str("Pattern", pattern).
Msg("Retrying health check")
}),
)
if err != nil {
return fmt.Errorf("health check failed after %d attempts: %w", attempts, err)
}
framework.L.Info().
Str("pattern", pattern).
Str("status", status).
Msg("All matching components ready")
return nil
}
// CreateJobRaw creates a Chainlink job based on the provided spec string
func (c *ChainlinkClient) CreateJobRaw(spec string) (*Job, *http.Response, error) {
job := &Job{}
framework.L.Info().Str("Node URL", c.Config.URL).Msg("Creating Job")
framework.L.Trace().Str("Node URL", c.Config.URL).Str("Job Body", spec).Msg("Creating Job")
resp, err := c.APIClient.R().
SetBody(&JobForm{
TOML: spec,
}).
SetResult(&job).
Post("/v2/jobs")
if err != nil {
return nil, nil, err
}
return job, resp.RawResponse, err
}
// MustCreateJob creates a Chainlink job based on the provided spec struct and returns error if
// the request is unsuccessful
func (c *ChainlinkClient) MustCreateJob(spec JobSpec) (*Job, error) {
job, resp, err := c.CreateJob(spec)
if err != nil {
return nil, err
}
return job, VerifyStatusCodeWithResponse(resp, http.StatusOK)
}
func (c *ChainlinkClient) GetConfig() Config {
return *c.Config
}
// CreateJob creates a Chainlink job based on the provided spec struct
func (c *ChainlinkClient) CreateJob(spec JobSpec) (*Job, *resty.Response, error) {
job := &Job{}
specString, err := spec.String()
if err != nil {
return nil, nil, err
}
framework.L.Info().Str("Node URL", c.Config.URL).Str("Type", spec.Type()).Msg("Creating Job")
framework.L.Trace().Str("Node URL", c.Config.URL).Str("Type", spec.Type()).Str("Spec", specString).Msg("Creating Job")
resp, err := c.APIClient.R().
SetBody(&JobForm{
TOML: specString,
}).
SetResult(&job).
Post("/v2/jobs")
if err != nil {
return nil, nil, err
}
return job, resp, err
}
// ReadJobs reads all jobs from the Chainlink node
func (c *ChainlinkClient) ReadJobs() (*ResponseSlice, *http.Response, error) {
specObj := &ResponseSlice{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Getting Jobs")
resp, err := c.APIClient.R().
SetResult(&specObj).
Get("/v2/jobs")
if err != nil {
return nil, nil, err
}
return specObj, resp.RawResponse, err
}
// ReadJob reads a job with the provided ID from the Chainlink node
func (c *ChainlinkClient) ReadJob(id string) (*Response, *http.Response, error) {
specObj := &Response{}
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", id).Msg("Reading Job")
resp, err := c.APIClient.R().
SetResult(&specObj).
SetPathParams(map[string]string{
"id": id,
}).
Get("/v2/jobs/{id}")
if err != nil {
return nil, nil, err
}
return specObj, resp.RawResponse, err
}
// MustDeleteJob deletes a job with a provided ID from the Chainlink node and returns error if
// the request is unsuccessful
func (c *ChainlinkClient) MustDeleteJob(id string) error {
resp, err := c.DeleteJob(id)
if err != nil {
return err
}
return VerifyStatusCode(resp.StatusCode, http.StatusNoContent)
}
// DeleteJob deletes a job with a provided ID from the Chainlink node
func (c *ChainlinkClient) DeleteJob(id string) (*http.Response, error) {
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", id).Msg("Deleting Job")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"id": id,
}).
Delete("/v2/jobs/{id}")
if err != nil {
return nil, err
}
return resp.RawResponse, err
}
// CreateSpec creates a job spec on the Chainlink node
func (c *ChainlinkClient) CreateSpec(spec string) (*Spec, *http.Response, error) {
s := &Spec{}
r := strings.NewReplacer("\n", "", " ", "", "\\", "") // Makes it more compact and readable for logging
framework.L.Info().Str(NodeURL, c.Config.URL).Str("Spec", r.Replace(spec)).Msg("Creating Spec")
resp, err := c.APIClient.R().
SetBody([]byte(spec)).
SetResult(&s).
Post("/v2/specs")
if err != nil {
return nil, nil, err
}
return s, resp.RawResponse, err
}
// ReadSpec reads a job spec with the provided ID on the Chainlink node
func (c *ChainlinkClient) ReadSpec(id string) (*Response, *http.Response, error) {
specObj := &Response{}
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", id).Msg("Reading Spec")
resp, err := c.APIClient.R().
SetResult(&specObj).
SetPathParams(map[string]string{
"id": id,
}).
Get("/v2/specs/{id}")
if err != nil {
return nil, nil, err
}
return specObj, resp.RawResponse, err
}
// MustReadRunsByJob attempts to read all runs for a job and returns error if
// the request is unsuccessful
func (c *ChainlinkClient) MustReadRunsByJob(jobID string) (*JobRunsResponse, error) {
runsObj, resp, err := c.ReadRunsByJob(jobID)
if err != nil {
return nil, err
}
return runsObj, VerifyStatusCode(resp.StatusCode, http.StatusOK)
}
// ReadRunsByJob reads all runs for a job
func (c *ChainlinkClient) ReadRunsByJob(jobID string) (*JobRunsResponse, *http.Response, error) {
runsObj := &JobRunsResponse{}
framework.L.Debug().Str(NodeURL, c.Config.URL).Str("JobID", jobID).Msg("Reading runs for a job")
resp, err := c.APIClient.R().
SetResult(&runsObj).
SetPathParams(map[string]string{
"jobID": jobID,
}).
Get("/v2/jobs/{jobID}/runs")
if err != nil {
return nil, nil, err
}
return runsObj, resp.RawResponse, err
}
// DeleteSpec deletes a job spec with the provided ID from the Chainlink node
func (c *ChainlinkClient) DeleteSpec(id string) (*http.Response, error) {
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", id).Msg("Deleting Spec")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"id": id,
}).
Delete("/v2/specs/{id}")
if err != nil {
return nil, err
}
return resp.RawResponse, err
}
// MustCreateBridge creates a bridge on the Chainlink node based on the provided attributes and returns error if
// the request is unsuccessful
func (c *ChainlinkClient) MustCreateBridge(bta *BridgeTypeAttributes) error {
framework.L.Debug().Str(NodeURL, c.Config.URL).Str("Name", bta.Name).Msg("Creating Bridge")
resp, err := c.CreateBridge(bta)
if err != nil {
return err
}
return VerifyStatusCode(resp.StatusCode, http.StatusOK)
}
func (c *ChainlinkClient) CreateBridge(bta *BridgeTypeAttributes) (*http.Response, error) {
framework.L.Debug().Str(NodeURL, c.Config.URL).Str("Name", bta.Name).Msg("Creating Bridge")
resp, err := c.APIClient.R().
SetBody(bta).
Post("/v2/bridge_types")
if err != nil {
return nil, err
}
return resp.RawResponse, err
}
// ReadBridge reads a bridge from the Chainlink node based on the provided name
func (c *ChainlinkClient) ReadBridge(name string) (*BridgeType, *http.Response, error) {
bt := BridgeType{}
framework.L.Debug().Str(NodeURL, c.Config.URL).Str("Name", name).Msg("Reading Bridge")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"name": name,
}).
SetResult(&bt).
Get("/v2/bridge_types/{name}")
if err != nil {
return nil, nil, err
}
return &bt, resp.RawResponse, err
}
// ReadBridges reads bridges from the Chainlink node
func (c *ChainlinkClient) ReadBridges() (*Bridges, *resty.Response, error) {
result := &Bridges{}
framework.L.Debug().Str(NodeURL, c.Config.URL).Msg("Getting all bridges")
resp, err := c.APIClient.R().
SetResult(&result).
Get("/v2/bridge_types")
if err != nil {
return nil, nil, err
}
return result, resp, err
}
// DeleteBridge deletes a bridge on the Chainlink node based on the provided name
func (c *ChainlinkClient) DeleteBridge(name string) (*http.Response, error) {
framework.L.Debug().Str(NodeURL, c.Config.URL).Str("Name", name).Msg("Deleting Bridge")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"name": name,
}).
Delete("/v2/bridge_types/{name}")
if err != nil {
return nil, err
}
return resp.RawResponse, err
}
// CreateOCRKey creates an OCRKey on the Chainlink node
func (c *ChainlinkClient) CreateOCRKey() (*OCRKey, *http.Response, error) {
ocrKey := &OCRKey{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Creating OCR Key")
resp, err := c.APIClient.R().
SetResult(ocrKey).
Post("/v2/keys/ocr")
if err != nil {
return nil, nil, err
}
return ocrKey, resp.RawResponse, err
}
// MustReadOCRKeys reads all OCRKeys from the Chainlink node and returns error if
// the request is unsuccessful
func (c *ChainlinkClient) MustReadOCRKeys() (*OCRKeys, error) {
ocrKeys := &OCRKeys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading OCR Keys")
resp, err := c.APIClient.R().
SetResult(ocrKeys).
Get("/v2/keys/ocr")
if err != nil {
return nil, err
}
err = VerifyStatusCode(resp.StatusCode(), http.StatusOK)
for index := range ocrKeys.Data {
ocrKeys.Data[index].Attributes.ConfigPublicKey = strings.TrimPrefix(
ocrKeys.Data[index].Attributes.ConfigPublicKey, "ocrcfg_")
ocrKeys.Data[index].Attributes.OffChainPublicKey = strings.TrimPrefix(
ocrKeys.Data[index].Attributes.OffChainPublicKey, "ocroff_")
ocrKeys.Data[index].Attributes.OnChainSigningAddress = strings.TrimPrefix(
ocrKeys.Data[index].Attributes.OnChainSigningAddress, "ocrsad_")
}
return ocrKeys, err
}
// DeleteOCRKey deletes an OCRKey based on the provided ID
func (c *ChainlinkClient) DeleteOCRKey(id string) (*http.Response, error) {
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", id).Msg("Deleting OCR Key")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"id": id,
}).
Delete("/v2/keys/ocr/{id}")
if err != nil {
return nil, err
}
return resp.RawResponse, err
}
// CreateOCR2Key creates an OCR2Key on the Chainlink node
func (c *ChainlinkClient) CreateOCR2Key(chain string) (*OCR2Key, *http.Response, error) {
ocr2Key := &OCR2Key{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Creating OCR2 Key")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"chain": chain,
}).
SetResult(ocr2Key).
Post("/v2/keys/ocr2/{chain}")
if err != nil {
return nil, nil, err
}
return ocr2Key, resp.RawResponse, err
}
// ReadOCR2Keys reads all OCR2Keys from the Chainlink node
func (c *ChainlinkClient) ReadOCR2Keys() (*OCR2Keys, *http.Response, error) {
ocr2Keys := &OCR2Keys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading OCR2 Keys")
resp, err := c.APIClient.R().
SetResult(ocr2Keys).
Get("/v2/keys/ocr2")
return ocr2Keys, resp.RawResponse, err
}
// MustReadOCR2Keys reads all OCR2Keys from the Chainlink node returns err if response not 200
func (c *ChainlinkClient) MustReadOCR2Keys() (*OCR2Keys, error) {
ocr2Keys := &OCR2Keys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading OCR2 Keys")
resp, err := c.APIClient.R().
SetResult(ocr2Keys).
Get("/v2/keys/ocr2")
if err != nil {
return nil, err
}
err = VerifyStatusCode(resp.StatusCode(), http.StatusOK)
return ocr2Keys, err
}
// DeleteOCR2Key deletes an OCR2Key based on the provided ID
func (c *ChainlinkClient) DeleteOCR2Key(id string) (*http.Response, error) {
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", id).Msg("Deleting OCR2 Key")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"id": id,
}).
Delete("/v2/keys/ocr2/{id}")
if err != nil {
return nil, err
}
return resp.RawResponse, err
}
// CreateP2PKey creates an P2PKey on the Chainlink node
func (c *ChainlinkClient) CreateP2PKey() (*P2PKey, *http.Response, error) {
p2pKey := &P2PKey{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Creating P2P Key")
resp, err := c.APIClient.R().
SetResult(p2pKey).
Post("/v2/keys/p2p")
if err != nil {
return nil, nil, err
}
return p2pKey, resp.RawResponse, err
}
// MustReadP2PKeys reads all P2PKeys from the Chainlink node and returns error if
// the request is unsuccessful
func (c *ChainlinkClient) MustReadP2PKeys() (*P2PKeys, error) {
p2pKeys := &P2PKeys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading P2P Keys")
resp, err := c.APIClient.R().
SetResult(p2pKeys).
Get("/v2/keys/p2p")
if err != nil {
return nil, err
}
err = VerifyStatusCode(resp.StatusCode(), http.StatusOK)
if len(p2pKeys.Data) == 0 {
err = fmt.Errorf("Found no P2P Keys on the Chainlink node. Node URL: %s", c.Config.URL)
framework.L.Err(err).Msg("Error getting P2P keys")
return nil, err
}
for index := range p2pKeys.Data {
p2pKeys.Data[index].Attributes.PeerID = strings.TrimPrefix(p2pKeys.Data[index].Attributes.PeerID, "p2p_")
}
return p2pKeys, err
}
// DeleteP2PKey deletes a P2PKey on the Chainlink node based on the provided ID
func (c *ChainlinkClient) DeleteP2PKey(id int) (*http.Response, error) {
framework.L.Info().Str(NodeURL, c.Config.URL).Int("ID", id).Msg("Deleting P2P Key")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"id": fmt.Sprint(id),
}).
Delete("/v2/keys/p2p/{id}")
if err != nil {
return nil, err
}
return resp.RawResponse, err
}
// MustReadETHKeys reads all ETH keys from the Chainlink node and returns error if
// the request is unsuccessful
func (c *ChainlinkClient) MustReadETHKeys() (*ETHKeys, error) {
ethKeys := ÐKeys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading ETH Keys")
resp, err := c.APIClient.R().
SetResult(ethKeys).
Get("/v2/keys/eth")
if err != nil {
return nil, err
}
err = VerifyStatusCode(resp.StatusCode(), http.StatusOK)
if len(ethKeys.Data) == 0 {
framework.L.Warn().Str(NodeURL, c.Config.URL).Msg("Found no ETH Keys on the node")
}
return ethKeys, err
}
// UpdateEthKeyMaxGasPriceGWei updates the maxGasPriceGWei for an eth key
func (c *ChainlinkClient) UpdateEthKeyMaxGasPriceGWei(keyId string, gWei int) (*ETHKey, *http.Response, error) {
ethKey := ÐKey{}
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", keyId).Int("maxGasPriceGWei", gWei).Msg("Update maxGasPriceGWei for eth key")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"keyId": keyId,
}).
SetQueryParams(map[string]string{
"maxGasPriceGWei": fmt.Sprint(gWei),
}).
SetResult(ethKey).
Put("/v2/keys/eth/{keyId}")
if err != nil {
return nil, nil, err
}
err = VerifyStatusCode(resp.StatusCode(), http.StatusOK)
if err != nil {
return nil, nil, err
}
return ethKey, resp.RawResponse, err
}
// ReadPrimaryETHKey reads updated information about the Chainlink's primary ETH key
func (c *ChainlinkClient) ReadPrimaryETHKey(chainId string) (*ETHKeyData, error) {
ethKeys, err := c.MustReadETHKeys()
if err != nil {
return nil, err
}
if len(ethKeys.Data) == 0 {
return nil, fmt.Errorf("Error retrieving primary eth key on node %s: No ETH keys present", c.URL())
}
for _, data := range ethKeys.Data {
if data.Attributes.ChainID == chainId {
return &data, nil
}
}
return nil, fmt.Errorf("error retrieving primary eth key on node %s: No ETH keys present for chain %s", c.URL(), chainId)
}
// ReadETHKeyAtIndex reads updated information about the Chainlink's ETH key at given index
func (c *ChainlinkClient) ReadETHKeyAtIndex(keyIndex int) (*ETHKeyData, error) {
ethKeys, err := c.MustReadETHKeys()
if err != nil {
return nil, err
}
if len(ethKeys.Data) == 0 {
return nil, fmt.Errorf("Error retrieving primary eth key on node %s: No ETH keys present", c.URL())
}
return ðKeys.Data[keyIndex], nil
}
// PrimaryEthAddress returns the primary ETH address for the Chainlink node
func (c *ChainlinkClient) PrimaryEthAddress() (string, error) {
if c.primaryEthAddress == "" {
ethKeys, err := c.MustReadETHKeys()
if err != nil {
return "", err
}
c.primaryEthAddress = ethKeys.Data[0].Attributes.Address
}
return c.primaryEthAddress, nil
}
// EthAddresses returns the ETH addresses for the Chainlink node
func (c *ChainlinkClient) EthAddresses() ([]string, error) {
if len(c.ethAddresses) == 0 {
ethKeys, err := c.MustReadETHKeys()
c.ethAddresses = make([]string, len(ethKeys.Data))
if err != nil {
return make([]string, 0), err
}
for index, data := range ethKeys.Data {
c.ethAddresses[index] = data.Attributes.Address
}
}
return c.ethAddresses, nil
}
// EthAddresses returns the ETH addresses of the Chainlink node for a specific chain id
func (c *ChainlinkClient) EthAddressesForChain(chainId string) ([]string, error) {
var ethAddresses []string
ethKeys, err := c.MustReadETHKeys()
if err != nil {
return nil, err
}
for _, ethKey := range ethKeys.Data {
if ethKey.Attributes.ChainID == chainId {
ethAddresses = append(ethAddresses, ethKey.Attributes.Address)
}
}
return ethAddresses, nil
}
// PrimaryEthAddressForChain returns the primary ETH address for the Chainlink node for mentioned chain
func (c *ChainlinkClient) PrimaryEthAddressForChain(chainId string) (string, error) {
ethKeys, err := c.MustReadETHKeys()
if err != nil {
return "", err
}
for _, ethKey := range ethKeys.Data {
if ethKey.Attributes.ChainID == chainId {
return ethKey.Attributes.Address, nil
}
}
return "", nil
}
// ExportEVMKeys exports Chainlink private EVM keys
func (c *ChainlinkClient) ExportEVMKeys() ([]*ExportedEVMKey, error) {
exportedKeys := make([]*ExportedEVMKey, 0)
keys, err := c.MustReadETHKeys()
if err != nil {
return nil, err
}
for _, key := range keys.Data {
if key.Attributes.ETHBalance != "0" {
exportedKey := &ExportedEVMKey{}
_, err := c.APIClient.R().
SetResult(exportedKey).
SetPathParam("keyAddress", key.Attributes.Address).
SetQueryParam("newpassword", ChainlinkKeyPassword).
Post("/v2/keys/eth/export/{keyAddress}")
if err != nil {
return nil, err
}
exportedKeys = append(exportedKeys, exportedKey)
}
}
framework.L.Info().
Str(NodeURL, c.Config.URL).
Str("Password", ChainlinkKeyPassword).
Msg("Exported EVM Keys")
return exportedKeys, nil
}
// ExportEVMKeysForChain exports Chainlink private EVM keys for a particular chain
func (c *ChainlinkClient) ExportEVMKeysForChain(chainid string) ([]*ExportedEVMKey, error) {
exportedKeys := make([]*ExportedEVMKey, 0)
keys, err := c.MustReadETHKeys()
if err != nil {
return nil, err
}
for _, key := range keys.Data {
if key.Attributes.ETHBalance != "0" && key.Attributes.ChainID == chainid {
exportedKey := &ExportedEVMKey{}
_, err := c.APIClient.R().
SetResult(exportedKey).
SetPathParam("keyAddress", key.Attributes.Address).
SetQueryParam("newpassword", ChainlinkKeyPassword).
Post("/v2/keys/eth/export/{keyAddress}")
if err != nil {
return nil, err
}
exportedKeys = append(exportedKeys, exportedKey)
}
}
framework.L.Info().
Str(NodeURL, c.Config.URL).
Str("Password", ChainlinkKeyPassword).
Msg("Exported EVM Keys")
return exportedKeys, nil
}
// CreateTxKey creates a tx key on the Chainlink node
func (c *ChainlinkClient) CreateTxKey(chain string, chainId string) (*TxKey, *http.Response, error) {
txKey := &TxKey{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Creating Tx Key")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"chain": chain,
}).
SetQueryParam("evmChainID", chainId).
SetResult(txKey).
Post("/v2/keys/{chain}")
if err != nil {
return nil, nil, err
}
return txKey, resp.RawResponse, err
}
// ReadTxKeys reads all tx keys from the Chainlink node
func (c *ChainlinkClient) ReadTxKeys(chain string) (*TxKeys, *http.Response, error) {
txKeys := &TxKeys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading Tx Keys")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"chain": chain,
}).
SetResult(txKeys).
Get("/v2/keys/{chain}")
if err != nil {
return nil, nil, err
}
return txKeys, resp.RawResponse, err
}
// DeleteTxKey deletes an tx key based on the provided ID
func (c *ChainlinkClient) DeleteTxKey(chain string, id string) (*http.Response, error) {
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", id).Msg("Deleting Tx Key")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"chain": chain,
"id": id,
}).
Delete("/v2/keys/{chain}/{id}")
if err != nil {
return nil, err
}
return resp.RawResponse, err
}
// MustReadTransactionAttempts reads all transaction attempts on the Chainlink node
// and returns error if the request is unsuccessful
func (c *ChainlinkClient) MustReadTransactionAttempts() (*TransactionsData, error) {
txsData := &TransactionsData{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading Transaction Attempts")
resp, err := c.APIClient.R().
SetResult(txsData).
Get("/v2/tx_attempts")
if err != nil {
return nil, err
}
err = VerifyStatusCode(resp.StatusCode(), http.StatusOK)
return txsData, err
}
// ReadTransactions reads all transactions made by the Chainlink node
func (c *ChainlinkClient) ReadTransactions() (*TransactionsData, *http.Response, error) {
txsData := &TransactionsData{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading Transactions")
resp, err := c.APIClient.R().
SetResult(txsData).
Get("/v2/transactions")
if err != nil {
return nil, nil, err
}
return txsData, resp.RawResponse, err
}
// MustSendNativeToken sends native token (ETH usually) of a specified amount from one of its addresses to the target address
// and returns error if the request is unsuccessful
// WARNING: The txdata object that Chainlink sends back is almost always blank.
func (c *ChainlinkClient) MustSendNativeToken(amount *big.Int, fromAddress, toAddress string) (TransactionData, error) {
request := SendEtherRequest{
DestinationAddress: toAddress,
FromAddress: fromAddress,
Amount: amount.String(),
AllowHigherAmounts: true,
}
txData := SingleTransactionDataWrapper{}
resp, err := c.APIClient.R().
SetBody(request).
SetResult(txData).
Post("/v2/transfers")
framework.L.Info().
Str(NodeURL, c.Config.URL).
Str("From", fromAddress).
Str("To", toAddress).
Str("Amount", amount.String()).
Msg("Sending Native Token")
if err == nil {
err = VerifyStatusCode(resp.StatusCode(), http.StatusOK)
}
return txData.Data, err
}
// ReadVRFKeys reads all VRF keys from the Chainlink node
func (c *ChainlinkClient) ReadVRFKeys() (*VRFKeys, *http.Response, error) {
vrfKeys := &VRFKeys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading VRF Keys")
resp, err := c.APIClient.R().
SetResult(vrfKeys).
Get("/v2/keys/vrf")
if err != nil {
return nil, nil, err
}
if len(vrfKeys.Data) == 0 {
framework.L.Warn().Str(NodeURL, c.Config.URL).Msg("Found no VRF Keys on the node")
}
return vrfKeys, resp.RawResponse, err
}
// MustCreateVRFKey creates a VRF key on the Chainlink node
// and returns error if the request is unsuccessful
func (c *ChainlinkClient) MustCreateVRFKey() (*VRFKey, error) {
vrfKey := &VRFKey{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Creating VRF Key")
resp, err := c.APIClient.R().
SetResult(vrfKey).
Post("/v2/keys/vrf")
if err == nil {
err = VerifyStatusCode(resp.StatusCode(), http.StatusOK)
}
return vrfKey, err
}
// ExportVRFKey exports a vrf key by key id
func (c *ChainlinkClient) ExportVRFKey(keyId string) (*VRFExportKey, *http.Response, error) {
vrfExportKey := &VRFExportKey{}
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", keyId).Msg("Exporting VRF Key")
resp, err := c.APIClient.R().
SetPathParams(map[string]string{
"keyId": keyId,
}).
SetResult(vrfExportKey).
Post("/v2/keys/vrf/export/{keyId}")
if err != nil {
return nil, nil, err
}
return vrfExportKey, resp.RawResponse, err
}
// ImportVRFKey import vrf key
func (c *ChainlinkClient) ImportVRFKey(vrfExportKey *VRFExportKey) (*VRFKey, *http.Response, error) {
vrfKey := &VRFKey{}
framework.L.Info().Str(NodeURL, c.Config.URL).Str("ID", vrfExportKey.VrfKey.Address).Msg("Importing VRF Key")
resp, err := c.APIClient.R().
SetBody(vrfExportKey).
SetResult(vrfKey).
Post("/v2/keys/vrf/import")
if err != nil {
return nil, nil, err
}
return vrfKey, resp.RawResponse, err
}
// ReadWorkflowKeys reads all Workflow keys from the Chainlink node
func (c *ChainlinkClient) ReadWorkflowKeys() (*WorkflowKeys, *http.Response, error) {
workflowKeys := &WorkflowKeys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading Workflow Keys")
resp, err := c.APIClient.R().
SetResult(workflowKeys).
Get("/v2/keys/workflow")
if err != nil {
return nil, nil, err
}
if len(workflowKeys.Data) == 0 {
framework.L.Warn().Str(NodeURL, c.Config.URL).Msg("Found no Workflow Keys on the node")
}
return workflowKeys, resp.RawResponse, err
}
// MustReadWorkflowKeys reads all Workflow keys from the Chainlink node
func (c *ChainlinkClient) MustReadWorkflowKeys() (*WorkflowKeys, *http.Response, error) {
workflowKeys, res, err := c.ReadWorkflowKeys()
if err != nil {
return nil, res, err
}
return workflowKeys, res, VerifyStatusCode(res.StatusCode, http.StatusOK)
}
// CreateCSAKey creates a CSA key on the Chainlink node, only 1 CSA key per node
func (c *ChainlinkClient) CreateCSAKey() (*CSAKey, *http.Response, error) {
csaKey := &CSAKey{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Creating CSA Key")
resp, err := c.APIClient.R().
SetResult(csaKey).
Post("/v2/keys/csa")
if err != nil {
return nil, nil, err
}
return csaKey, resp.RawResponse, err
}
func (c *ChainlinkClient) MustReadCSAKeys() (*CSAKeys, *resty.Response, error) {
csaKeys, res, err := c.ReadCSAKeys()
if err != nil {
return nil, res, err
}
return csaKeys, res, VerifyStatusCodeWithResponse(res, http.StatusOK)
}
// ReadCSAKeys reads CSA keys from the Chainlink node
func (c *ChainlinkClient) ReadCSAKeys() (*CSAKeys, *resty.Response, error) {
csaKeys := &CSAKeys{}
framework.L.Info().Str(NodeURL, c.Config.URL).Msg("Reading CSA Keys")
resp, err := c.APIClient.R().
SetResult(csaKeys).
Get("/v2/keys/csa")