31 lines
1.3 KiB
JavaScript
31 lines
1.3 KiB
JavaScript
|
|
// The one Electrum call the deposit gate needs: a verbose transaction.
|
||
|
|
|
||
|
|
import tls from 'node:tls';
|
||
|
|
import net from 'node:net';
|
||
|
|
|
||
|
|
export function electrumCall({ host, port, tls: useTls = true, timeoutMs = 15_000 }, method, params) {
|
||
|
|
return new Promise((resolve, reject) => {
|
||
|
|
const sock = useTls ? tls.connect({ host, port, servername: host }) : net.connect({ host, port });
|
||
|
|
let buf = '';
|
||
|
|
const timer = setTimeout(() => { sock.destroy(); reject(new Error('Electrum server did not answer')); }, timeoutMs);
|
||
|
|
const done = (err, val) => { clearTimeout(timer); sock.end(); if (err) reject(err); else resolve(val); };
|
||
|
|
sock.setEncoding('utf8');
|
||
|
|
sock.on('error', (e) => done(e));
|
||
|
|
sock.write(JSON.stringify({ jsonrpc: '2.0', id: 0, method: 'server.version', params: ['pithos-hosted', '1.4'] }) + '\n');
|
||
|
|
sock.write(JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }) + '\n');
|
||
|
|
sock.on('data', (d) => {
|
||
|
|
buf += d;
|
||
|
|
let i;
|
||
|
|
while ((i = buf.indexOf('\n')) >= 0) {
|
||
|
|
const line = buf.slice(0, i);
|
||
|
|
buf = buf.slice(i + 1);
|
||
|
|
let msg;
|
||
|
|
try { msg = JSON.parse(line); } catch { continue; }
|
||
|
|
if (msg.id !== 1) continue;
|
||
|
|
if (msg.error) return done(new Error(msg.error.message || 'Electrum error'));
|
||
|
|
return done(null, msg.result);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
});
|
||
|
|
}
|