-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathtallycoin_connect.js
238 lines (201 loc) · 6.62 KB
/
tallycoin_connect.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
const express = require('express')
const jsonParser = require('body-parser').json()
const fs = require('fs')
const WebSocket = require('ws')
const lnService = require('ln-service')
const server = require('http').createServer()
const shajs = require('sha.js')
const app = express()
let ws, wstimer, connected = 'N', users = [], keys = {}
// Utils
const writeConfig = update => {
if(typeof(keys) === 'object'){
const config = JSON.stringify(Object.assign(keys, update), null, 2)
if (config != '' && config !== null){
fs.writeFile(CONFIG_FILE, config, err => {
if (err) console.error(err)
})
}else{
console.log('tallycoin_api.key has missing parameters')
}
}
}
const hash_text = text => shajs('sha256').update(text).digest('hex')
const base64FromFile = file => Buffer.from(fs.readFileSync(file)).toString('base64')
// Load config from file and use environment variables as overrides
const {
TALLYCOIN_APIKEY,
TALLYCOIN_PASSWD,
TALLYCOIN_PASSWD_CLEARTEXT,
LND_TLSCERT_PATH,
LND_MACAROON_PATH,
LND_SOCKET = '127.0.0.1:10009',
CONFIG_FILE = 'tallycoin_api.key',
PORT = 8123
} = process.env
try {
keys = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'))
} catch (err) {
console.error('Could not read config file:', err.message)
}
// override from env
if (LND_TLSCERT_PATH) keys.tls_cert = base64FromFile(LND_TLSCERT_PATH)
if (LND_MACAROON_PATH) keys.macaroon = base64FromFile(LND_MACAROON_PATH)
// override unless customized
if (!keys.lnd_socket && LND_SOCKET) keys.lnd_socket = LND_SOCKET
if (!keys.tallycoin_api && TALLYCOIN_APIKEY) keys.tallycoin_api = TALLYCOIN_APIKEY
if (!keys.tallycoin_passwd && TALLYCOIN_PASSWD) keys.tallycoin_passwd = TALLYCOIN_PASSWD
if (!keys.tallycoin_passwd && TALLYCOIN_PASSWD_CLEARTEXT) keys.tallycoin_passwd = hash_text(TALLYCOIN_PASSWD_CLEARTEXT)
writeConfig(keys)
// Create a server for transaction and setup pages
app.set('trust proxy', true)
app.use('/assets', express.static(__dirname + '/assets'))
app.get('/', (req, res) => {
if (users.includes(req.ip) || !keys.tallycoin_passwd) {
res.sendFile(__dirname + '/index.html')
} else {
res.sendFile(__dirname + '/login.html')
}
})
server.on('request', app)
// Retrieve invoice list from LND
app.post('/list', jsonParser, (req, res) => {
const { lnd } = lnService.authenticatedLndGrpc({
cert: keys.tls_cert,
macaroon: keys.macaroon,
socket: keys.lnd_socket
})
lnService.getInvoices({ lnd }, (err, invoices) => {
if (err) {
const [code, name, { err: { details } }] = err
res.status(code).json({ error: details })
} else {
res.json(invoices)
}
})
})
// Confirm sync connection to Tallycoin server
app.post('/sync', jsonParser, (req, res) => {
let lnd_status = 'Y'
if (keys.macaroon == '' || keys.tls_cert == '' || keys.tls_cert == null || keys.macaroon == null) {
lnd_status = 'N'
}
res.json({
sync: connected,
api: keys.tallycoin_api,
lnd: lnd_status
})
})
// Login when password is set
app.post('/login', jsonParser, (req, res) => {
if (hash_text(req.body.passwd) == keys.tallycoin_passwd) {
users.push(req.ip)
res.json({ login_state: 'Y' })
} else {
res.json({ login_state: 'N' })
}
})
// Save API from setup page
app.post('/save_api', jsonParser, (req, res) => {
writeConfig({
tallycoin_api: req.body.api
})
})
// Save password from setup page
app.post('/save_passwd', jsonParser, (req, res) => {
writeConfig({
tallycoin_passwd: hash_text(req.body.passwd)
})
})
// start connection to Tallycoin server
start_websocket()
// Start server
server.listen(PORT, () => {
console.log(`Running on http://localhost:${PORT}`)
})
// Websocket connection
function start_websocket() {
console.log('Starting websocket')
clearInterval(wstimer)
ws = new WebSocket('wss://ws.tallycoin.app:8123/')
let restarting
// send setup message and API key every 20 seconds to keep a live connection
ws.on('open', function open() {
restarting = 'N'
connected = 'Y'
ws.send(JSON.stringify({ setup: keys.tallycoin_api }))
wstimer = setInterval(() => {
if (ws.readyState == 1) {
ws.send(JSON.stringify({ ping: keys.tallycoin_api }))
}
}, 20000)
})
// Parse incoming message
ws.on('message', function incoming(data) {
const msg = JSON.parse(data)
lightning(msg.type, msg)
})
// Error handling. Try reconnect every 10 seconds.
ws.on('close', function close(e) {
clearInterval(wstimer)
connected = 'N'
if (restarting != 'Y') {
restarting = 'Y'
console.log('Close websocket')
setTimeout(start_websocket, 10000)
}
})
ws.on('error', function error(e) {
clearInterval(wstimer)
connected = 'N'
if (restarting != 'Y') {
restarting = 'Y'
setTimeout(start_websocket, 10000)
}
})
}
// Parse incoming messages and reply to Tallycoin server
function lightning(type, data) {
const { lnd } = lnService.authenticatedLndGrpc({
cert: keys.tls_cert,
macaroon: keys.macaroon,
socket: keys.lnd_socket
})
// When message 'payment_create' received, get fresh invoice from LND and send response to Tallycoin server
if (type == 'payment_create') {
var description = data.description
var description_hash = null
// Check LNURL payRequest: https://github.com/lnurl/luds/blob/luds/06.md
if( description.includes('[[\"text/plain\"') ){
description_hash = hash_text(description)
var new_description = JSON.parse(description)
description = new_description[0][1]
}
lnService.createInvoice({ lnd, is_including_private_channels: true, is_fallback_included: true, description: description, description_hash: description_hash, tokens: data.amount}, (err, invoice) => {
ws.send(JSON.stringify({
type: 'payment_data',
id: invoice['id'],
chain_address: invoice['chain_address'],
payment_request: invoice['request'],
api_key: keys.tallycoin_api,
unique_id: data.unique_id
}))
})
}
// When message 'payment_verify' received, check payment status of specific invoice with LND and send response to Tallycoin server
if (type == 'payment_verify') {
lnService.getInvoice({ lnd, id: data.inv_id }, (err, invoice) => {
const received = parseInt(invoice['received']) // amount received in satoshis
const tokens = parseInt(invoice['tokens']) // amount requested in satoshis
const status = received >= tokens ? 'paid' : 'unpaid'
ws.send(JSON.stringify({
type: 'payment_verify',
id: invoice['id'],
status: status,
amount: tokens,
api_key: keys.tallycoin_api,
unique_id: data.unique_id
}))
})
}
}