-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.js
More file actions
133 lines (120 loc) · 3.81 KB
/
node.js
File metadata and controls
133 lines (120 loc) · 3.81 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
import rand from '@mfelements/rand'
import { nodes } from './servers.js'
import logged, { withName } from '@mfelements/logger'
const requestTimeout = 2000,
attemptCount = 3;
class BlockchainError extends Error{
constructor(error){
super(`${error.code}\n${error.message}`);
this.name = 'BlockchainError'
}
}
function shuffleArray(array){
const newarr = Array.from(array);
for (let i = newarr.length - 1; i > 0; i--){
const j = Math.floor(Math.random() * (i + 1));
[newarr[i], newarr[j]] = [newarr[j], newarr[i]];
}
return newarr
}
function getKeyByVal(obj, val){
for(const i in obj) if(obj[i] === val) return i
}
async function rateNodes(){
const startTime = Date.now();
let res = [];
const blockCounter = {};
for(const node of shuffleArray(nodes)) res.push(Promise.all([ node, node, node ].map(node => sendRequestWithNode(node, rand(2), 'getinfo', requestTimeout).then(r => {
if(!r || !r.result || !r.result.blocks) return null;
const { blocks } = r.result;
if(!blockCounter[blocks]) blockCounter[blocks] = 1;
else blockCounter[blocks]++;
r.requestTime = Date.now() - startTime;
r.node = node;
return r
}))).then(v => v.reduce((p, c) => {
p.requestTime += c.requestTime;
return p
})));
res = (await Promise.all(res)).filter(v => v);
const blockCountConsensusCount = Math.max(...Object.values(blockCounter));
const blockCountConsensus = +getKeyByVal(blockCounter, blockCountConsensusCount);
res = res.filter(r => (r.result.blocks === blockCountConsensus));
res = res.sort((a, b) => (a.requestTime - b.requestTime));
return res.map(v => v.node)
}
const _ratedNodes = rateNodes();
async function sendRequest(id, method, timeout, params = [], attempt = 0, nodeArray = shuffleArray(nodes)){
const controller = new AbortController;
const { signal } = controller;
let pointer;
if(timeout !== null) pointer = setTimeout(() => controller.abort(), timeout);
const currentNode = nodeArray.pop();
try{
if(!currentNode){
attempt = attemptCount - 1;
throw new Error
}
return await fetch(currentNode, {
method: 'POST',
body: JSON.stringify({
jsonrpc: '2.0',
method,
params,
id,
}),
signal,
}).then(r => {
if(timeout !== null) clearTimeout(pointer);
return r.json()
})
} catch(e){
if(++attempt === attemptCount) throw withName('NetworkError', new Error(`cannot connect to any node after ${attemptCount} attempts`));
return sendRequest(id, method, timeout, params, attempt, nodeArray)
}
}
async function sendRequestWithNode(node, id, method, timeout, params = []){
try{
return sendRequest(id, method, timeout, params, 2, [ node ])
} catch(e){
return null
}
}
const blockchainAPI = new Proxy(Object.create(null), {
get(_, method){
if(!_[method]) Object.assign(_, {
[method]: logged(() => withName('RPC.' + method, async (...params) => {
const id = rand(12);
const data = await sendRequest(id, method, requestTimeout, params, 0, [...await _ratedNodes]);
if(data.error) throw new BlockchainError(data.error);
if(data.id !== id) throw withName('SystemError', new Error('returned info does not match requested one'));
return data.result
}))
});
return _[method]
}
});
const isBin = /[\x00-\x08\x0E-\x1F]/;
function parseNVSValue(value){
if(isBin.test(value)) return new Uint8Array([...value].map(v => v.charCodeAt(0)));
const res = {};
const lines = value.split('\n');
let line;
while(line = lines.shift()){
if(line){
const splitted = line.split('=');
res[splitted.shift()] = splitted.join('=')
}
}
return res
}
export async function getNames(prefix){
if(!prefix) throw new Error('There is no prefix specified');
const names = await blockchainAPI.name_filter('^' + prefix + ':');
const res = {};
for(const { name, value } of names){
res[name.slice(prefix.length + 1)] = parseNVSValue(value)
}
return res
}
export default blockchainAPI