-
Notifications
You must be signed in to change notification settings - Fork 0
/
pktutil.js
164 lines (154 loc) · 5.46 KB
/
pktutil.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
/*@flow*/
const Http = require('http');
const Querystring = require('querystring');
const Request = require('request');
const Minimist = require('minimist');
const RpcClient = require('bitcoind-rpc');
const nThen = require('nthen');
const Config = require('./config.js');
/*::
export type Rpc_Config_t = {
protocol: "http"|"https",
user: string,
pass: string,
host: string,
port: number,
rejectUnauthorized: ?bool
};
*/
// TODO ?
const validArgs = (args, cmd) => true;
const getArgs = (cmd) => {
return ``;
};
const query = (ctx, cmd, args, cb) => {
ctx.rpc.batch(() => {
ctx.rpc.batchedCalls = {
jsonrpc: "1.0",
id: "pktutil",
method: cmd,
params: args
};
}, cb);
};
const mempool = (ctx, _args, then) => {
query(ctx, 'getrawmempool', [], (err, ret) => {
//console.log(err, ret);
if (!err && ret.error) { err = ret.error; }
if (err) {
return void then(err);
} else {
return void then(null, `Transactions in mempool:\n` +
ret.result.map((x)=>`* [${x}](https://explorer.pkt.cash/tx/${x})`).join('\n'));
}
});
};
const diff = (ctx, _args, then) => {
ctx.rpc.getInfo((err, ret) => {
//console.log(err, ret);
if (!err && ret.error) { err = ret.error; }
if (err) {
return void then(err);
} else {
return void then(null, `Current difficulty: ${Math.floor(ret.result.difficulty)}`);
}
});
};
const height = (ctx, _args, then) => {
ctx.rpc.getInfo((err, ret) => {
//console.log(err, ret);
if (!err && ret.error) { err = ret.error; }
if (err) {
return void then(err);
} else {
return void then(null, `Current block height: ${Math.floor(ret.result.blocks)}`);
}
});
};
const commafy = (number) => {
return ('' + number).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
};
const balance = (ctx, args, then) => {
if (!/[a-zA-Z0-9]+/.test(args._[0])) {
return void then(`${args._[0]} is not a valid PKT address`);
}
Request(ctx.cfg.explorerGetBalance + args._[1], (err, _response, body) => {
if (err) {
return void then(err);
}
let balance = -1;
try {
const msg = JSON.parse(body);
if (msg.error) { return void then('Explorer replied: ' + msg.error); }
//console.log(msg);
balance = Number(msg.balance) / 0x40000000;
} catch (e) {
return void then(err);
}
then(null, `**${commafy(Math.floor(balance))}**` +
(''+Math.floor(balance*100)/100).replace(/^[0-9]+/, '') + ' PKT');
});
};
let COMMANDS = {};
const help = (ctx, _args, then) => {
then(null, `Available commands:\n` + Object.keys(COMMANDS).map((cname) => (
`* **/${ctx.cfg.trigger} ${cname}** - ${getArgs(COMMANDS[cname])} ${COMMANDS[cname].help}`
)).join('\n') + `\nTo have the response written to the channel you're in, use \`--noisy\` flag.`);
};
COMMANDS = {
diff: { cmd: diff, args: {}, help: 'Get the current PKT difficulty' },
mempool: { cmd: mempool, args: {}, help: 'Show transactions which are currently in the mempool' },
height: { cmd: height, args: {}, help: 'Get the current block height' },
balance: { cmd: balance, args: { _: 1 }, help: 'Get the PKT balance for an address' },
help: { cmd: help, args: {}, help: 'Print this message' },
};
const main = (cfg) => {
const ctx = Object.freeze({
cfg: Config,
rpc: new RpcClient(Config.pktd),
});
Http.createServer((req, res) => {
console.log(req.method + ' ' + req.url);
const data = [];
req.on('data', (d) => data.push(d));
req.on('end', () => {
const q = Querystring.parse(data.join(''));
//console.log(q);
const args = Minimist(q.text.split(' '), {
boolean: [ 'noisy' ],
});
const cmd = args._[0] || 'help';
const resp = {
response_type: undefined, // default is ephimeral message
text: `I don't understand the command ${cmd}, use "/${ctx.cfg.trigger} help" for more information`,
// goto_location: "https://redirect.them.here",
// username: "my username",
// icon_url: "https://www.mattermost.org/wp-content/uploads/2016/04/icon.png",
};
if (args.noisy) { resp.response_type = 'in_channel'; }
const command = COMMANDS[cmd];
nThen((w) => {
if (!command) { return; }
if (!validArgs(args, cmd)) {
resp.text = `Invalid arguments, the ${cmd} command expects: ${getArgs(cmd)}`;
return;
}
command.cmd(ctx, args, w((err, ret) => {
if (err) {
resp.text = `Error: ${err}`;
} else {
resp.text = ret;
}
if (args.noisy) {
resp.text = `@${q.user_name}: \`/${ctx.cfg.trigger} ${q.text}\`\n` + resp.text;
}
}));
}).nThen((w) => {
//console.log(JSON.stringify(resp));
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(resp));
});
});
}).listen(cfg.httpPort);
};
main(Config);