-
Notifications
You must be signed in to change notification settings - Fork 134
/
yaml.ts
353 lines (281 loc) · 11.5 KB
/
yaml.ts
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
import fs from "fs"
import path from "path"
import Ajv from "ajv"
import yaml from "js-yaml"
import { I18n } from "i18n"
import { baseLogger } from "@services/logger"
import { checkedToScanDepth } from "@domain/bitcoin/onchain"
import { checkedToTargetConfs, toSats } from "@domain/bitcoin"
import { toCents } from "@domain/fiat"
import { WithdrawalFeePriceMethod } from "@domain/wallets"
import { toDays, toSeconds } from "@domain/primitives"
import { checkedToPubkey } from "@domain/bitcoin/lightning"
import { WalletCurrency } from "@domain/shared"
import { configSchema } from "./schema"
import { ConfigError } from "./error"
import { merge } from "./utils"
let customContent: string, customConfig
try {
customContent = fs.readFileSync("/var/yaml/custom.yaml", "utf8")
customConfig = yaml.load(customContent)
baseLogger.info("loading custom.yaml")
} catch (err) {
baseLogger.debug({ err }, "no custom.yaml available. using default values")
}
// TODO: fix errors
// const ajv = new Ajv({ allErrors: true, strict: "log" })
const ajv = new Ajv({ useDefaults: true })
const defaultConfig = {}
const validate = ajv.compile<YamlSchema>(configSchema)
// validate is mutating defaultConfig - even thought it's a const -> it's changing its properties
validate(defaultConfig)
export const yamlConfigInit = merge(defaultConfig, customConfig)
const valid = validate(yamlConfigInit)
if (!valid) {
baseLogger.error({ validationErrors: validate.errors }, "Invalid yaml configuration")
throw new ConfigError("Invalid yaml configuration", validate.errors)
}
export const yamlConfig = yamlConfigInit as YamlSchema
export const RATIO_PRECISION: number = yamlConfig.ratioPrecision
export const MEMO_SHARING_SATS_THRESHOLD = yamlConfig.spamLimits
.memoSharingSatsThreshold as Satoshis
export const MEMO_SHARING_CENTS_THRESHOLD = yamlConfig.spamLimits
.memoSharingCentsThreshold as UsdCents
// how many block are we looking back for getChainTransactions
const getOnChainScanDepth = (val: number): ScanDepth => {
const scanDepth = checkedToScanDepth(val)
if (scanDepth instanceof Error) throw scanDepth
return scanDepth
}
export const ONCHAIN_MIN_CONFIRMATIONS = getOnChainScanDepth(
yamlConfig.onChainWallet.minConfirmations,
)
export const ONCHAIN_SCAN_DEPTH = getOnChainScanDepth(yamlConfig.onChainWallet.scanDepth)
export const ONCHAIN_SCAN_DEPTH_OUTGOING = getOnChainScanDepth(
yamlConfig.onChainWallet.scanDepthOutgoing,
)
export const ONCHAIN_SCAN_DEPTH_CHANNEL_UPDATE = getOnChainScanDepth(
yamlConfig.onChainWallet.scanDepthChannelUpdate,
)
export const USER_ACTIVENESS_MONTHLY_VOLUME_THRESHOLD = toCents(
yamlConfig.userActivenessMonthlyVolumeThreshold,
)
export const getGaloyInstanceName = (): string => yamlConfig.name
export const getLightningAddressDomain = (): string => yamlConfig.lightningAddressDomain
export const getLightningAddressDomainAliases = (): string[] =>
yamlConfig.lightningAddressDomainAliases
export const getLocale = (): UserLanguage => yamlConfig.locale as UserLanguage
export const getPubkeysToSkipProbe = (): Pubkey[] => yamlConfig.skipFeeProbe
const i18n = new I18n()
i18n.configure({
objectNotation: true,
updateFiles: false,
locales: ["en", "es"],
directory: path.join(__dirname, "locales"),
})
export const getI18nInstance = (): I18n => i18n
export const getDisplayCurrencyConfig = (): {
code: DisplayCurrency
symbol: string
} => ({
code: yamlConfig.displayCurrency.code as DisplayCurrency,
symbol: yamlConfig.displayCurrency.symbol,
})
export const getDealerConfig = () => yamlConfig.dealer
export const getLndParams = (): LndParams[] => {
const lnds = yamlConfig.lnds
lnds.forEach((input) => {
const keys = ["_TLS", "_MACAROON", "_DNS", "_PUBKEY"]
keys.forEach((key) => {
if (!process.env[`${input.name}${key}`]) {
throw new ConfigError(`lnd params missing for: ${input.name}${key}`)
}
})
})
return lnds.map((input) => {
const cert = process.env[`${input.name}_TLS`]
if (!cert) throw new ConfigError(`missing TLS for ${input.name}`)
const macaroon = process.env[`${input.name}_MACAROON`]
if (!macaroon) throw new ConfigError(`missing macaroon for ${input.name}`)
const node = process.env[`${input.name}_DNS`]
if (!node) throw new ConfigError(`missing DNS for ${input.name}`)
const pubkey_ = process.env[`${input.name}_PUBKEY`]
if (!pubkey_) throw new ConfigError(`missing PUBKEY for ${input.name}`)
const pubkey = checkedToPubkey(pubkey_)
if (pubkey instanceof Error)
throw new ConfigError(`wrong PUBKEY formatting for ${input.name}`)
const port = process.env[`${input.name}_RPCPORT`] ?? 10009
const type = input.type.map((item) => item as NodeType) // TODO: verify if validation is done from yaml.ts
const priority = input.priority
const name = input.name
return {
cert,
macaroon,
node,
port,
pubkey,
type,
priority,
name,
}
})
}
export const getFeesConfig = (feesConfig = yamlConfig.fees): FeesConfig => {
const method = feesConfig.withdraw.method as WithdrawalFeePriceMethod
const withdrawRatioAsBasisPoints =
method === WithdrawalFeePriceMethod.flat
? 0n
: BigInt(feesConfig.withdraw.ratioAsBasisPoints)
return {
depositFeeVariable: feesConfig.deposit,
depositFeeFixed: toSats(0),
withdrawMethod: method,
withdrawRatioAsBasisPoints,
withdrawThreshold: toSats(feesConfig.withdraw.threshold),
withdrawDaysLookback: toDays(feesConfig.withdraw.daysLookback),
withdrawDefaultMin: toSats(feesConfig.withdraw.defaultMin),
}
}
export const getAccountLimits = ({
level,
accountLimits = yamlConfig.accountLimits,
}: AccountLimitsArgs): IAccountLimits => {
return {
intraLedgerLimit: toCents(accountLimits.intraLedger.level[level]),
withdrawalLimit: toCents(accountLimits.withdrawal.level[level]),
tradeIntraAccountLimit: toCents(accountLimits.tradeIntraAccount.level[level]),
}
}
const getRateLimits = (config: RateLimitInput): RateLimitOptions => {
/**
* Returns a subset of the required parameters for the
* 'rate-limiter-flexible.RateLimiterRedis' object.
*/
return {
points: config.points,
duration: toSeconds(config.duration),
blockDuration: toSeconds(config.blockDuration),
}
}
export const getRequestPhoneCodePerPhoneLimits = () =>
getRateLimits(yamlConfig.rateLimits.requestPhoneCodePerPhone)
export const getRequestPhoneCodePerPhoneMinIntervalLimits = () =>
getRateLimits(yamlConfig.rateLimits.requestPhoneCodePerPhoneMinInterval)
export const getRequestPhoneCodePerIpLimits = () =>
getRateLimits(yamlConfig.rateLimits.requestPhoneCodePerIp)
export const getFailedLoginAttemptPerPhoneLimits = () =>
getRateLimits(yamlConfig.rateLimits.failedLoginAttemptPerPhone)
export const getfailedLoginAttemptPerEmailAddressLimits = () =>
getRateLimits(yamlConfig.rateLimits.failedLoginAttemptPerEmailAddress)
export const getFailedLoginAttemptPerIpLimits = () =>
getRateLimits(yamlConfig.rateLimits.failedLoginAttemptPerIp)
export const getInvoiceCreateAttemptLimits = () =>
getRateLimits(yamlConfig.rateLimits.invoiceCreateAttempt)
export const getInvoiceCreateForRecipientAttemptLimits = () =>
getRateLimits(yamlConfig.rateLimits.invoiceCreateForRecipientAttempt)
export const getOnChainAddressCreateAttemptLimits = () =>
getRateLimits(yamlConfig.rateLimits.onChainAddressCreateAttempt)
export const getOnChainWalletConfig = () => ({
dustThreshold: yamlConfig.onChainWallet.dustThreshold,
})
export const getColdStorageConfig = (): ColdStorageConfig => {
const config = yamlConfig.coldStorage
const targetConfirmations = checkedToTargetConfs(config.targetConfirmations)
if (targetConfirmations instanceof Error) throw targetConfirmations
return {
minOnChainHotWalletBalance: toSats(config.minOnChainHotWalletBalance),
maxHotWalletBalance: toSats(config.maxHotWalletBalance),
minRebalanceSize: toSats(config.minRebalanceSize),
walletPattern: config.walletPattern,
onChainWallet: config.onChainWallet,
targetConfirmations,
}
}
export const getBuildVersions = (): {
minBuildNumberAndroid: number
lastBuildNumberAndroid: number
minBuildNumberIos: number
lastBuildNumberIos: number
} => {
const { android, ios } = yamlConfig.buildVersion
return {
minBuildNumberAndroid: android.minBuildNumber,
lastBuildNumberAndroid: android.lastBuildNumber,
minBuildNumberIos: ios.minBuildNumber,
lastBuildNumberIos: ios.lastBuildNumber,
}
}
export const PROXY_CHECK_APIKEY = yamlConfig?.PROXY_CHECK_APIKEY
export const getIpConfig = (config = yamlConfig): IpConfig => ({
ipRecordingEnabled: config.ipRecording.enabled,
proxyCheckingEnabled: config.ipRecording.proxyChecking.enabled,
})
export const getApolloConfig = (config = yamlConfig): ApolloConfig => config.apollo
export const LND_SCB_BACKUP_BUCKET_NAME = yamlConfig.lndScbBackupBucketName
export const getTestAccounts = (config = yamlConfig): TestAccount[] =>
config.test_accounts.map((account) => ({
phone: account.phone as PhoneNumber,
code: account.code as PhoneCode,
username: account.username as Username,
role: account.role,
}))
export const getCronConfig = (config = yamlConfig): CronConfig => config.cronConfig
export const getKratosConfig = (config = yamlConfig): KratosConfig => {
const kratosConfig = config.kratosConfig
const publicApi = process.env.KRATOS_PUBLIC_API ?? kratosConfig.publicApi
const adminApi = process.env.KRATOS_ADMIN_API ?? kratosConfig.adminApi
return {
...kratosConfig,
publicApi,
adminApi,
}
}
export const getCaptcha = (config = yamlConfig): CaptchaConfig => config.captcha
export const getRewardsConfig = () => {
const denyPhoneCountries = yamlConfig.rewards.denyPhoneCountries || []
const allowPhoneCountries = yamlConfig.rewards.allowPhoneCountries || []
const denyIPCountries = yamlConfig.rewards.denyIPCountries || []
const allowIPCountries = yamlConfig.rewards.allowIPCountries || []
const denyASNs = yamlConfig.rewards.denyASNs || []
const allowASNs = yamlConfig.rewards.allowASNs || []
return {
denyPhoneCountries: denyPhoneCountries.map((c) => c.toUpperCase()),
allowPhoneCountries: allowPhoneCountries.map((c) => c.toUpperCase()),
denyIPCountries: denyIPCountries.map((c) => c.toUpperCase()),
allowIPCountries: allowIPCountries.map((c) => c.toUpperCase()),
denyASNs: denyASNs.map((c) => c.toUpperCase()),
allowASNs: allowASNs.map((c) => c.toUpperCase()),
}
}
export const getDefaultAccountsConfig = (config = yamlConfig): AccountsConfig => ({
initialStatus: config.accounts.initialStatus as AccountStatus,
initialWallets: config.accounts.initialWallets,
})
export const getSwapConfig = (): SwapConfig => {
const config = yamlConfig.swap
return {
loopOutWhenHotWalletLessThan: {
amount: BigInt(config.loopOutWhenHotWalletLessThan),
currency: WalletCurrency.Btc,
},
swapOutAmount: { amount: BigInt(config.swapOutAmount), currency: WalletCurrency.Btc },
lnd1loopRestEndpoint: config.lnd1loopRestEndpoint,
lnd2loopRestEndpoint: config.lnd2loopRestEndpoint,
lnd1loopRpcEndpoint: config.lnd1loopRpcEndpoint,
lnd2loopRpcEndpoint: config.lnd2loopRpcEndpoint,
swapProviders: config.swapProviders,
feeAccountingEnabled: config.feeAccountingEnabled,
}
}
export const decisionsApi = (config = yamlConfig) => {
return config.oathkeeperConfig.decisionsApi
}
export const getJwksArgs = (config = yamlConfig) => {
const urlJkws = config.oathkeeperConfig.urlJkws
return {
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: urlJkws,
}
}