forked from Overtorment/Cashier-BTC
-
Notifications
You must be signed in to change notification settings - Fork 1
/
worker.js
83 lines (75 loc) · 2.69 KB
/
worker.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
/**
* Cashier-BTC
* -----------
* Self-hosted bitcoin payment gateway
*
* https://github.com/Overtorment/Cashier-BTC
*
**/
/**
* worker iterates through all addresses,
* marks paid and fires callbacks
*
*/
let rp = require('request-promise')
let storage = require('./models/storage')
let blockchain = require('./models/blockchain')
let config = require('./config')
require('./smoke-test')
const { createLogger, format, transports } = require('winston')
const { combine, timestamp, printf } = format
const myFormat = printf(info => {
return `${info.timestamp} ${info.level}: ${info.message}`
})
const logger = createLogger({
level: config.logging_level,
format: combine(
timestamp(),
myFormat
), // winston.format.json(),
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
// or new transports.Console()
new transports.File({ filename: './logs/error.log', level: 'error' }),
new transports.File({ filename: './logs/combined.log' })
]
})
;(async () => {
while (1) {
logger.info('worker.js' + ' tick tock')
let wait = ms => new Promise(resolve => setTimeout(resolve, ms))
let job = await storage.getUnprocessedAdressesNewerThanPromise(Date.now() - config.process_unpaid_for_period)
logger.info('worker js found ' + job.rows.length + ' records')
await processJob(job)
await wait(15000)
}
})()
async function processJob (rows) {
rows = rows || {}
rows.rows = rows.rows || []
logger.debug('worker js processing rows')
for (const row of rows.rows) {
let json = row.doc
let received = await blockchain.getreceivedbyaddress(json.address, config.minimum_confirmation_required)
logger.debug('worker.js address:' + json.address + ', expect:' + json.btc_to_ask + ', confirmed:' + received[1].result + ', unconfirmed:' + received[0].result)
if (
(!config.only_accept_equal_or_more_funds && received[1].result > 0) ||
(
(json.btc_to_ask > config.small_amount_threshhold && (received[1].result >= json.btc_to_ask)) ||
(json.btc_to_ask <= config.small_amount_threshhold && (received[0].result >= json.btc_to_ask))
)
) {
// paid ok
json.processed = 'paid'
json.paid_on = Date.now()
await storage.saveJobResultsPromise(json)
logger.info('worker.js: firing callback: ' + json.callback_url)
await rp({ uri: json.callback_url, timeout: 10 * 1000 })
// marked as paid and fired a callback. why not forward funds instantly?
// because in case of zero-conf accepted balance we would need to wait for a couple of
// confirmations till we can forward funds
}
}
}