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
|
import config from "$config";
import store from "$lib/store";
import { emit } from "$lib/sockets";
import { v4 } from "uuid";
import { notify } from "$lib/notifications";
import { db, g, s, t } from "$lib/db";
import { l, err, warn } from "$lib/logging";
import { fail, wait } from "$lib/utils";
import { callWebhook } from "$lib/webhooks";
import dollarsToWords from "dollars-to-words";
import got from "got";
import mqtt from "mqtt";
import { spawn } from "child_process";
import ffmpeg from "fluent-ffmpeg";
import fs from "fs";
import EventEmitter from "events";
import crc32 from "buffer-crc32";
export const types = {
internal: "internal",
bitcoin: "bitcoin",
lightning: "lightning",
pot: "pot",
classic: "classic"
};
export let debit = async (
hash,
amount,
fee = 0,
memo,
user,
type = types.internal,
id = v4()
) => {
let ref;
let { id: uid, currency, username } = user;
let rate = store.rates[currency];
let invoice = await g(`invoice:${hash}`);
if (invoice) {
ref = invoice.uid;
let equivalentRate =
invoice.rate * (store.rates[currency] / store.rates[invoice.currency]);
if (Math.abs(invoice.rate / store.rates[invoice.currency] - 1) < 0.01) {
rate = equivalentRate;
} else {
warn("rate slipped", hash, invoice.rate, equivalentRate);
}
}
let tip = parseInt(invoice?.tip) || null;
if (!amount || amount < 0) fail("Amount must be greater than zero");
let ourfee = [types.bitcoin, types.lightning].includes(type)
? Math.round(amount * config.fee)
: 0;
await t(`balance:${uid}`, async (balance, db) => {
await t(`credit:${type}:${uid}`, async (credit, db) => {
let covered = Math.min(credit, ourfee) || 0;
ourfee -= covered;
l(
"debiting",
user.username,
balance,
amount,
tip,
fee,
ourfee,
amount + fee + ourfee + tip
);
if (balance < amount + tip + fee + ourfee) fail("Insufficient funds");
await db
.multi()
.decrBy(`credit:${type}:${uid}`, covered)
.decrBy(`balance:${uid}`, amount + tip + fee + ourfee)
.exec();
});
});
let p = {
id,
amount: -amount,
fee,
ourfee,
memo,
uid,
confirmed: true,
rate,
currency,
type,
ref,
tip,
created: Date.now()
};
await s(`payment:${id}`, p);
await db.lPush(`${uid}:payments`, id);
l("sent", type, user.username, amount);
emit(user.id, "payment", p);
return p;
};
export let credit = async (hash, amount, memo, ref, type = types.internal) => {
amount = parseInt(amount) || 0;
let invoice = await g(`invoice:${hash}`);
if (!invoice) return warn("failed to credit", hash, ", invoice not found");
let { tip } = invoice;
tip = parseInt(tip) || 0;
if (!memo) ({ memo } = invoice);
if (amount < 0 || tip < 0) fail("Invalid amount");
if (type === types.internal) amount += tip;
let user = await g(`user:${invoice.uid}`);
let { id: uid, currency, username } = user;
let rate = store.rates[currency];
let equivalentRate =
invoice.rate * (store.rates[currency] / store.rates[invoice.currency]);
if (Math.abs(invoice.rate / store.rates[invoice.currency] - 1) < 0.01) {
rate = equivalentRate;
} else {
warn("rate slipped", hash, invoice.rate, equivalentRate);
}
let p = {
hash,
amount: parseInt(amount - tip),
uid,
rate,
currency,
memo,
ref,
tip,
type,
confirmed: true,
created: Date.now()
};
if (type === types.bitcoin) invoice.pending += amount;
else invoice.received += amount;
let balance = "balance";
if (type === types.bitcoin) {
let [txid, vout] = ref.split(":").slice(-2);
p.id = `${txid}:${vout}`;
p.confirmed = false;
balance = "pending";
} else {
p.id = hash;
}
let m = await db.multi();
if ([types.bitcoin, types.lightning].includes(type))
m.incrBy(`credit:${type}:${uid}`, Math.round(amount * config.fee));
m.set(`invoice:${hash}`, JSON.stringify(invoice))
.set(`payment:${p.id}`, JSON.stringify(p))
.lPush(`${uid}:payments`, p.id)
.incrBy(`${balance}:${uid}`, amount)
.exec();
l("received", type, username, amount, tip);
emit(uid, "payment", p);
notify(user, `Received ${amount} sats`);
callWebhook(invoice, p);
if (user.hasprinter) {
let client = mqtt.connect("mqtt://ln.coinos.io", config.mqtt);
client.subscribe(username);
let connected;
if (user.hasspeaker) {
let fiat = parseFloat(((amount * p.rate) / 100000000).toFixed(2));
let words = dollarsToWords(fiat);
if (fiat === 0.02) {
words = "there is no second best";
client.publish(username, "easter");
}
if (fiat === 0.21) {
words = "tick tock, next block";
client.publish(username, "easter");
}
if (fiat === 0.69) {
words = "have fun staying poor";
client.publish(username, "easter");
}
let raw = `/app/data/uploads/${p.id}-raw.mp3`;
let out = `/app/data/uploads/${p.id}.mp3`;
let mimic = spawn("/mimic", [
"-t",
words,
"-voice",
"/cmu_us_axb.flitevox",
"-o",
raw
]);
mimic.stdout.on("end", async () => {
await wait(() => connected);
client.publish(username, "start");
let n = 0;
let t = 0;
let sz = 480;
let chunks = [];
let buf = Buffer.alloc(0);
let send = n => {
let chunk = chunks[n];
if (!chunk) return;
let num = Buffer.alloc(2);
num.writeUInt16BE(n, 0);
let flag = Buffer.from("dddddddd", "hex");
let checksum = crc32(chunk).reverse();
let payload = Buffer.concat([flag, num, checksum, chunk]);
client.publish(username, payload);
};
client.on("message", (topic, message) => {
if (topic !== username) return;
let m = message.toString();
if (m.startsWith("missing:")) {
let missing = m.replace("missing:", "").split(",");
for (let n of missing) send(chunk);
client.publish(username, `end:${n}`);
}
});
ffmpeg(raw)
.audioBitrate(128)
.audioFrequency(44100)
.toFormat("mp3")
.on("error", err => {
console.log("Error:", err);
})
.stream()
.on("data", data => {
t += data.length;
let i = 0;
buf = Buffer.concat([buf, data]);
while (i < data.length) {
chunks[n] = data.slice(i, i + sz);
send(n);
n++;
i += sz;
}
})
.on("end", () => {
client.publish(username, `end:${chunks.length}`);
});
});
}
client.on("connect", function() {
client.publish(
username,
`pay:${p.amount}:${p.tip}:${p.rate}:${p.created}:${p.id}`
);
setTimeout(() => (connected = true), 50);
});
}
return p;
};
export let confirm = async (address, txid, vout) => {
let id = `payment:${txid}:${vout}`;
let p = await g(id);
if (!p) return db.sAdd("missed", id);
if (p.confirmed) return;
p.confirmed = true;
emit(p.uid, "payment", p);
l("confirming", txid, p.uid);
await db
.multi()
.set(id, JSON.stringify(p))
.decrBy(`pending:${p.uid}`, p.amount)
.incrBy(`balance:${p.uid}`, p.amount)
.exec();
};
|