forked from byteball/headless-obyte
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc_service.js
201 lines (186 loc) · 6.78 KB
/
rpc_service.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
/*jslint node: true */
/*
Accept commands via JSON-RPC API.
The daemon listens on port 6332 by default.
See https://github.com/byteball/headless-byteball/wiki/Running-RPC-service for detailed description of the API
*/
"use strict";
var headlessWallet = require('../start.js');
var conf = require('byteballcore/conf.js');
var eventBus = require('byteballcore/event_bus.js');
var db = require('byteballcore/db.js');
var mutex = require('byteballcore/mutex.js');
var storage = require('byteballcore/storage.js');
var constants = require('byteballcore/constants.js');
var validationUtils = require("byteballcore/validation_utils.js");
var wallet_id;
if (conf.bSingleAddress)
throw Error('can`t run in single address mode');
function initRPC() {
var composer = require('byteballcore/composer.js');
var network = require('byteballcore/network.js');
var rpc = require('json-rpc2');
var walletDefinedByKeys = require('byteballcore/wallet_defined_by_keys.js');
var Wallet = require('byteballcore/wallet.js');
var balances = require('byteballcore/balances.js');
var server = rpc.Server.$create({
'websocket': true, // is true by default
'headers': { // allow custom headers is empty by default
'Access-Control-Allow-Origin': '*'
}
});
/**
* Returns information about the current state.
* @return { last_mci: {Integer}, last_stable_mci: {Integer}, count_unhandled: {Integer} }
*/
server.expose('getinfo', function(args, opt, cb) {
var response = {};
storage.readLastMainChainIndex(function(last_mci){
response.last_mci = last_mci;
storage.readLastStableMcIndex(db, function(last_stable_mci){
response.last_stable_mci = last_stable_mci;
db.query("SELECT COUNT(*) AS count_unhandled FROM unhandled_joints", function(rows){
response.count_unhandled = rows[0].count_unhandled;
cb(null, response);
});
});
});
});
/**
* Creates and returns new wallet address.
* @return {String} address
*/
server.expose('getnewaddress', function(args, opt, cb) {
mutex.lock(['rpc_getnewaddress'], function(unlock){
walletDefinedByKeys.issueNextAddress(wallet_id, 0, function(addressInfo) {
unlock();
cb(null, addressInfo.address);
});
});
});
/**
* Returns address balance(stable and pending).
* If address is invalid, then returns "invalid address".
* If your wallet doesn`t own the address, then returns "address not found".
* @param {String} address
* @return {"base":{"stable":{Integer},"pending":{Integer}}} balance
*
* If no address supplied, returns wallet balance(stable and pending).
* @return {"base":{"stable":{Integer},"pending":{Integer}}} balance
*/
server.expose('getbalance', function(args, opt, cb) {
let start_time = Date.now();
var address = args[0];
if (address) {
if (validationUtils.isValidAddress(address))
db.query("SELECT COUNT(*) AS count FROM my_addresses WHERE address = ?", [address], function(rows) {
if (rows[0].count)
db.query(
"SELECT asset, is_stable, SUM(amount) AS balance \n\
FROM outputs JOIN units USING(unit) \n\
WHERE is_spent=0 AND address=? AND sequence='good' AND asset IS NULL \n\
GROUP BY is_stable", [address],
function(rows) {
var balance = {
base: {
stable: 0,
pending: 0
}
};
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
balance.base[row.is_stable ? 'stable' : 'pending'] = row.balance;
}
cb(null, balance);
}
);
else
cb("address not found");
});
else
cb("invalid address");
}
else
Wallet.readBalance(wallet_id, function(balances) {
console.log('getbalance took '+(Date.now()-start_time)+'ms');
cb(null, balances);
});
});
/**
* Returns wallet balance(stable and pending) without commissions earned from headers and witnessing.
*
* @return {"base":{"stable":{Integer},"pending":{Integer}}} balance
*/
server.expose('getmainbalance', function(args, opt, cb) {
let start_time = Date.now();
balances.readOutputsBalance(wallet_id, function(balances) {
console.log('getmainbalance took '+(Date.now()-start_time)+'ms');
cb(null, balances);
});
});
/**
* Returns transaction list.
* If address is invalid, then returns "invalid address".
* @param {String} address or {since_mci: {Integer}, unit: {String}}
* @return [{"action":{'invalid','received','sent','moved'},"amount":{Integer},"my_address":{String},"arrPayerAddresses":[{String}],"confirmations":{0,1},"unit":{String},"fee":{Integer},"time":{String},"level":{Integer},"asset":{String}}] transactions
*
* If no address supplied, returns wallet transaction list.
* @return [{"action":{'invalid','received','sent','moved'},"amount":{Integer},"my_address":{String},"arrPayerAddresses":[{String}],"confirmations":{0,1},"unit":{String},"fee":{Integer},"time":{String},"level":{Integer},"asset":{String}}] transactions
*/
server.expose('listtransactions', function(args, opt, cb) {
let start_time = Date.now();
if (Array.isArray(args) && typeof args[0] === 'string') {
var address = args[0];
if (validationUtils.isValidAddress(address))
Wallet.readTransactionHistory({address: address}, function(result) {
cb(null, result);
});
else
cb("invalid address");
}
else{
var opts = {wallet: wallet_id};
if (args.unit && validationUtils.isValidBase64(args.unit, constants.HASH_LENGTH))
opts.unit = args.unit;
else if (args.since_mci && validationUtils.isNonnegativeInteger(args.since_mci))
opts.since_mci = args.since_mci;
else
opts.limit = 200;
Wallet.readTransactionHistory(opts, function(result) {
console.log('listtransactions '+JSON.stringify(args)+' took '+(Date.now()-start_time)+'ms');
cb(null, result);
});
}
});
/**
* Send funds to address.
* If address is invalid, then returns "invalid address".
* @param {String} address
* @param {Integer} amount
* @return {String} status
*/
server.expose('sendtoaddress', function(args, opt, cb) {
console.log('sendtoaddress '+JSON.stringify(args));
let start_time = Date.now();
var amount = args[1];
var toAddress = args[0];
if (amount && toAddress) {
if (validationUtils.isValidAddress(toAddress))
headlessWallet.issueChangeAddressAndSendPayment(null, amount, toAddress, null, function(err, unit) {
console.log('sendtoaddress '+JSON.stringify(args)+' took '+(Date.now()-start_time)+'ms, unit='+unit+', err='+err);
cb(err, err ? undefined : unit);
});
else
cb("invalid address");
}
else
cb("wrong parameters");
});
headlessWallet.readSingleWallet(function(_wallet_id) {
wallet_id = _wallet_id;
// listen creates an HTTP server on localhost only
var httpServer = server.listen(conf.rpcPort, conf.rpcInterface);
httpServer.timeout = 900*1000;
});
}
eventBus.on('headless_wallet_ready', initRPC);