forked from slickage/baron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaymentutil.js
386 lines (370 loc) · 14 KB
/
paymentutil.js
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
var helper = require(__dirname + '/helper');
var validate = require(__dirname + '/validate');
var BigNumber = require('bignumber.js');
var bitstamped = require('bitstamped');
var bitcoinUtil = require(__dirname + '/bitcoinutil');
var db = require(__dirname + '/db');
var api = require(__dirname + '/insightapi');
var config = require(__dirname + '/config');
var invoiceHelper = require(__dirname + '/invoicehelper');
var invoiceWebhooks = require(__dirname + '/invoicewebhooks');
var _ = require('lodash');
// ===============================================
// Creating New Payments with Transaction Data
// ===============================================
function stopWatchingPayment(paymentId) {
db.findPaymentById(paymentId, function(err, payment) {
if (err || !payment) {
return console.log('Error retrieving payment by id');
}
if (payment.watched && Number(payment.amount_paid) === 0) {
payment.watched = false;
db.insert(payment);
}
});
}
function resetPayment(payment, expectedAmount, cb) {
var curTime = new Date().getTime();
bitstamped.getTicker(curTime, function(err, docs) {
if (!err && docs.rows && docs.rows.length > 0) {
var tickerData = docs.rows[0].value;
var rate = Number(tickerData.vwap); // Bitcoin volume weighted average price
payment.expected_amount = expectedAmount;
payment.spot_rate = rate;
payment.watched = true;
payment.created = new Date().getTime();
db.insert(payment, function(err, result) {
if (err) {
return cb(err, null);
}
else {
setTimeout(stopWatchingPayment, config.paymentValidForMinutes * 60 * 1000, result.id);
return cb(null, payment);
}
});
}
else {
return cb(err, null);
}
});
}
// Inserts a new payment into the db
function insertPayment(invoiceId, address, expectedAmount, cb) {
var curTime = new Date().getTime();
bitstamped.getTicker(curTime, function(err, docs) {
if (!err && docs.rows && docs.rows.length > 0) {
var tickerData = docs.rows[0].value;
var rate = Number(tickerData.vwap); // Bitcoin volume weighted average price
var payment = {
invoice_id: invoiceId,
address: address,
amount_paid: 0, // Always stored in BTC
expected_amount: expectedAmount,
block_hash: null,
spot_rate: rate,
status: 'unpaid',
created: new Date().getTime(),
paid_timestamp: null,
tx_id: null, // Bitcoind txid for transaction
watched: true, // Watch payments till 100 conf or expired
type: 'payment'
};
db.insert(payment, function(err, result) {
if (err) {
return cb(err, null);
}
else {
setTimeout(stopWatchingPayment, config.paymentValidForMinutes * 60 * 1000, result.id);
payment._id = result.id;
return cb(null, payment);
}
});
}
else {
return cb(err, null);
}
});
}
// Creates a new payment object associated with invoice
var createNewPayment = function(invoiceId, expectedAmount, cb) {
db.findInvoiceAndPayments(invoiceId, function(err, invoice, paymentsArr) {
if (!err && invoice && paymentsArr.length > 0) {
var activePayment = invoiceHelper.getActivePayment(paymentsArr);
if(!activePayment.watched && Number(activePayment.amount_paid) === 0) {
resetPayment(activePayment, expectedAmount, cb);
return;
}
}
bitcoinUtil.getPaymentAddress(function(err, info) {
if (err) {
return cb(err, null);
}
else {
insertPayment(invoiceId, info.result, expectedAmount, cb);
}
});
});
};
// ===============================================
// Updating Payments with Transaction Data
// ===============================================
function validateTransactionBlock(payment, transaction, cb) {
if (transaction.blockhash) {
api.getBlock(transaction.blockhash, function(err, block) {
if (err) {
return cb(err, false, false);
}
var blockIsValid = validate.block(block);
// Block is invalid and payment and transaction blockhash match
var isReorg = !blockIsValid && payment.block_hash === transaction.blockhash;
// Incoming block is valid and payment and transaction hash both are populated but dont match
var blockHashChanged = blockIsValid && payment.block_hash && transaction.blockhash && payment.block_hash !== transaction.blockhash;
// Block isnt valid and payment.block_hash === transaction.blockhash.
return cb(null, blockIsValid, isReorg || blockHashChanged);
});
}
else if (!transaction.blockhash && payment.block_hash) { // Reorg
// No tx blockhash but payment used to have one. Indicates reorg.
return cb(null, false, true);
}
else { // If transaction doesnt have blockhash it is initial notification
return cb(null, true, false);
}
}
var processReorgedPayment = function(payment, blockHash) {
payment.block_hash = null;
if (blockHash) {
var reorgHistory = payment.reorg_history ? payment.reorg_history : [];
if (!_.contains(reorgHistory, blockHash)) {
reorgHistory.push(blockHash);
}
payment.reorg_history = reorgHistory;
}
if (payment.confirmations === -1) {
payment.status = 'invalid';
payment.watched = false;
}
else { // if confirmations arent -1 could be reorged back in
payment.status = 'pending';
}
};
var processReorgedPayments = function (blockHash) {
db.getPaymentByBlockHash(blockHash, function(err, paymentsArr) {
if (err) {
return console.log(err);
}
if (paymentsArr) {
paymentsArr.forEach(function (payment) {
var origStatus = payment.status;
processReorgedPayment(payment, blockHash);
db.insert(payment, function(err) {
if (!err) {
invoiceWebhooks.determineWebhookCall(payment.invoice_id, origStatus, payment.status);
}
});
});
}
});
};
var processReorgAndCheckDoubleSpent = function (transaction, blockHash, cb) {
if (transaction.txid && transaction.walletconflicts.length > 0) {
db.findPaymentByTxId(transaction.txid, function(err, payment) {
if (err) {
return cb ? cb(err) : null;
}
var origStatus = payment.status;
//TODO: Notify Admin of Double Spend
if (transaction.walletconflicts.length > 0) {
payment.double_spent_history = transaction.walletconflicts;
}
if (blockHash) {
processReorgedPayment(payment, blockHash);
}
db.insert(payment, function(err) {
if (err) {
cb(err);
}
else {
invoiceWebhooks.determineWebhookCall(payment.invoice_id, origStatus, payment.status);
cb();
}
});
});
}
};
// Updates payment with transaction data from listsinceblock or walletnotify
function updatePaymentWithTransaction(payment, transaction, cb) {
db.findInvoice(payment.invoice_id, function(err, invoice) {
if (err) {
return cb(err);
}
validateTransactionBlock(payment, transaction, function(err, blockIsValid, isReorg) {
if (err) {
return cb(err);
}
var oldBlockHash = payment.block_hash;
if (blockIsValid) {
var origStatus = payment.status;
var curStatus = helper.getPaymentStatus(payment, transaction.confirmations, invoice);
if(validate.paymentChanged(payment, transaction, curStatus)) {
if (isReorg) { // Handle Reorg History.
var reorgHistory = payment.reorg_history ? payment.reorg_history : [];
if (!_.contains(reorgHistory, oldBlockHash)) {
reorgHistory.push(oldBlockHash);
}
payment.reorgHistory = reorgHistory;
}
if (transaction.walletconflicts.length > 0) { // Handle Double Spent History.
payment.double_spent_history = transaction.walletconflicts;
}
var amount = transaction.amount;
payment.amount_paid = amount;
payment.tx_id = transaction.txid;
payment.block_hash = transaction.blockhash ? transaction.blockhash : null;
payment.paid_timestamp = transaction.time * 1000;
var paymentIsUnpaid = payment.status === 'unpaid';
payment.watched = paymentIsUnpaid ? paymentIsUnpaid : payment.watched;
var isUSD = invoice.currency.toUpperCase() === 'USD';
if (isUSD) {
var actualPaid = new BigNumber(amount).times(payment.spot_rate);
var expectedPaid = new BigNumber(payment.expected_amount).times(payment.spot_rate);
actualPaid = helper.roundToDecimal(actualPaid.valueOf(), 2);
expectedPaid = helper.roundToDecimal(expectedPaid.valueOf(), 2);
var closeEnough = new BigNumber(actualPaid).equals(expectedPaid);
if (closeEnough) {
payment.expected_amount = amount;
}
}
// Update status after updating amounts to see if it changed.
payment.status = helper.getPaymentStatus(payment, transaction.confirmations, invoice);
db.insert(payment, function (err) {
if (isReorg) {
processReorgedPayments(oldBlockHash);
}
if (!err) {
invoiceWebhooks.determineWebhookCall(payment.invoice_id, origStatus, payment.status);
}
return cb(err);
});
}
else {
var error = new Error('No changes to update.');
return cb(error);
}
}
else if (isReorg) {
// Check for doublespend
processReorgAndCheckDoubleSpent(transaction, payment.block_hash, function(err) {
if (err) {
return cb(err);
}
// If no double spend process reorg for all payments with block hash
processReorgedPayments(payment.block_hash);
});
}
});
});
}
// Handles case where user sends multiple payments to same address
// Creates payment with transaction data from listsinceblock or walletnotify
function createNewPaymentWithTransaction(invoiceId, transaction, cb) {
var paidTime = transaction.time * 1000;
db.findInvoiceAndPayments(invoiceId, function(err, invoice, paymentsArr) {
if (err) {
return cb(err);
}
bitstamped.getTicker(paidTime, function(err, docs) {
if (!err && docs.rows && docs.rows.length > 0) {
var tickerData = docs.rows[0].value;
var rate = new BigNumber(tickerData.vwap);
var totalPaid = new BigNumber(invoiceHelper.getTotalPaid(invoice, paymentsArr));
var remainingBalance = new BigNumber(invoice.balance_due).minus(totalPaid);
var isUSD = invoice.currency.toUpperCase() === 'USD';
if (isUSD) {
var actualPaid = helper.roundToDecimal(rate.times(transaction.amount).valueOf(), 2);
var closeEnough = new BigNumber(actualPaid).equals(helper.roundToDecimal(remainingBalance, 2));
if (closeEnough) {
remainingBalance = transaction.amount;
}
else {
remainingBalance = Number(remainingBalance.dividedBy(rate).valueOf());
}
}
remainingBalance = helper.roundToDecimal(remainingBalance, 8);
var payment = {
invoice_id: invoiceId,
address: transaction.address,
amount_paid: Number(transaction.amount),
expected_amount: Number(remainingBalance),
block_hash: transaction.blockhash ? transaction.blockhash : null,
spot_rate: Number(rate.valueOf()), // Exchange rate at time of payment
created: new Date().getTime(),
paid_timestamp: paidTime,
tx_id: transaction.txid, // Bitcoind txid for transaction
watched: true,
type: 'payment'
};
payment.status = helper.getPaymentStatus(payment, transaction.confirmations, invoice);
// New transaction to known address has wallet conflicts. This indicates that
// this transaction is a mutated tx of a known payment.
if (transaction.walletconflicts.length > 0) {
payment.double_spent_history = transaction.walletconflicts;
var latestConflictingTx = transaction.walletconflicts[transaction.walletconflicts.length - 1];
// Need to grab spot rate and expected_amount from conflicting payment
paymentsArr.forEach(function(curPayment) {
if (curPayment.tx_id === latestConflictingTx) {
payment.expected_amount = curPayment.expected_amount;
payment.spot_rate = curPayment.spot_rate;
}
});
}
db.insert(payment, cb);
}
else {
return cb(err);
}
});
});
}
// Updates payment with walletnotify data
var updatePayment = function(transaction, cb) {
if (!transaction.txid || !transaction.address || transaction.amount < 0) {
var error = new Error('Ignoring irrelevant transaction.');
return cb(error, null);
}
db.findPaymentByTxId(transaction.txid, function(err, payment) {
if (!err && payment) {
// Updating confirmations of a watched payment
updatePaymentWithTransaction(payment, transaction, cb);
}
else {
// look up payment by address, maybe it hasnt got a txid yet
db.findPayments(transaction.address, function(err, paymentsArr) {
if (err) {
return cb(err, null);
}
var invoiceId = null;
paymentsArr.forEach(function(payment) {
if (!payment.tx_id) {
// Initial update from walletnotify
updatePaymentWithTransaction(payment, transaction, cb);
}
else {
invoiceId = payment.invoice_id;
}
});
if (invoiceId) {
// Create new payment for same invoice as pre-existing payment
createNewPaymentWithTransaction(invoiceId, transaction, cb);
}
});
}
});
};
module.exports = {
createNewPayment: createNewPayment,
updatePayment: updatePayment,
processReorgedPayment: processReorgedPayment,
processReorgedPayments: processReorgedPayments,
processReorgAndCheckDoubleSpent: processReorgAndCheckDoubleSpent
};