-
Notifications
You must be signed in to change notification settings - Fork 0
/
arbiters.js
69 lines (64 loc) · 2.08 KB
/
arbiters.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
/*jslint node: true */
"use strict";
var db = require('./db.js');
var device = require('./device.js');
var http = require('https');
var validationUtils = require('ocore/validation_utils.js');
var arbStoreInfos = {}; // map arbiter_address => arbstoreInfo {address: ..., cut: ...}
function getInfo(address, cb) {
var cb = cb || function() {};
db.query("SELECT device_pub_key, real_name FROM wallet_arbiters WHERE arbiter_address=?", [address], function(rows){
if (rows.length && rows[0].real_name) { // request again if no real name
cb(null, rows[0]);
} else {
device.requestFromHub("hub/get_arbstore_url", address, function(err, url){
if (err) {
return cb(err);
}
requestInfoFromArbStore(url+'/api/arbiter/'+address, function(err, info){
if (err) {
return cb(err);
}
db.query("REPLACE INTO wallet_arbiters (arbiter_address, device_pub_key, real_name) VALUES (?, ?, ?)", [address, info.device_pub_key, info.real_name], function() {cb(null, info);});
});
});
}
});
}
function requestInfoFromArbStore(url, cb){
http.get(url, function(resp){
var data = '';
resp.on('data', function(chunk){
data += chunk;
});
resp.on('end', function(){
try {
cb(null, JSON.parse(data));
} catch(ex) {
cb(ex);
}
});
}).on("error", cb);
}
function getArbstoreInfo(arbiter_address, cb) {
if (!cb)
return new Promise(resolve => getArbstoreInfo(arbiter_address, resolve));
if (arbStoreInfos[arbiter_address]) return cb(null, arbStoreInfos[arbiter_address]);
device.requestFromHub("hub/get_arbstore_url", arbiter_address, function(err, url){
if (err) {
return cb(err);
}
requestInfoFromArbStore(url+'/api/get_info', function(err, info){
if (err)
return cb(err);
if (!info.address || !validationUtils.isValidAddress(info.address) || parseFloat(info.cut) === NaN || parseFloat(info.cut) < 0 || parseFloat(info.cut) >= 1) {
cb("mailformed info received from ArbStore");
}
info.url = url;
arbStoreInfos[arbiter_address] = info;
cb(null, info);
});
});
}
exports.getInfo = getInfo;
exports.getArbstoreInfo = getArbstoreInfo;