-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
node.go
1110 lines (956 loc) · 31.9 KB
/
node.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
package client
import (
"context"
"fmt"
"math/big"
"net/url"
"strconv"
"sync"
"time"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
"github.com/google/uuid"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/smartcontractkit/chainlink/v2/core/chains/evm/config"
evmtypes "github.com/smartcontractkit/chainlink/v2/core/chains/evm/types"
"github.com/smartcontractkit/chainlink/v2/core/logger"
"github.com/smartcontractkit/chainlink/v2/core/utils"
)
var (
promEVMPoolRPCNodeDials = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_dials_total",
Help: "The total number of dials for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCNodeDialsFailed = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_dials_failed",
Help: "The total number of failed dials for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCNodeDialsSuccess = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_dials_success",
Help: "The total number of successful dials for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCNodeVerifies = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_verifies",
Help: "The total number of chain ID verifications for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCNodeVerifiesFailed = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_verifies_failed",
Help: "The total number of failed chain ID verifications for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCNodeVerifiesSuccess = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_verifies_success",
Help: "The total number of successful chain ID verifications for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCNodeCalls = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_calls_total",
Help: "The approximate total number of RPC calls for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCNodeCallsFailed = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_calls_failed",
Help: "The approximate total number of failed RPC calls for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCNodeCallsSuccess = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "evm_pool_rpc_node_calls_success",
Help: "The approximate total number of successful RPC calls for the given RPC node",
}, []string{"evmChainID", "nodeName"})
promEVMPoolRPCCallTiming = promauto.NewHistogramVec(prometheus.HistogramOpts{
Name: "evm_pool_rpc_node_rpc_call_time",
Help: "The duration of an RPC call in nanoseconds",
Buckets: []float64{
float64(50 * time.Millisecond),
float64(100 * time.Millisecond),
float64(200 * time.Millisecond),
float64(500 * time.Millisecond),
float64(1 * time.Second),
float64(2 * time.Second),
float64(4 * time.Second),
float64(8 * time.Second),
},
}, []string{"evmChainID", "nodeName", "rpcHost", "isSendOnly", "success", "rpcCallName"})
)
//go:generate mockery --quiet --name Node --output ../mocks/ --case=underscore
// Node represents a client that connects to an ethereum-compatible RPC node
type Node interface {
Start(ctx context.Context) error
Close() error
// State returns NodeState
State() NodeState
// StateAndLatest returns NodeState with the latest received block number & total difficulty.
StateAndLatest() (state NodeState, blockNum int64, totalDifficulty *utils.Big)
// Name is a unique identifier for this node.
Name() string
ChainID() *big.Int
Order() int32
CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
BatchCallContext(ctx context.Context, b []rpc.BatchElem) error
SendTransaction(ctx context.Context, tx *types.Transaction) error
PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error)
PendingNonceAt(ctx context.Context, account common.Address) (uint64, error)
NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (uint64, error)
TransactionReceipt(ctx context.Context, txHash common.Hash) (*types.Receipt, error)
TransactionByHash(ctx context.Context, txHash common.Hash) (*types.Transaction, error)
BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error)
BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error)
BlockNumber(ctx context.Context) (uint64, error)
BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (*big.Int, error)
FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error)
SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error)
EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error)
SuggestGasPrice(ctx context.Context) (*big.Int, error)
CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) ([]byte, error)
CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) ([]byte, error)
HeaderByNumber(context.Context, *big.Int) (*types.Header, error)
HeaderByHash(context.Context, common.Hash) (*types.Header, error)
SuggestGasTipCap(ctx context.Context) (*big.Int, error)
EthSubscribe(ctx context.Context, channel chan<- *evmtypes.Head, args ...interface{}) (ethereum.Subscription, error)
String() string
}
type rawclient struct {
rpc *rpc.Client
geth *ethclient.Client
uri url.URL
}
// Node represents one ethereum node.
// It must have a ws url and may have a http url
type node struct {
utils.StartStopOnce
lfcLog logger.Logger
rpcLog logger.Logger
name string
id int32
chainID *big.Int
nodePoolCfg config.NodePool
noNewHeadsThreshold time.Duration
order int32
ws rawclient
http *rawclient
stateMu sync.RWMutex // protects state* fields
state NodeState
// Each node is tracking the last received head number and total difficulty
stateLatestBlockNumber int64
stateLatestTotalDifficulty *utils.Big
// Need to track subscriptions because closing the RPC does not (always?)
// close the underlying subscription
subs []ethereum.Subscription
// chStopInFlight can be closed to immediately cancel all in-flight requests on
// this node. Closing and replacing should be serialized through
// stateMu since it can happen on state transitions as well as node Close.
chStopInFlight chan struct{}
// nodeCtx is the node lifetime's context
nodeCtx context.Context
// cancelNodeCtx cancels nodeCtx when stopping the node
cancelNodeCtx context.CancelFunc
// wg waits for subsidiary goroutines
wg sync.WaitGroup
// nLiveNodes is a passed in function that allows this node to:
// 1. see how many live nodes there are in total, so we can prevent the last alive node in a pool from being
// moved to out-of-sync state. It is better to have one out-of-sync node than no nodes at all.
// 2. compare against the highest head (by number or difficulty) to ensure we don't fall behind too far.
nLiveNodes func() (count int, blockNumber int64, totalDifficulty *utils.Big)
}
// NewNode returns a new *node as Node
func NewNode(nodeCfg config.NodePool, noNewHeadsThreshold time.Duration, lggr logger.Logger, wsuri url.URL, httpuri *url.URL, name string, id int32, chainID *big.Int, nodeOrder int32) Node {
n := new(node)
n.name = name
n.id = id
n.chainID = chainID
n.nodePoolCfg = nodeCfg
n.noNewHeadsThreshold = noNewHeadsThreshold
n.ws.uri = wsuri
n.order = nodeOrder
if httpuri != nil {
n.http = &rawclient{uri: *httpuri}
}
n.chStopInFlight = make(chan struct{})
n.nodeCtx, n.cancelNodeCtx = context.WithCancel(context.Background())
lggr = lggr.Named("Node").With(
"nodeTier", "primary",
"nodeName", name,
"node", n.String(),
"evmChainID", chainID,
"nodeOrder", n.order,
"mode", n.getNodeMode(),
)
n.lfcLog = lggr.Named("Lifecycle")
n.rpcLog = lggr.Named("RPC")
n.stateLatestBlockNumber = -1
return n
}
// Start dials and verifies the node
// Should only be called once in a node's lifecycle
// Return value is necessary to conform to interface but this will never
// actually return an error.
func (n *node) Start(startCtx context.Context) error {
return n.StartOnce(n.name, func() error {
n.start(startCtx)
return nil
})
}
// start initially dials the node and verifies chain ID
// This spins off lifecycle goroutines.
// Not thread-safe.
// Node lifecycle is synchronous: only one goroutine should be running at a
// time.
func (n *node) start(startCtx context.Context) {
if n.state != NodeStateUndialed {
panic(fmt.Sprintf("cannot dial node with state %v", n.state))
}
dialCtx, dialCancel := n.makeQueryCtx(startCtx)
defer dialCancel()
if err := n.dial(dialCtx); err != nil {
n.lfcLog.Errorw("Dial failed: EVM Node is unreachable", "err", err)
n.declareUnreachable()
return
}
n.setState(NodeStateDialed)
verifyCtx, verifyCancel := n.makeQueryCtx(startCtx)
defer verifyCancel()
if err := n.verify(verifyCtx); errors.Is(err, errInvalidChainID) {
n.lfcLog.Errorw("Verify failed: EVM Node has the wrong chain ID", "err", err)
n.declareInvalidChainID()
return
} else if err != nil {
n.lfcLog.Errorw(fmt.Sprintf("Verify failed: %v", err), "err", err)
n.declareUnreachable()
return
}
n.declareAlive()
}
// Not thread-safe
// Pure dial: does not mutate node "state" field.
func (n *node) dial(callerCtx context.Context) error {
ctx, cancel := n.makeQueryCtx(callerCtx)
defer cancel()
promEVMPoolRPCNodeDials.WithLabelValues(n.chainID.String(), n.name).Inc()
lggr := n.lfcLog.With("wsuri", n.ws.uri.Redacted())
if n.http != nil {
lggr = lggr.With("httpuri", n.http.uri.Redacted())
}
lggr.Debugw("RPC dial: evmclient.Client#dial")
wsrpc, err := rpc.DialWebsocket(ctx, n.ws.uri.String(), "")
if err != nil {
promEVMPoolRPCNodeDialsFailed.WithLabelValues(n.chainID.String(), n.name).Inc()
return errors.Wrapf(err, "error while dialing websocket: %v", n.ws.uri.Redacted())
}
var httprpc *rpc.Client
if n.http != nil {
httprpc, err = rpc.DialHTTP(n.http.uri.String())
if err != nil {
promEVMPoolRPCNodeDialsFailed.WithLabelValues(n.chainID.String(), n.name).Inc()
return errors.Wrapf(err, "error while dialing HTTP: %v", n.http.uri.Redacted())
}
}
n.ws.rpc = wsrpc
n.ws.geth = ethclient.NewClient(wsrpc)
if n.http != nil {
n.http.rpc = httprpc
n.http.geth = ethclient.NewClient(httprpc)
}
promEVMPoolRPCNodeDialsSuccess.WithLabelValues(n.chainID.String(), n.name).Inc()
return nil
}
var errInvalidChainID = errors.New("invalid chain id")
// verify checks that all connections to eth nodes match the given chain ID
// Not thread-safe
// Pure verify: does not mutate node "state" field.
func (n *node) verify(callerCtx context.Context) (err error) {
ctx, cancel := n.makeQueryCtx(callerCtx)
defer cancel()
promEVMPoolRPCNodeVerifies.WithLabelValues(n.chainID.String(), n.name).Inc()
promFailed := func() {
promEVMPoolRPCNodeVerifiesFailed.WithLabelValues(n.chainID.String(), n.name).Inc()
}
st := n.State()
switch st {
case NodeStateDialed, NodeStateOutOfSync, NodeStateInvalidChainID:
default:
panic(fmt.Sprintf("cannot verify node in state %v", st))
}
var chainID *big.Int
if chainID, err = n.ws.geth.ChainID(ctx); err != nil {
promFailed()
return errors.Wrapf(err, "failed to verify chain ID for node %s", n.name)
} else if chainID.Cmp(n.chainID) != 0 {
promFailed()
return errors.Wrapf(
errInvalidChainID,
"websocket rpc ChainID doesn't match local chain ID: RPC ID=%s, local ID=%s, node name=%s",
chainID.String(),
n.chainID.String(),
n.name,
)
}
if n.http != nil {
if chainID, err = n.http.geth.ChainID(ctx); err != nil {
promFailed()
return errors.Wrapf(err, "failed to verify chain ID for node %s", n.name)
} else if chainID.Cmp(n.chainID) != 0 {
promFailed()
return errors.Wrapf(
errInvalidChainID,
"http rpc ChainID doesn't match local chain ID: RPC ID=%s, local ID=%s, node name=%s",
chainID.String(),
n.chainID.String(),
n.name,
)
}
}
promEVMPoolRPCNodeVerifiesSuccess.WithLabelValues(n.chainID.String(), n.name).Inc()
return nil
}
func (n *node) Close() error {
return n.StopOnce(n.name, func() error {
defer func() {
n.wg.Wait()
if n.ws.rpc != nil {
n.ws.rpc.Close()
}
}()
n.stateMu.Lock()
defer n.stateMu.Unlock()
n.cancelNodeCtx()
n.cancelInflightRequests()
n.state = NodeStateClosed
return nil
})
}
// registerSub adds the sub to the node list
func (n *node) registerSub(sub ethereum.Subscription) {
n.stateMu.Lock()
defer n.stateMu.Unlock()
n.subs = append(n.subs, sub)
}
// disconnectAll disconnects all clients connected to the node
// WARNING: NOT THREAD-SAFE
// This must be called from within the n.stateMu lock
func (n *node) disconnectAll() {
if n.ws.rpc != nil {
n.ws.rpc.Close()
}
n.cancelInflightRequests()
n.unsubscribeAll()
}
// cancelInflightRequests closes and replaces the chStopInFlight
// WARNING: NOT THREAD-SAFE
// This must be called from within the n.stateMu lock
func (n *node) cancelInflightRequests() {
close(n.chStopInFlight)
n.chStopInFlight = make(chan struct{})
}
// unsubscribeAll unsubscribes all subscriptions
// WARNING: NOT THREAD-SAFE
// This must be called from within the n.stateMu lock
func (n *node) unsubscribeAll() {
for _, sub := range n.subs {
sub.Unsubscribe()
}
n.subs = nil
}
// getChStopInflight provides a convenience helper that mutex wraps a
// read to the chStopInFlight
func (n *node) getChStopInflight() chan struct{} {
n.stateMu.RLock()
defer n.stateMu.RUnlock()
return n.chStopInFlight
}
func (n *node) getRPCDomain() string {
if n.http != nil {
return n.http.uri.Host
}
return n.ws.uri.Host
}
// RPC wrappers
// CallContext implementation
func (n *node) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return err
}
defer cancel()
lggr := n.newRqLggr().With(
"method", method,
"args", args,
)
lggr.Debug("RPC call: evmclient.Client#CallContext")
start := time.Now()
if http != nil {
err = n.wrapHTTP(http.rpc.CallContext(ctx, result, method, args...))
} else {
err = n.wrapWS(ws.rpc.CallContext(ctx, result, method, args...))
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "CallContext")
return err
}
func (n *node) BatchCallContext(ctx context.Context, b []rpc.BatchElem) error {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return err
}
defer cancel()
lggr := n.newRqLggr().With("nBatchElems", len(b), "batchElems", b)
lggr.Trace("RPC call: evmclient.Client#BatchCallContext")
start := time.Now()
if http != nil {
err = n.wrapHTTP(http.rpc.BatchCallContext(ctx, b))
} else {
err = n.wrapWS(ws.rpc.BatchCallContext(ctx, b))
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "BatchCallContext")
return err
}
func (n *node) EthSubscribe(ctx context.Context, channel chan<- *evmtypes.Head, args ...interface{}) (ethereum.Subscription, error) {
ctx, cancel, ws, _, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("args", args)
lggr.Debug("RPC call: evmclient.Client#EthSubscribe")
start := time.Now()
sub, err := ws.rpc.EthSubscribe(ctx, channel, args...)
if err == nil {
n.registerSub(sub)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "EthSubscribe")
return sub, err
}
// GethClient wrappers
func (n *node) TransactionReceipt(ctx context.Context, txHash common.Hash) (receipt *types.Receipt, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("txHash", txHash)
lggr.Debug("RPC call: evmclient.Client#TransactionReceipt")
start := time.Now()
if http != nil {
receipt, err = http.geth.TransactionReceipt(ctx, txHash)
err = n.wrapHTTP(err)
} else {
receipt, err = ws.geth.TransactionReceipt(ctx, txHash)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "TransactionReceipt",
"receipt", receipt,
)
return
}
func (n *node) TransactionByHash(ctx context.Context, txHash common.Hash) (tx *types.Transaction, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("txHash", txHash)
lggr.Debug("RPC call: evmclient.Client#TransactionByHash")
start := time.Now()
if http != nil {
tx, _, err = http.geth.TransactionByHash(ctx, txHash)
err = n.wrapHTTP(err)
} else {
tx, _, err = ws.geth.TransactionByHash(ctx, txHash)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "TransactionByHash",
"receipt", tx,
)
return
}
func (n *node) HeaderByNumber(ctx context.Context, number *big.Int) (header *types.Header, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("number", number)
lggr.Debug("RPC call: evmclient.Client#HeaderByNumber")
start := time.Now()
if http != nil {
header, err = http.geth.HeaderByNumber(ctx, number)
err = n.wrapHTTP(err)
} else {
header, err = ws.geth.HeaderByNumber(ctx, number)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "HeaderByNumber", "header", header)
return
}
func (n *node) HeaderByHash(ctx context.Context, hash common.Hash) (header *types.Header, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("hash", hash)
lggr.Debug("RPC call: evmclient.Client#HeaderByHash")
start := time.Now()
if http != nil {
header, err = http.geth.HeaderByHash(ctx, hash)
err = n.wrapHTTP(err)
} else {
header, err = ws.geth.HeaderByHash(ctx, hash)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "HeaderByHash",
"header", header,
)
return
}
func (n *node) SendTransaction(ctx context.Context, tx *types.Transaction) error {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return err
}
defer cancel()
lggr := n.newRqLggr().With("tx", tx)
lggr.Debug("RPC call: evmclient.Client#SendTransaction")
start := time.Now()
if http != nil {
err = n.wrapHTTP(http.geth.SendTransaction(ctx, tx))
} else {
err = n.wrapWS(ws.geth.SendTransaction(ctx, tx))
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "SendTransaction")
return err
}
// PendingNonceAt returns one higher than the highest nonce from both mempool and mined transactions
func (n *node) PendingNonceAt(ctx context.Context, account common.Address) (nonce uint64, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return 0, err
}
defer cancel()
lggr := n.newRqLggr().With("account", account)
lggr.Debug("RPC call: evmclient.Client#PendingNonceAt")
start := time.Now()
if http != nil {
nonce, err = http.geth.PendingNonceAt(ctx, account)
err = n.wrapHTTP(err)
} else {
nonce, err = ws.geth.PendingNonceAt(ctx, account)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "PendingNonceAt",
"nonce", nonce,
)
return
}
// NonceAt is a bit of a misnomer. You might expect it to return the highest
// mined nonce at the given block number, but it actually returns the total
// transaction count which is the highest mined nonce + 1
func (n *node) NonceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (nonce uint64, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return 0, err
}
defer cancel()
lggr := n.newRqLggr().With("account", account, "blockNumber", blockNumber)
lggr.Debug("RPC call: evmclient.Client#NonceAt")
start := time.Now()
if http != nil {
nonce, err = http.geth.NonceAt(ctx, account, blockNumber)
err = n.wrapHTTP(err)
} else {
nonce, err = ws.geth.NonceAt(ctx, account, blockNumber)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "NonceAt",
"nonce", nonce,
)
return
}
func (n *node) PendingCodeAt(ctx context.Context, account common.Address) (code []byte, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("account", account)
lggr.Debug("RPC call: evmclient.Client#PendingCodeAt")
start := time.Now()
if http != nil {
code, err = http.geth.PendingCodeAt(ctx, account)
err = n.wrapHTTP(err)
} else {
code, err = ws.geth.PendingCodeAt(ctx, account)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "PendingCodeAt",
"code", code,
)
return
}
func (n *node) CodeAt(ctx context.Context, account common.Address, blockNumber *big.Int) (code []byte, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("account", account, "blockNumber", blockNumber)
lggr.Debug("RPC call: evmclient.Client#CodeAt")
start := time.Now()
if http != nil {
code, err = http.geth.CodeAt(ctx, account, blockNumber)
err = n.wrapHTTP(err)
} else {
code, err = ws.geth.CodeAt(ctx, account, blockNumber)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "CodeAt",
"code", code,
)
return
}
func (n *node) EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return 0, err
}
defer cancel()
lggr := n.newRqLggr().With("call", call)
lggr.Debug("RPC call: evmclient.Client#EstimateGas")
start := time.Now()
if http != nil {
gas, err = http.geth.EstimateGas(ctx, call)
err = n.wrapHTTP(err)
} else {
gas, err = ws.geth.EstimateGas(ctx, call)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "EstimateGas",
"gas", gas,
)
return
}
func (n *node) SuggestGasPrice(ctx context.Context) (price *big.Int, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr()
lggr.Debug("RPC call: evmclient.Client#SuggestGasPrice")
start := time.Now()
if http != nil {
price, err = http.geth.SuggestGasPrice(ctx)
err = n.wrapHTTP(err)
} else {
price, err = ws.geth.SuggestGasPrice(ctx)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "SuggestGasPrice",
"price", price,
)
return
}
func (n *node) CallContract(ctx context.Context, msg ethereum.CallMsg, blockNumber *big.Int) (val []byte, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("callMsg", msg, "blockNumber", blockNumber)
lggr.Debug("RPC call: evmclient.Client#CallContract")
start := time.Now()
if http != nil {
val, err = http.geth.CallContract(ctx, msg, blockNumber)
err = n.wrapHTTP(err)
} else {
val, err = ws.geth.CallContract(ctx, msg, blockNumber)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "CallContract",
"val", val,
)
return
}
func (n *node) BlockByNumber(ctx context.Context, number *big.Int) (b *types.Block, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("number", number)
lggr.Debug("RPC call: evmclient.Client#BlockByNumber")
start := time.Now()
if http != nil {
b, err = http.geth.BlockByNumber(ctx, number)
err = n.wrapHTTP(err)
} else {
b, err = ws.geth.BlockByNumber(ctx, number)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "BlockByNumber",
"block", b,
)
return
}
func (n *node) BlockByHash(ctx context.Context, hash common.Hash) (b *types.Block, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("hash", hash)
lggr.Debug("RPC call: evmclient.Client#BlockByHash")
start := time.Now()
if http != nil {
b, err = http.geth.BlockByHash(ctx, hash)
err = n.wrapHTTP(err)
} else {
b, err = ws.geth.BlockByHash(ctx, hash)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "BlockByHash",
"block", b,
)
return
}
func (n *node) BlockNumber(ctx context.Context) (height uint64, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return 0, err
}
defer cancel()
lggr := n.newRqLggr()
lggr.Debug("RPC call: evmclient.Client#BlockNumber")
start := time.Now()
if http != nil {
height, err = http.geth.BlockNumber(ctx)
err = n.wrapHTTP(err)
} else {
height, err = ws.geth.BlockNumber(ctx)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "BlockNumber",
"height", height,
)
return
}
func (n *node) BalanceAt(ctx context.Context, account common.Address, blockNumber *big.Int) (balance *big.Int, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("account", account.Hex(), "blockNumber", blockNumber)
lggr.Debug("RPC call: evmclient.Client#BalanceAt")
start := time.Now()
if http != nil {
balance, err = http.geth.BalanceAt(ctx, account, blockNumber)
err = n.wrapHTTP(err)
} else {
balance, err = ws.geth.BalanceAt(ctx, account, blockNumber)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "BalanceAt",
"balance", balance,
)
return
}
func (n *node) FilterLogs(ctx context.Context, q ethereum.FilterQuery) (l []types.Log, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("q", q)
lggr.Debug("RPC call: evmclient.Client#FilterLogs")
start := time.Now()
if http != nil {
l, err = http.geth.FilterLogs(ctx, q)
err = n.wrapHTTP(err)
} else {
l, err = ws.geth.FilterLogs(ctx, q)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "FilterLogs",
"log", l,
)
return
}
func (n *node) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (sub ethereum.Subscription, err error) {
ctx, cancel, ws, _, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr().With("q", q)
lggr.Debug("RPC call: evmclient.Client#SubscribeFilterLogs")
start := time.Now()
sub, err = ws.geth.SubscribeFilterLogs(ctx, q, ch)
if err == nil {
n.registerSub(sub)
}
err = n.wrapWS(err)
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "SubscribeFilterLogs")
return
}
func (n *node) SuggestGasTipCap(ctx context.Context) (tipCap *big.Int, err error) {
ctx, cancel, ws, http, err := n.makeLiveQueryCtxAndSafeGetClients(ctx)
if err != nil {
return nil, err
}
defer cancel()
lggr := n.newRqLggr()
lggr.Debug("RPC call: evmclient.Client#SuggestGasTipCap")
start := time.Now()
if http != nil {
tipCap, err = http.geth.SuggestGasTipCap(ctx)
err = n.wrapHTTP(err)
} else {
tipCap, err = ws.geth.SuggestGasTipCap(ctx)
err = n.wrapWS(err)
}
duration := time.Since(start)
n.logResult(lggr, err, duration, n.getRPCDomain(), "SuggestGasTipCap",
"tipCap", tipCap,
)
return
}
func (n *node) ChainID() (chainID *big.Int) { return n.chainID }
// newRqLggr generates a new logger with a unique request ID
func (n *node) newRqLggr() logger.Logger {
return n.rpcLog.With(
"requestID", uuid.New(),
)
}
func (n *node) logResult(
lggr logger.Logger,
err error,
callDuration time.Duration,
rpcDomain,
callName string,
results ...interface{},
) {
lggr = lggr.With("duration", callDuration, "rpcDomain", rpcDomain, "callName", callName)
promEVMPoolRPCNodeCalls.WithLabelValues(n.chainID.String(), n.name).Inc()
if err == nil {
promEVMPoolRPCNodeCallsSuccess.WithLabelValues(n.chainID.String(), n.name).Inc()