/
general_config.go
1560 lines (1353 loc) · 56.7 KB
/
general_config.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 config
import (
"fmt"
"math/big"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-contrib/sessions"
"github.com/multiformats/go-multiaddr"
"github.com/pkg/errors"
uuid "github.com/satori/go.uuid"
"github.com/spf13/viper"
"go.uber.org/zap/zapcore"
"github.com/smartcontractkit/chainlink/core/assets"
"github.com/smartcontractkit/chainlink/core/config/envvar"
"github.com/smartcontractkit/chainlink/core/config/parse"
"github.com/smartcontractkit/chainlink/core/logger"
"github.com/smartcontractkit/chainlink/core/logger/audit"
"github.com/smartcontractkit/chainlink/core/services/pg"
"github.com/smartcontractkit/chainlink/core/static"
"github.com/smartcontractkit/chainlink/core/store/dialects"
"github.com/smartcontractkit/chainlink/core/store/models"
"github.com/smartcontractkit/chainlink/core/utils"
)
//go:generate mockery --quiet --name GeneralConfig --output ./mocks/ --case=underscore
// nolint
var (
ErrEnvUnset = errors.New("env var unset")
ErrEnvInvalid = errors.New("env var invalid")
configFileNotFoundError = reflect.TypeOf(viper.ConfigFileNotFoundError{})
)
// FeatureFlags contains bools that toggle various features or chains
// TODO: document the new ones
type FeatureFlags interface {
FeatureExternalInitiators() bool
FeatureFeedsManager() bool
FeatureOffchainReporting() bool
FeatureOffchainReporting2() bool
FeatureUICSAKeys() bool
FeatureLogPoller() bool
AutoPprofEnabled() bool
EVMEnabled() bool
EVMRPCEnabled() bool
P2PEnabled() bool
SolanaEnabled() bool
StarkNetEnabled() bool
}
type LogFn func(...any)
type BasicConfig interface {
Validate() error
LogConfiguration(log LogFn)
SetLogLevel(lvl zapcore.Level) error
SetLogSQL(logSQL bool)
SetPasswords(keystore, vrf *string)
FeatureFlags
audit.Config
AdvisoryLockCheckInterval() time.Duration
AdvisoryLockID() int64
AllowOrigins() string
AppID() uuid.UUID
AuthenticatedRateLimit() int64
AuthenticatedRateLimitPeriod() models.Duration
AutoPprofBlockProfileRate() int
AutoPprofCPUProfileRate() int
AutoPprofGatherDuration() models.Duration
AutoPprofGatherTraceDuration() models.Duration
AutoPprofGoroutineThreshold() int
AutoPprofMaxProfileSize() utils.FileSize
AutoPprofMemProfileRate() int
AutoPprofMemThreshold() utils.FileSize
AutoPprofMutexProfileFraction() int
AutoPprofPollInterval() models.Duration
AutoPprofProfileRoot() string
BlockBackfillDepth() uint64
BlockBackfillSkip() bool
BridgeResponseURL() *url.URL
BridgeCacheTTL() time.Duration
CertFile() string
DatabaseBackupDir() string
DatabaseBackupFrequency() time.Duration
DatabaseBackupMode() DatabaseBackupMode
DatabaseBackupOnVersionUpgrade() bool
DatabaseBackupURL() *url.URL
DatabaseDefaultIdleInTxSessionTimeout() time.Duration
DatabaseDefaultLockTimeout() time.Duration
DatabaseDefaultQueryTimeout() time.Duration
DatabaseListenerMaxReconnectDuration() time.Duration
DatabaseListenerMinReconnectInterval() time.Duration
DatabaseLockingMode() string
DatabaseURL() url.URL
DefaultChainID() *big.Int
DefaultHTTPLimit() int64
DefaultHTTPTimeout() models.Duration
DefaultLogLevel() zapcore.Level
Dev() bool
ShutdownGracePeriod() time.Duration
EthereumHTTPURL() *url.URL
EthereumNodes() string
EthereumSecondaryURLs() []url.URL
EthereumURL() string
ExplorerAccessKey() string
ExplorerSecret() string
ExplorerURL() *url.URL
FMDefaultTransactionQueueDepth() uint32
FMSimulateTransactions() bool
GetAdvisoryLockIDConfiguredOrDefault() int64
GetDatabaseDialectConfiguredOrDefault() dialects.DialectName
HTTPServerWriteTimeout() time.Duration
InsecureFastScrypt() bool
JSONConsole() bool
JobPipelineMaxRunDuration() time.Duration
JobPipelineMaxSuccessfulRuns() uint64
JobPipelineReaperInterval() time.Duration
JobPipelineReaperThreshold() time.Duration
JobPipelineResultWriteQueueDepth() uint64
KeeperDefaultTransactionQueueDepth() uint32
KeeperGasPriceBufferPercent() uint16
KeeperGasTipCapBufferPercent() uint16
KeeperBaseFeeBufferPercent() uint16
KeeperMaximumGracePeriod() int64
KeeperRegistryCheckGasOverhead() uint32
KeeperRegistryPerformGasOverhead() uint32
KeeperRegistryMaxPerformDataSize() uint32
KeeperRegistrySyncInterval() time.Duration
KeeperRegistrySyncUpkeepQueueSize() uint32
KeeperTurnLookBack() int64
KeyFile() string
KeystorePassword() string
LeaseLockDuration() time.Duration
LeaseLockRefreshInterval() time.Duration
LogFileDir() string
LogLevel() zapcore.Level
LogSQL() bool
LogFileMaxSize() utils.FileSize
LogFileMaxAge() int64
LogFileMaxBackups() int64
LogUnixTimestamps() bool
MercuryCredentials(url string) (username, password string, err error)
MigrateDatabase() bool
ORMMaxIdleConns() int
ORMMaxOpenConns() int
Port() uint16
PyroscopeAuthToken() string
PyroscopeServerAddress() string
PyroscopeEnvironment() string
RPID() string
RPOrigin() string
ReaperExpiration() models.Duration
RootDir() string
SecureCookies() bool
SentryDSN() string
SentryDebug() bool
SentryEnvironment() string
SentryRelease() string
SessionOptions() sessions.Options
SessionTimeout() models.Duration
SolanaNodes() string
StarkNetNodes() string
TLSCertPath() string
TLSDir() string
TLSHost() string
TLSKeyPath() string
TLSPort() uint16
TLSRedirect() bool
TelemetryIngressLogging() bool
TelemetryIngressUniConn() bool
TelemetryIngressServerPubKey() string
TelemetryIngressURL() *url.URL
TelemetryIngressBufferSize() uint
TelemetryIngressMaxBatchSize() uint
TelemetryIngressSendInterval() time.Duration
TelemetryIngressSendTimeout() time.Duration
TelemetryIngressUseBatchSend() bool
TriggerFallbackDBPollInterval() time.Duration
UnAuthenticatedRateLimit() int64
UnAuthenticatedRateLimitPeriod() models.Duration
VRFPassword() string
OCR1Config
OCR2Config
P2PNetworking
P2PV1Networking
P2PV2Networking
}
// GlobalConfig holds global ENV overrides for EVM chains
// If set the global ENV will override everything
// The second bool indicates if it is set or not
type GlobalConfig interface {
GlobalBalanceMonitorEnabled() (bool, bool)
GlobalBlockEmissionIdleWarningThreshold() (time.Duration, bool)
GlobalBlockHistoryEstimatorBatchSize() (uint32, bool)
GlobalBlockHistoryEstimatorBlockDelay() (uint16, bool)
GlobalBlockHistoryEstimatorBlockHistorySize() (uint16, bool)
GlobalBlockHistoryEstimatorEIP1559FeeCapBufferBlocks() (uint16, bool)
GlobalBlockHistoryEstimatorCheckInclusionBlocks() (uint16, bool)
GlobalBlockHistoryEstimatorCheckInclusionPercentile() (uint16, bool)
GlobalBlockHistoryEstimatorTransactionPercentile() (uint16, bool)
GlobalChainType() (string, bool)
GlobalEthTxReaperInterval() (time.Duration, bool)
GlobalEthTxReaperThreshold() (time.Duration, bool)
GlobalEthTxResendAfterThreshold() (time.Duration, bool)
GlobalEvmEIP1559DynamicFees() (bool, bool)
GlobalEvmFinalityDepth() (uint32, bool)
GlobalEvmGasBumpPercent() (uint16, bool)
GlobalEvmGasBumpThreshold() (uint64, bool)
GlobalEvmGasBumpTxDepth() (uint16, bool)
GlobalEvmGasBumpWei() (*assets.Wei, bool)
GlobalEvmGasFeeCapDefault() (*assets.Wei, bool)
GlobalEvmGasLimitDefault() (uint32, bool)
GlobalEvmGasLimitMax() (uint32, bool)
GlobalEvmGasLimitMultiplier() (float32, bool)
GlobalEvmGasLimitTransfer() (uint32, bool)
GlobalEvmGasLimitOCRJobType() (uint32, bool)
GlobalEvmGasLimitDRJobType() (uint32, bool)
GlobalEvmGasLimitVRFJobType() (uint32, bool)
GlobalEvmGasLimitFMJobType() (uint32, bool)
GlobalEvmGasLimitKeeperJobType() (uint32, bool)
GlobalEvmGasPriceDefault() (*assets.Wei, bool)
GlobalEvmGasTipCapDefault() (*assets.Wei, bool)
GlobalEvmGasTipCapMinimum() (*assets.Wei, bool)
GlobalEvmHeadTrackerHistoryDepth() (uint32, bool)
GlobalEvmHeadTrackerMaxBufferSize() (uint32, bool)
GlobalEvmHeadTrackerSamplingInterval() (time.Duration, bool)
GlobalEvmLogBackfillBatchSize() (uint32, bool)
GlobalEvmLogPollInterval() (time.Duration, bool)
GlobalEvmLogKeepBlocksDepth() (uint32, bool)
GlobalEvmMaxGasPriceWei() (*assets.Wei, bool)
GlobalEvmMaxInFlightTransactions() (uint32, bool)
GlobalEvmMaxQueuedTransactions() (uint64, bool)
GlobalEvmMinGasPriceWei() (*assets.Wei, bool)
GlobalEvmNonceAutoSync() (bool, bool)
GlobalEvmUseForwarders() (bool, bool)
GlobalEvmRPCDefaultBatchSize() (uint32, bool)
GlobalFlagsContractAddress() (string, bool)
GlobalGasEstimatorMode() (string, bool)
GlobalLinkContractAddress() (string, bool)
GlobalOCRContractConfirmations() (uint16, bool)
GlobalOCRContractTransmitterTransmitTimeout() (time.Duration, bool)
GlobalOCRDatabaseTimeout() (time.Duration, bool)
GlobalOCRObservationGracePeriod() (time.Duration, bool)
GlobalOCR2AutomationGasLimit() (uint32, bool)
GlobalOperatorFactoryAddress() (string, bool)
GlobalMinIncomingConfirmations() (uint32, bool)
GlobalMinimumContractPayment() (*assets.Link, bool)
GlobalNodeNoNewHeadsThreshold() (time.Duration, bool)
GlobalNodePollFailureThreshold() (uint32, bool)
GlobalNodePollInterval() (time.Duration, bool)
GlobalNodeSelectionMode() (string, bool)
GlobalNodeSyncThreshold() (uint32, bool)
}
type GeneralConfig interface {
BasicConfig
GlobalConfig
}
// generalConfig holds parameters used by the application which can be overridden by
// setting environment variables.
//
// If you add an entry here which does not contain sensitive information, you
// should also update presenters.ConfigWhitelist and cmd_test.TestClient_RunNodeShowsEnv.
type generalConfig struct {
lggr logger.Logger
viper *viper.Viper
randomP2PPort uint16
randomP2PPortMtx sync.RWMutex
dialect dialects.DialectName
advisoryLockID int64
logLevel zapcore.Level
defaultLogLevel zapcore.Level
logSQL bool
logMutex sync.RWMutex
genAppID sync.Once
appID uuid.UUID
passwordKeystore, passwordVRF string
passwordMu sync.RWMutex // passwords are set after initialization
}
// NewGeneralConfig returns the config with the environment variables set to their
// respective fields, or their defaults if environment variables are not set.
// https://app.shortcut.com/chainlinklabs/story/33622/remove-legacy-config
func NewGeneralConfig(lggr logger.Logger) GeneralConfig {
v := viper.New()
c := newGeneralConfigWithViper(v, lggr.Named("GeneralConfig"))
c.dialect = dialects.Postgres
return c
}
func newGeneralConfigWithViper(v *viper.Viper, lggr logger.Logger) (config *generalConfig) {
schemaT := reflect.TypeOf(envvar.ConfigSchema{})
for index := 0; index < schemaT.NumField(); index++ {
item := schemaT.FieldByIndex([]int{index})
name := item.Tag.Get("env")
def, exists := item.Tag.Lookup("default")
if exists {
v.SetDefault(name, def)
}
_ = v.BindEnv(name, name)
}
config = &generalConfig{
lggr: lggr,
viper: v,
}
if err := utils.EnsureDirAndMaxPerms(config.RootDir(), os.FileMode(0700)); err != nil {
lggr.Fatalf(`Error creating root directory "%s": %+v`, config.RootDir(), err)
}
v.SetConfigName("chainlink")
v.AddConfigPath(config.RootDir())
err := v.ReadInConfig()
if err != nil && reflect.TypeOf(err) != configFileNotFoundError {
lggr.Warnf("Unable to load config file: %v\n", err)
}
ll, invalid := envvar.LogLevel.Parse()
if invalid != "" {
lggr.Error(invalid)
}
config.defaultLogLevel = ll
config.logLevel = config.defaultLogLevel
config.logSQL = viper.GetBool(envvar.Name("LogSQL"))
return
}
func (c *generalConfig) LogConfiguration(log LogFn) {
log("Environment variables\n", NewConfigPrinter(c))
}
// Validate performs basic sanity checks on config and returns error if any
// misconfiguration would be fatal to the application
func (c *generalConfig) Validate() error {
if c.P2PAnnouncePort() != 0 && c.P2PAnnounceIP() == nil {
return errors.Errorf("P2P_ANNOUNCE_PORT was given as %v but P2P_ANNOUNCE_IP was unset. You must also set P2P_ANNOUNCE_IP if P2P_ANNOUNCE_PORT is set", c.P2PAnnouncePort())
}
if _, exists := os.LookupEnv("MINIMUM_CONTRACT_PAYMENT"); exists {
return errors.Errorf("MINIMUM_CONTRACT_PAYMENT is deprecated, use MINIMUM_CONTRACT_PAYMENT_LINK_JUELS instead")
}
if _, exists := os.LookupEnv("ETH_DISABLED"); exists {
c.lggr.Error(`ETH_DISABLED is deprecated.
This will become a fatal error in a future release. Please switch to using one of the two options below instead:
- EVM_ENABLED=false - set this if you wish to completely disable all EVM chains and jobs and prevent them from ever loading (this is probably the one you want).
- EVM_RPC_ENABLED=false - set this if you wish to load all EVM chains and jobs, but prevent any RPC calls to the eth node (the old behaviour).
`)
}
if _, exists := os.LookupEnv("EVM_DISABLED"); exists {
c.lggr.Error(`EVM_DISABLED is deprecated and superceded by EVM_ENABLED.
This will become a fatal error in a future release. Please use the following instead to disable EVM chains:
EVM_ENABLED=false
`)
}
if _, err := c.OCRKeyBundleID(); errors.Is(errors.Cause(err), ErrEnvInvalid) {
return err
}
if _, err := c.OCRTransmitterAddress(); errors.Is(errors.Cause(err), ErrEnvInvalid) {
return err
}
if peers, err := c.P2PBootstrapPeers(); err == nil {
for i := range peers {
if _, err := multiaddr.NewMultiaddr(peers[i]); err != nil {
return errors.Errorf("p2p bootstrap peer %d is invalid: err %v", i, err)
}
}
}
if ct, set := c.GlobalChainType(); set && !ChainType(ct).IsValid() {
return errors.Errorf("CHAIN_TYPE is invalid: %s", ct)
}
if c.EthereumURL() == "" {
if c.EthereumHTTPURL() != nil {
c.lggr.Warn("ETH_HTTP_URL has no effect when ETH_URL is not set")
}
if len(c.EthereumSecondaryURLs()) > 0 {
c.lggr.Warn("ETH_SECONDARY_URL/ETH_SECONDARY_URLS have no effect when ETH_URL is not set")
}
} else if c.EthereumNodes() != "" {
return errors.Errorf("It is not permitted to set both ETH_URL (got %s) and EVM_NODES (got %s). Please set either one or the other", c.EthereumURL(), c.EthereumNodes())
}
// Warn on legacy OCR env vars
if c.ocrDHTLookupInterval() != 0 {
c.lggr.Error("OCR_DHT_LOOKUP_INTERVAL is deprecated, use P2P_DHT_LOOKUP_INTERVAL instead")
}
if c.ocrBootstrapCheckInterval() != 0 {
c.lggr.Error("OCR_BOOTSTRAP_CHECK_INTERVAL is deprecated, use P2P_BOOTSTRAP_CHECK_INTERVAL instead")
}
if c.ocrIncomingMessageBufferSize() != 0 {
c.lggr.Error("OCR_INCOMING_MESSAGE_BUFFER_SIZE is deprecated, use P2P_INCOMING_MESSAGE_BUFFER_SIZE instead")
}
if c.ocrOutgoingMessageBufferSize() != 0 {
c.lggr.Error("OCR_OUTGOING_MESSAGE_BUFFER_SIZE is deprecated, use P2P_OUTGOING_MESSAGE_BUFFER_SIZE instead")
}
if c.ocrNewStreamTimeout() != 0 {
c.lggr.Error("OCR_NEW_STREAM_TIMEOUT is deprecated, use P2P_NEW_STREAM_TIMEOUT instead")
}
switch c.DatabaseLockingMode() {
case "dual", "lease", "advisorylock", "none":
default:
return errors.Errorf("unrecognised value for DATABASE_LOCKING_MODE: %s (valid options are 'dual', 'lease', 'advisorylock' or 'none')", c.DatabaseLockingMode())
}
if c.LeaseLockRefreshInterval() > c.LeaseLockDuration()/2 {
return errors.Errorf("LEASE_LOCK_REFRESH_INTERVAL must be less than or equal to half of LEASE_LOCK_DURATION (got LEASE_LOCK_REFRESH_INTERVAL=%s, LEASE_LOCK_DURATION=%s)", c.LeaseLockRefreshInterval().String(), c.LeaseLockDuration().String())
}
if c.viper.GetString(envvar.Name("LogFileDir")) != "" && c.LogFileMaxSize() <= 0 {
c.lggr.Warn("LOG_FILE_DIR is ignored and has no effect when LOG_FILE_MAX_SIZE is not set to a value greater than zero")
}
{
str := os.Getenv("SKIP_DATABASE_PASSWORD_COMPLEXITY_CHECK")
var skipDatabasePasswordComplexityCheck bool
if str != "" {
var err error
skipDatabasePasswordComplexityCheck, err = strconv.ParseBool(str)
if err != nil {
return errors.Errorf("SKIP_DATABASE_PASSWORD_COMPLEXITY_CHECK has invalid value for bool: %s", str)
}
}
if !(c.Dev() || skipDatabasePasswordComplexityCheck) {
if err := ValidateDBURL(c.DatabaseURL()); err != nil {
// TODO: Make this a hard error in some future version of Chainlink > 1.4.x
c.lggr.Errorf("DEPRECATION WARNING: Database has missing or insufficiently complex password: %s.\nDatabase should be secured by a password matching the following complexity requirements:\n%s\nThis error will PREVENT BOOT in a future version of Chainlink. To bypass this check at your own risk, you may set SKIP_DATABASE_PASSWORD_COMPLEXITY_CHECK=true\n\n", err, utils.PasswordComplexityRequirements)
}
}
}
if str := c.viper.GetString("MIN_OUTGOING_CONFIRMATIONS"); str != "" {
c.lggr.Errorf("MIN_OUTGOING_CONFIRMATIONS has been removed and no longer has any effect. ETH_FINALITY_DEPTH is now used as the default for ethtx confirmations instead. You may override this on a per-task basis by setting `minConfirmations` e.g. `foo [type=ethtx minConfirmations=%s ...]`", str)
}
return nil
}
func ValidateDBURL(dbURI url.URL) error {
if strings.Contains(dbURI.Redacted(), "_test") {
return nil
}
// url params take priority if present, multiple params are ignored by postgres (it picks the first)
q := dbURI.Query()
// careful, this is a raw database password
pw := q.Get("password")
if pw == "" {
// fallback to user info
userInfo := dbURI.User
if userInfo == nil {
return errors.Errorf("DB URL must be authenticated; plaintext URLs are not allowed")
}
var pwSet bool
pw, pwSet = userInfo.Password()
if !pwSet {
return errors.Errorf("DB URL must be authenticated; password is required")
}
}
return utils.VerifyPasswordComplexity(pw)
}
func (c *generalConfig) GetAdvisoryLockIDConfiguredOrDefault() int64 {
return c.advisoryLockID
}
func (c *generalConfig) GetDatabaseDialectConfiguredOrDefault() dialects.DialectName {
return c.dialect
}
// AllowOrigins returns the CORS hosts used by the frontend.
func (c *generalConfig) AllowOrigins() string {
return c.viper.GetString(envvar.Name("AllowOrigins"))
}
func (c *generalConfig) AppID() uuid.UUID {
c.genAppID.Do(func() {
c.appID = uuid.NewV4()
})
return c.appID
}
func (c *generalConfig) AuditLoggerEnabled() bool {
return c.viper.GetBool(envvar.Name("AuditLoggerEnabled"))
}
func (c *generalConfig) AuditLoggerForwardToUrl() (models.URL, error) {
url, err := models.ParseURL(c.viper.GetString(envvar.Name("AuditLoggerForwardToUrl")))
if err != nil {
return models.URL{}, err
}
return *url, nil
}
func (c *generalConfig) AuditLoggerEnvironment() string {
if c.Dev() {
return "develop"
}
return "production"
}
func (c *generalConfig) AuditLoggerJsonWrapperKey() string {
return c.viper.GetString(envvar.Name("AuditLoggerJsonWrapperKey"))
}
func (c *generalConfig) AuditLoggerHeaders() (audit.ServiceHeaders, error) {
sh, invalid := audit.AuditLoggerHeaders.Parse()
if invalid != "" {
return nil, errors.New(invalid)
}
return sh, nil
}
// AuthenticatedRateLimit defines the threshold to which authenticated requests
// get limited. More than this many requests per AuthenticatedRateLimitPeriod will be rejected.
func (c *generalConfig) AuthenticatedRateLimit() int64 {
return c.viper.GetInt64(envvar.Name("AuthenticatedRateLimit"))
}
// AuthenticatedRateLimitPeriod defines the period to which authenticated requests get limited
func (c *generalConfig) AuthenticatedRateLimitPeriod() models.Duration {
return models.MustMakeDuration(getEnvWithFallback(c, envvar.AuthenticatedRateLimitPeriod))
}
func (c *generalConfig) AutoPprofEnabled() bool {
return c.viper.GetBool(envvar.Name("AutoPprofEnabled"))
}
func (c *generalConfig) AutoPprofProfileRoot() string {
root := c.viper.GetString(envvar.Name("AutoPprofProfileRoot"))
if root == "" {
return filepath.Join(c.RootDir(), "pprof")
}
return root
}
func (c *generalConfig) AutoPprofPollInterval() models.Duration {
return models.MustMakeDuration(getEnvWithFallback(c, envvar.AutoPprofPollInterval))
}
func (c *generalConfig) AutoPprofGatherDuration() models.Duration {
return models.MustMakeDuration(getEnvWithFallback(c, envvar.AutoPprofGatherDuration))
}
func (c *generalConfig) AutoPprofGatherTraceDuration() models.Duration {
return models.MustMakeDuration(getEnvWithFallback(c, envvar.AutoPprofGatherTraceDuration))
}
func (c *generalConfig) AutoPprofMaxProfileSize() utils.FileSize {
return getEnvWithFallback(c, envvar.New("AutoPprofMaxProfileSize", parse.FileSize))
}
func (c *generalConfig) AutoPprofCPUProfileRate() int {
return c.viper.GetInt(envvar.Name("AutoPprofCPUProfileRate"))
}
func (c *generalConfig) AutoPprofMemProfileRate() int {
return c.viper.GetInt(envvar.Name("AutoPprofMemProfileRate"))
}
func (c *generalConfig) AutoPprofBlockProfileRate() int {
return c.viper.GetInt(envvar.Name("AutoPprofBlockProfileRate"))
}
func (c *generalConfig) AutoPprofMutexProfileFraction() int {
return c.viper.GetInt(envvar.Name("AutoPprofMutexProfileFraction"))
}
func (c *generalConfig) AutoPprofMemThreshold() utils.FileSize {
return getEnvWithFallback(c, envvar.New("AutoPprofMemThreshold", parse.FileSize))
}
func (c *generalConfig) AutoPprofGoroutineThreshold() int {
return c.viper.GetInt(envvar.Name("AutoPprofGoroutineThreshold"))
}
// PyroscopeAuthToken specifies the Auth Token used to send profiling info to Pyroscope
func (c *generalConfig) PyroscopeAuthToken() string {
return c.viper.GetString(envvar.Name("PyroscopeAuthToken"))
}
// PyroscopeServerAddress specifies the Server Address where the Pyroscope instance lives
func (c *generalConfig) PyroscopeServerAddress() string {
return c.viper.GetString(envvar.Name("PyroscopeServerAddress"))
}
// PyroscopeEnvironment specifies the Environment where the Pyroscope logs will be categorized
func (c *generalConfig) PyroscopeEnvironment() string {
return c.viper.GetString(envvar.Name("PyroscopeEnvironment"))
}
// BlockBackfillDepth specifies the number of blocks before the current HEAD that the
// log broadcaster will try to re-consume logs from
func (c *generalConfig) BlockBackfillDepth() uint64 {
return getEnvWithFallback(c, envvar.BlockBackfillDepth)
}
// BlockBackfillSkip enables skipping of very long log backfills
func (c *generalConfig) BlockBackfillSkip() bool {
return getEnvWithFallback(c, envvar.NewBool("BlockBackfillSkip"))
}
// BridgeResponseURL represents the URL for bridges to send a response to.
func (c *generalConfig) BridgeResponseURL() *url.URL {
return getEnvWithFallback(c, envvar.New("BridgeResponseURL", url.Parse))
}
// BridgeCacheTTL represents the max acceptable duration for a cached bridge value to be used in case of intermittent failure.
func (c *generalConfig) BridgeCacheTTL() time.Duration {
return getEnvWithFallback(c, envvar.NewDuration("BridgeCacheTTL"))
}
// FeatureUICSAKeys enables the CSA Keys UI Feature.
func (c *generalConfig) FeatureUICSAKeys() bool {
return getEnvWithFallback(c, envvar.NewBool("FeatureUICSAKeys"))
}
func (c *generalConfig) DatabaseListenerMinReconnectInterval() time.Duration {
return getEnvWithFallback(c, envvar.NewDuration("DatabaseListenerMinReconnectInterval"))
}
func (c *generalConfig) DatabaseListenerMaxReconnectDuration() time.Duration {
return getEnvWithFallback(c, envvar.NewDuration("DatabaseListenerMaxReconnectDuration"))
}
var DatabaseBackupModeEnvVar = envvar.New("DatabaseBackupMode", parseDatabaseBackupMode)
// DatabaseBackupMode sets the database backup mode
func (c *generalConfig) DatabaseBackupMode() DatabaseBackupMode {
return getEnvWithFallback(c, DatabaseBackupModeEnvVar)
}
// DatabaseBackupFrequency turns on the periodic database backup if set to a positive value
// DatabaseBackupMode must be then set to a value other than "none"
func (c *generalConfig) DatabaseBackupFrequency() time.Duration {
return getEnvWithFallback(c, envvar.NewDuration("DatabaseBackupFrequency"))
}
// DatabaseBackupURL configures the URL for the database to backup, if it's to be different from the main on
func (c *generalConfig) DatabaseBackupURL() *url.URL {
s := c.viper.GetString(envvar.Name("DatabaseBackupURL"))
if s == "" {
return nil
}
uri, err := url.Parse(s)
if err != nil {
c.lggr.Errorf("Invalid database backup url %s", s)
return nil
}
return uri
}
// DatabaseBackupOnVersionUpgrade controls whether an automatic backup will be
// taken before migrations are run, if the node version has been bumped
func (c *generalConfig) DatabaseBackupOnVersionUpgrade() bool {
return getEnvWithFallback(c, envvar.NewBool("DatabaseBackupOnVersionUpgrade"))
}
// DatabaseBackupDir configures the directory for saving the backup file, if it's to be different from default one located in the RootDir
func (c *generalConfig) DatabaseBackupDir() string {
return c.viper.GetString(envvar.Name("DatabaseBackupDir"))
}
func (c *generalConfig) DatabaseDefaultIdleInTxSessionTimeout() time.Duration {
return pg.DefaultIdleInTxSessionTimeout
}
func (c *generalConfig) DatabaseDefaultLockTimeout() time.Duration {
return pg.DefaultLockTimeout
}
func (c *generalConfig) DatabaseDefaultQueryTimeout() time.Duration {
return pg.DefaultQueryTimeout
}
// DatabaseURL configures the URL for chainlink to connect to. This must be
// a properly formatted URL, with a valid scheme (postgres://)
func (c *generalConfig) DatabaseURL() url.URL {
s := c.viper.GetString(envvar.Name("DatabaseURL"))
uri, err := url.Parse(s)
if err != nil {
c.lggr.Error("invalid database url %s", s)
return url.URL{}
}
if uri.String() == "" {
return *uri
}
static.SetConsumerName(uri, "Default", nil)
return *uri
}
// MigrateDatabase determines whether the database will be automatically
// migrated on application startup if set to true
func (c *generalConfig) MigrateDatabase() bool {
return c.viper.GetBool(envvar.Name("MigrateDatabase"))
}
// DefaultHTTPLimit defines the size limit for HTTP requests and responses
func (c *generalConfig) DefaultHTTPLimit() int64 {
return c.viper.GetInt64(envvar.Name("DefaultHTTPLimit"))
}
// DefaultHTTPTimeout defines the default timeout for http requests
func (c *generalConfig) DefaultHTTPTimeout() models.Duration {
return models.MustMakeDuration(getEnvWithFallback(c, envvar.NewDuration("DefaultHTTPTimeout")))
}
// Dev configures "development" mode for chainlink.
func (c *generalConfig) Dev() bool {
return c.viper.GetBool(envvar.Name("Dev"))
}
// ShutdownGracePeriod is the maximum duration of graceful application shutdown.
// If exceeded, it will try closing DB lock and connection and exit immediately to avoid SIGKILL.
func (c *generalConfig) ShutdownGracePeriod() time.Duration {
return getEnvWithFallback(c, envvar.NewDuration("ShutdownGracePeriod"))
}
// FeatureExternalInitiators enables the External Initiator feature.
func (c *generalConfig) FeatureExternalInitiators() bool {
return c.viper.GetBool(envvar.Name("FeatureExternalInitiators"))
}
// FeatureFeedsManager enables the feeds manager
func (c *generalConfig) FeatureFeedsManager() bool {
return c.viper.GetBool(envvar.Name("FeatureFeedsManager"))
}
func (c *generalConfig) FeatureLogPoller() bool {
return c.viper.GetBool(envvar.Name("FeatureLogPoller"))
}
// FeatureOffchainReporting enables the OCR job type.
func (c *generalConfig) FeatureOffchainReporting() bool {
return getEnvWithFallback(c, envvar.NewBool("FeatureOffchainReporting"))
}
// FeatureOffchainReporting2 enables the OCR2 job type.
func (c *generalConfig) FeatureOffchainReporting2() bool {
return getEnvWithFallback(c, envvar.NewBool("FeatureOffchainReporting2"))
}
// FMDefaultTransactionQueueDepth controls the queue size for DropOldestStrategy in Flux Monitor
// Set to 0 to use SendEvery strategy instead
func (c *generalConfig) FMDefaultTransactionQueueDepth() uint32 {
return c.viper.GetUint32(envvar.Name("FMDefaultTransactionQueueDepth"))
}
// FMSimulateTransactions enables using eth_call transaction simulation before
// sending when set to true
func (c *generalConfig) FMSimulateTransactions() bool {
return c.viper.GetBool(envvar.Name("FMSimulateTransactions"))
}
// EthereumURL represents the URL of the Ethereum node to connect Chainlink to.
func (c *generalConfig) EthereumURL() string {
return c.viper.GetString(envvar.Name("EthereumURL"))
}
// EthereumHTTPURL is an optional but recommended url that points to the HTTP port of the primary node
func (c *generalConfig) EthereumHTTPURL() (uri *url.URL) {
urlStr := c.viper.GetString(envvar.Name("EthereumHTTPURL"))
if urlStr == "" {
return nil
}
var err error
uri, err = url.Parse(urlStr)
if err != nil || !(uri.Scheme == "http" || uri.Scheme == "https") {
c.lggr.Fatalf("Invalid Ethereum HTTP URL: %s, got error: %s", urlStr, err)
}
return
}
// EthereumNodes is a hack to allow node operators to give a JSON string that
// sets up multiple nodes
func (c *generalConfig) EthereumNodes() string {
return c.viper.GetString(envvar.Name("EthereumNodes"))
}
// EthereumSecondaryURLs is an optional backup RPC URL
// Must be http(s) format
// If specified, transactions will also be broadcast to this ethereum node
func (c *generalConfig) EthereumSecondaryURLs() []url.URL {
oldConfig := c.viper.GetString(envvar.Name("EthereumSecondaryURL"))
newConfig := c.viper.GetString(envvar.Name("EthereumSecondaryURLs"))
config := ""
if newConfig != "" {
config = newConfig
} else if oldConfig != "" {
config = oldConfig
}
urlStrings := regexp.MustCompile(`\s*[;,]\s*`).Split(config, -1)
var urls []url.URL
for _, urlString := range urlStrings {
if urlString == "" {
continue
}
url, err := url.Parse(urlString)
if err != nil {
c.lggr.Fatalf("Invalid Secondary Ethereum URL: %s, got error: %v", urlString, err)
}
urls = append(urls, *url)
}
return urls
}
// EVMRPCEnabled if false prevents any calls to any EVM-based chain RPC node
func (c *generalConfig) EVMRPCEnabled() bool {
if ethDisabled, exists := os.LookupEnv("ETH_DISABLED"); exists {
res, err := parse.Bool(ethDisabled)
if err == nil {
return !res.(bool)
}
c.lggr.Warnw("Failed to parse value for ETH_DISABLED", "err", err)
}
rpcEnabled := c.viper.GetBool(envvar.Name("EVMRPCEnabled"))
return rpcEnabled
}
// EVMEnabled allows EVM chains to be used
func (c *generalConfig) EVMEnabled() bool {
if evmDisabled, exists := os.LookupEnv("EVM_DISABLED"); exists {
res, err := parse.Bool(evmDisabled)
if err == nil {
return res.(bool)
}
c.lggr.Warnw("Failed to parse value for EVM_DISABLED", "err", err)
}
return c.viper.GetBool(envvar.Name("EVMEnabled"))
}
// SolanaEnabled allows Solana to be used
func (c *generalConfig) SolanaEnabled() bool {
return c.viper.GetBool(envvar.Name("SolanaEnabled"))
}
// StarkNetEnabled allows StarkNet to be used
func (c *generalConfig) StarkNetEnabled() bool {
return c.viper.GetBool(envvar.Name("StarknetEnabled"))
}
// P2PEnabled controls whether Chainlink will run as a P2P peer for OCR protocol
func (c *generalConfig) P2PEnabled() bool {
// We need p2p networking if either ocr1 or ocr2 is enabled
return c.P2PListenPort() > 0 || c.FeatureOffchainReporting() || c.FeatureOffchainReporting2()
}
// InsecureFastScrypt causes all key stores to encrypt using "fast" scrypt params instead
// This is insecure and only useful for local testing. DO NOT SET THIS IN PRODUCTION
func (c *generalConfig) InsecureFastScrypt() bool {
return c.viper.GetBool(envvar.Name("InsecureFastScrypt"))
}
func (c *generalConfig) TriggerFallbackDBPollInterval() time.Duration {
return getEnvWithFallback(c, envvar.NewDuration("TriggerFallbackDBPollInterval"))
}
// JobPipelineMaxRunDuration is the maximum time that a job run may take
func (c *generalConfig) JobPipelineMaxRunDuration() time.Duration {
return getEnvWithFallback(c, envvar.JobPipelineMaxRunDuration)
}
func (c *generalConfig) JobPipelineResultWriteQueueDepth() uint64 {
return getEnvWithFallback(c, envvar.JobPipelineResultWriteQueueDepth)
}
func (c *generalConfig) JobPipelineMaxSuccessfulRuns() uint64 {
return getEnvWithFallback(c, envvar.JobPipelineMaxSuccessfulRuns)
}
func (c *generalConfig) JobPipelineReaperInterval() time.Duration {
return getEnvWithFallback(c, envvar.JobPipelineReaperInterval)
}
func (c *generalConfig) JobPipelineReaperThreshold() time.Duration {
return getEnvWithFallback(c, envvar.JobPipelineReaperThreshold)
}
// KeeperRegistryCheckGasOverhead is the amount of extra gas to provide checkUpkeep() calls
// to account for the gas consumed by the keeper registry
func (c *generalConfig) KeeperRegistryCheckGasOverhead() uint32 {
return getEnvWithFallback(c, envvar.KeeperRegistryCheckGasOverhead)
}
// KeeperRegistryPerformGasOverhead is the amount of extra gas to provide performUpkeep() calls
// to account for the gas consumed by the keeper registry
func (c *generalConfig) KeeperRegistryPerformGasOverhead() uint32 {
return getEnvWithFallback(c, envvar.KeeperRegistryPerformGasOverhead)
}
// KeeperRegistryMaxPerformDataSize is the max perform data size we allow in our pipeline for an
// upkeep to be performed with
func (c *generalConfig) KeeperRegistryMaxPerformDataSize() uint32 {
return getEnvWithFallback(c, envvar.KeeperRegistryMaxPerformDataSize)
}
// KeeperDefaultTransactionQueueDepth controls the queue size for DropOldestStrategy in Keeper
// Set to 0 to use SendEvery strategy instead
func (c *generalConfig) KeeperDefaultTransactionQueueDepth() uint32 {
return c.viper.GetUint32(envvar.Name("KeeperDefaultTransactionQueueDepth"))
}
// KeeperGasPriceBufferPercent adds the specified percentage to the gas price
// used for checking whether to perform an upkeep. Only applies in legacy mode.
func (c *generalConfig) KeeperGasPriceBufferPercent() uint16 {
return uint16(c.viper.GetUint32(envvar.Name("KeeperGasPriceBufferPercent")))
}
// KeeperGasTipCapBufferPercent adds the specified percentage to the gas price
// used for checking whether to perform an upkeep. Only applies in EIP-1559 mode.
func (c *generalConfig) KeeperGasTipCapBufferPercent() uint16 {
return uint16(c.viper.GetUint32(envvar.Name("KeeperGasTipCapBufferPercent")))
}
// KeeperBaseFeeBufferPercent adds the specified percentage to the base fee
// used for checking whether to perform an upkeep. Only applies in EIP-1559 mode.
func (c *generalConfig) KeeperBaseFeeBufferPercent() uint16 {
return uint16(c.viper.GetUint32(envvar.Name("KeeperBaseFeeBufferPercent")))
}
// KeeperRegistrySyncInterval is the interval in which the RegistrySynchronizer performs a full
// sync of the keeper registry contract it is tracking *after* the most recent update triggered
// by an on-chain log.
func (c *generalConfig) KeeperRegistrySyncInterval() time.Duration {
return getEnvWithFallback(c, envvar.KeeperRegistrySyncInterval)
}
// KeeperMaximumGracePeriod is the maximum number of blocks that a keeper will wait after performing
// an upkeep before it resumes checking that upkeep
func (c *generalConfig) KeeperMaximumGracePeriod() int64 {
return c.viper.GetInt64(envvar.Name("KeeperMaximumGracePeriod"))
}
// KeeperRegistrySyncUpkeepQueueSize represents the maximum number of upkeeps that can be synced in parallel
func (c *generalConfig) KeeperRegistrySyncUpkeepQueueSize() uint32 {
return getEnvWithFallback(c, envvar.KeeperRegistrySyncUpkeepQueueSize)
}
// KeeperTurnLookBack represents the number of blocks in the past to loo back when getting block for turn
func (c *generalConfig) KeeperTurnLookBack() int64 {
return c.viper.GetInt64(envvar.Name("KeeperTurnLookBack"))
}
// JSONConsole when set to true causes logging to be made in JSON format
// If set to false, logs in console format
func (c *generalConfig) JSONConsole() bool {
return getEnvWithFallback(c, envvar.JSONConsole)
}
// ExplorerURL returns the websocket URL for this node to push stats to, or nil.
func (c *generalConfig) ExplorerURL() *url.URL {
return getEnvWithFallback(c, envvar.New("ExplorerURL", url.Parse))
}
// ExplorerAccessKey returns the access key for authenticating with explorer
func (c *generalConfig) ExplorerAccessKey() string {
return c.viper.GetString(envvar.Name("ExplorerAccessKey"))
}
// ExplorerSecret returns the secret for authenticating with explorer
func (c *generalConfig) ExplorerSecret() string {
return c.viper.GetString(envvar.Name("ExplorerSecret"))
}
// SolanaNodes is a hack to allow node operators to give a JSON string that
// sets up multiple nodes
func (c *generalConfig) SolanaNodes() string {