-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsteem-interface.js
More file actions
312 lines (253 loc) · 8.57 KB
/
steem-interface.js
File metadata and controls
312 lines (253 loc) · 8.57 KB
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
const fs = require('fs');
const utils = require('./utils');
const steem_engine = require('./steem-engine');
const dsteem = require('dsteem');
let _options = {
logging_level: 3,
rpc_error_limit: 5,
rpc_nodes: ["https://api.steemit.com", "https://steemd.minnowsupportproject.org", "https://seed.steemmonsters.com"],
save_state: saveState,
load_state: loadState,
on_block: null,
on_op: null,
on_behind_blocks: null,
steem_engine: {
rpc_url: "https://api.steem-engine.com/rpc",
chain_id: "ssc-mainnet1"
}
};
let clients = [];
let last_block = 0;
function init(options) {
_options = Object.assign(_options, options);
utils.set_options(_options);
clients = _options.rpc_nodes.map(n => new dsteem.Client(n, { timeout: 1000 }));
if(_options.steem_engine)
steem_engine.init(_options.steem_engine);
}
async function api(method_name, params) {
var result = null;
for(var i = 0; i < clients.length; i++) {
if(clients[i].sm_disabled) {
// Check how recently the node was disabled and re-enable if it's been over an hour
if(clients[i].sm_last_error_date > Date.now() - 60 * 60 * 1000)
continue;
else
clients[i].sm_disabled = false;
}
result = await tryDatabaseCall(clients[i], method_name, params);
if(result.success)
return result.result;
}
utils.log('All nodes failed calling [' + method_name + ']!', 1, 'Red');
return result;
}
async function tryDatabaseCall(client, method_name, params) {
return await client.database.call(method_name, params)
.then(async result => { return { success: true, result: result } })
.catch(async err => {
utils.log('Error calling [' + method_name + '] from node: ' + client.address + ', Error: ' + err, 1, 'Yellow');
// Record that this client had an error
updateClientErrors(client);
return { success: false, error: err }
});
}
async function broadcast(method_name, params, key) {
return new Promise(async (resolve, reject) => {
let error = null;
for(let i = 0; i < clients.length; i++) {
if(clients[i].sm_disabled) {
// Check how recently the node was disabled and re-enable if it's been over an hour
if(clients[i].sm_last_error_date > Date.now() - 60 * 60 * 1000)
continue;
else
clients[i].sm_disabled = false;
}
try {
resolve(await trySteemBroadcast(clients[i], method_name, params, key));
return;
} catch(err) {
if(utils.isTxError(err))
return reject(err);
error = err;
}
}
utils.log(`All nodes failed broadcasting [${method_name}]!`, 1, 'Red');
reject(error);
});
}
async function trySteemBroadcast(client, method_name, params, key) {
return new Promise(async (resolve, reject) => {
try {
let result = await client.broadcast.sendOperations([[method_name, params]], dsteem.PrivateKey.fromString(key));
resolve(result);
} catch (err) {
utils.log(`Error broadcasting tx [${method_name}] from node: ${client.address}, Error: ${err}`, 1, 'Yellow');
// Record that this client had an error (if it's not an error with the transaction itself)
if(!utils.isTxError(err))
updateClientErrors(client);
reject(err);
}
});
}
async function sendSignedTx(tx) {
let op_name = tx.operations && tx.operations.length > 0 ? tx.operations[0][0] : null;
return new Promise(async (resolve, reject) => {
let error = null;
for(let i = 0; i < clients.length; i++) {
if(clients[i].sm_disabled) {
// Check how recently the node was disabled and re-enable if it's been over an hour
if(clients[i].sm_last_error_date > Date.now() - 60 * 60 * 1000)
continue;
else
clients[i].sm_disabled = false;
}
try {
resolve(await trySendSignedTx(clients[i], tx));
return;
} catch(err) {
if(utils.isTxError(err))
return reject(err);
error = err;
}
}
utils.log(`All nodes failed sending signed tx [${op_name}]!`, 1, 'Red');
reject(error);
});
}
async function trySendSignedTx(client, tx) {
return new Promise(async (resolve, reject) => {
try {
let result = await client.broadcast.send(tx);
resolve(result);
} catch (err) {
utils.log(`Error sending signed tx from node: ${client.address}, Error: ${err}`, 1, 'Yellow');
// Record that this client had an error (if it's not an error with the transaction itself)
if(!utils.isTxError(err))
updateClientErrors(client);
reject(err);
}
});
}
function updateClientErrors(client) {
// Check if the client has had errors within the last 10 minutes
if(client.sm_last_error_date && client.sm_last_error_date > Date.now() - 10 * 60 * 1000)
client.sm_errors++;
else
client.sm_errors = 1;
client.sm_last_error_date = Date.now();
if(client.sm_errors >= _options.rpc_error_limit) {
utils.log('Disabling node: ' + client.address + ' due to too many errors!', 1, 'Red');
client.sm_disabled = true;
}
// If all clients have been disabled, we're in trouble, but just try re-enabling them all
if(!clients.find(c => !c.sm_disabled)) {
utils.log('All clients disabled!!! Re-enabling them...', 1, 'Red');
clients.forEach(c => c.sm_disabled = false);
}
}
async function custom_json(id, json, account, key, use_active) {
var data = {
id: id,
json: JSON.stringify(json),
required_auths: use_active ? [account] : [],
required_posting_auths: use_active ? [] : [account]
}
return new Promise((resolve, reject) => {
broadcast('custom_json', data, key)
.then(r => {
utils.log(`Custom JSON [${id}] broadcast successfully. Tx: [${r.id}]`, 3);
resolve(r);
})
.catch(async err => {
utils.log(`Error broadcasting custom_json [${id}]. Error: ${err}`, 1, 'Red');
reject(err);
});
});
}
async function transfer(from, to, amount, memo, key) {
return await broadcast('transfer', { amount, from, memo, to }, key);
}
async function stream(options) {
_options = Object.assign(_options, options);
// Load saved state (last block read)
if(_options.load_state)
last_block = await _options.load_state();
// Start streaming blocks
getNextBlock();
}
async function getNextBlock() {
var result = await api('get_dynamic_global_properties');
if(!result) {
setTimeout(getNextBlock, 1000);
return;
}
let cur_block_num = _options.irreversible ? result.last_irreversible_block_num : (result.head_block_number - (_options.wait_blocks || 0));
if(!last_block || isNaN(last_block))
last_block = cur_block_num - 1;
// We are 20+ blocks behind!
if(cur_block_num >= last_block + 20) {
utils.log('Streaming is ' + (cur_block_num - last_block) + ' blocks behind!', 1, 'Red');
if(_options.on_behind_blocks)
_options.on_behind_blocks(cur_block_num- last_block);
}
// If we have a new block, process it
while(cur_block_num > last_block)
await processBlock(last_block + 1);
// Attempt to load the next block after a 1 second delay (or faster if we're behind and need to catch up)
setTimeout(getNextBlock, 1000);
}
async function processBlock(block_num) {
var block = await api('get_block', [block_num]);
// Log every 1000th block loaded just for easy parsing of logs, or every block depending on logging level
utils.log('Processing block [' + block_num + ']...', block_num % 1000 == 0 ? 1 : 4);
if(!block || !block.transactions) {
// Block couldn't be loaded...this is typically because it hasn't been created yet
utils.log('Error loading block [' + block_num + ']', 4);
await utils.timeout(1000);
return;
}
if(_options.on_block)
await _options.on_block(block_num, block);
if(_options.on_op) {
var block_time = new Date(block.timestamp + 'Z');
// Loop through all of the transactions and operations in the block
for(var i = 0; i < block.transactions.length; i++) {
var trans = block.transactions[i];
for(var op_index = 0; op_index < trans.operations.length; op_index++) {
var op = trans.operations[op_index];
try {
await _options.on_op(op, block_num, block.block_id, block.previous, block.transaction_ids[i], block_time);
} catch(err) { utils.log(`Error processing transaction [${block.transaction_ids[i]}]: ${err}`, 1, 'Red'); }
}
}
}
last_block = block_num;
if(_options.save_state)
_options.save_state(last_block);
}
async function loadState() {
// Check if state has been saved to disk, in which case load it
if (fs.existsSync('state.json')) {
let state = JSON.parse(fs.readFileSync("state.json"));
utils.log('Restored saved state: ' + JSON.stringify(state));
return state.last_block;
}
}
function saveState(last_block) {
// Save the last block read to disk
fs.writeFile('state.json', JSON.stringify({ last_block }), function (err) {
if (err)
utils.log(err);
});
}
module.exports = {
init,
api,
broadcast,
custom_json,
transfer,
stream,
sendSignedTx,
steem_engine: steem_engine
}