-
Notifications
You must be signed in to change notification settings - Fork 137
/
trigger.ts
254 lines (220 loc) · 7.44 KB
/
trigger.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
import { Storage } from "@google-cloud/storage"
import crypto from "crypto"
import { Dropbox } from "dropbox"
import express from "express"
import {
subscribeToBackups,
subscribeToBlocks,
subscribeToChannels,
subscribeToInvoices,
subscribeToTransactions,
} from "lightning"
import { updateUsersPendingPayment } from "../ledger/balanceSheet"
import { activateLndHealthCheck, lndStatusEvent } from "../lndHealth"
import { onChannelUpdated } from "../lndUtils"
import { baseLogger } from "../logger"
import { setupMongoConnection } from "../mongodb"
import { transactionNotification } from "../notifications/payment"
import { Price } from "../priceImpl"
import { InvoiceUser, Transaction, User } from "../schema"
import { WalletFactory } from "../walletFactory"
const logger = baseLogger.child({ module: "trigger" })
const txsReceived = new Set()
export const uploadBackup = async ({ backup, pubkey }) => {
logger.debug({ backup }, "updating scb on dbx")
const filename = `${process.env.NETWORK}_lnd_scb_${pubkey}`
try {
const dbx = new Dropbox({ accessToken: process.env.DROPBOX_ACCESS_TOKEN })
await dbx.filesUpload({ path: `/${filename}`, contents: backup })
logger.info({ backup }, "scb backed up on dbx successfully")
} catch (error) {
logger.error({ error }, "scb backup to dbx failed")
}
logger.debug({ backup }, "updating scb on gcs")
try {
const storage = new Storage({ keyFilename: process.env.GCS_APPLICATION_CREDENTIALS })
const bucket = storage.bucket("lnd-static-channel-backups")
const file = bucket.file(`${filename}`)
await file.save(backup)
logger.info({ backup }, "scb backed up on gcs successfully")
} catch (error) {
logger.error({ error }, "scb backup to gcs failed")
}
}
export async function onchainTransactionEventHandler(tx) {
// workaround for https://github.com/lightningnetwork/lnd/issues/2267
const hash = crypto.createHash("sha256").update(JSON.stringify(tx)).digest("base64")
if (txsReceived.has(hash)) {
return
}
txsReceived.add(hash)
logger.info({ tx }, "received new onchain tx event")
const onchainLogger = logger.child({
topic: "payment",
protocol: "onchain",
tx,
onUs: false,
})
if (tx.is_outgoing) {
if (!tx.is_confirmed) {
return
// FIXME
// we have to return here because we will not know whose user the the txid belong to
// this is because of limitation for lnd onchain wallet. we only know the txid after the
// transaction has been sent. and this events is trigger before
}
await Transaction.updateMany({ hash: tx.id }, { pending: false })
onchainLogger.info(
{ success: true, pending: false, transactionType: "payment" },
"payment completed",
)
const entry = await Transaction.findOne({
account_path: { $all: ["Liabilities", "Customer"] },
hash: tx.id,
})
const user = await User.findOne({ _id: entry.account_path[2] })
await transactionNotification({
type: "onchain_payment",
user,
amount: Number(tx.tokens) - tx.fee,
txid: tx.id,
logger: onchainLogger,
})
} else {
// incoming transaction
let user
try {
user = await User.findOne({ "onchain.address": tx.output_addresses })
if (!user) {
//FIXME: Log the onchain address, need to first find which of the tx.output_addresses belongs to us
onchainLogger.fatal(`No user associated with the onchain address`)
return
}
} catch (error) {
onchainLogger.error(
{ error },
"issue in onchainTransactionEventHandler to get User id attached to output_addresses",
)
throw error
}
if (tx.is_confirmed === false) {
onchainLogger.info(
{ transactionType: "receipt", pending: true },
"mempool appearence",
)
} else {
// onchain is currently only BTC
const wallet = await WalletFactory({ user, logger: onchainLogger })
await wallet.updateOnchainReceipt()
}
const type = tx.is_confirmed ? "onchain_receipt" : "onchain_receipt_pending"
await transactionNotification({
type,
user,
logger: onchainLogger,
amount: Number(tx.tokens),
txid: tx.id,
})
}
}
export const onInvoiceUpdate = async (invoice) => {
logger.debug({ invoice }, "onInvoiceUpdate")
if (!invoice.is_confirmed) {
return
}
const invoiceUser = await InvoiceUser.findOne({ _id: invoice.id })
if (invoiceUser) {
const uid = invoiceUser.uid
const hash = invoice.id
const user = await User.findOne({ _id: uid })
const wallet = await WalletFactory({ user, logger })
await wallet.updatePendingInvoice({ hash, pubkey: invoiceUser.pubkey })
await transactionNotification({
type: "paid-invoice",
amount: invoice.received,
hash,
user,
logger,
})
} else {
logger.fatal({ invoice }, "we received an invoice but had no user attached to it")
}
}
const updatePriceForChart = async () => {
const price = new Price({ logger: baseLogger })
const interval = 1000 * 30
setInterval(async function () {
try {
await price.update()
} catch (err) {
logger.error({ err }, "can't update the price")
}
}, interval)
}
const listenerOnchain = ({ lnd }) => {
const subTransactions = subscribeToTransactions({ lnd })
subTransactions.on("chain_transaction", onchainTransactionEventHandler)
subTransactions.on("error", (err) => {
baseLogger.info({ err }, "error subTransactions")
subTransactions.removeAllListeners()
})
const subBlocks = subscribeToBlocks({ lnd })
subBlocks.on("block", () => updateUsersPendingPayment({ onchainOnly: true }))
subBlocks.on("error", (err) => {
console.log({ err }, "error subBlocks")
})
}
const listenerOffchain = ({ lnd, pubkey }) => {
const subInvoices = subscribeToInvoices({ lnd })
subInvoices.on("invoice_updated", onInvoiceUpdate)
subInvoices.on("error", (err) => {
baseLogger.info({ err }, "error subInvoices")
subInvoices.removeAllListeners()
})
const subChannels = subscribeToChannels({ lnd })
subChannels.on("channel_opened", (channel) =>
onChannelUpdated({ channel, lnd, stateChange: "opened" }),
)
subChannels.on("channel_closed", (channel) =>
onChannelUpdated({ channel, lnd, stateChange: "closed" }),
)
subChannels.on("error", (err) => {
baseLogger.info({ err }, "error subChannels")
subChannels.removeAllListeners()
})
const subBackups = subscribeToBackups({ lnd })
subBackups.on("backup", ({ backup }) => uploadBackup({ backup, pubkey }))
subBackups.on("error", (err) => {
baseLogger.info({ err }, "error subBackups")
subBackups.removeAllListeners()
})
}
const main = async () => {
lndStatusEvent.on("started", ({ lnd, pubkey, socket, type }) => {
baseLogger.info({ socket }, "lnd started")
if (type.indexOf("onchain") !== -1) {
listenerOnchain({ lnd })
}
if (type.indexOf("offchain") !== -1) {
listenerOffchain({ lnd, pubkey })
}
})
lndStatusEvent.on("stopped", ({ socket }) => {
baseLogger.info({ socket }, "lnd stopped")
})
activateLndHealthCheck()
updatePriceForChart()
}
const healthCheck = () => {
const app = express()
const port = 8888
app.get("/healthz", (req, res) => res.sendStatus(200))
app.listen(port, () => logger.info(`Health check listening on port ${port}!`))
}
// only execute if it is the main module
if (require.main === module) {
healthCheck()
setupMongoConnection()
.then(main)
.catch((err) => logger.error(err))
}