-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathconnection.js
245 lines (215 loc) · 8.24 KB
/
connection.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
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
const WebSocket = require('ws');
const { Serialize } = require('eosjs');
const { TextDecoder, TextEncoder } = require('text-encoding');
const zlib = require('zlib');
class Connection {
constructor({ socketAddresses, socketAddress, receivedAbi, receivedBlock }) {
this.receivedAbi = receivedAbi;
this.receivedBlock = receivedBlock;
this.socketAddresses = socketAddresses;
if (typeof socketAddress == 'string' && !(socketAddresses && socketAddresses.length)){
this.socketAddresses = [socketAddress]
}
this.abi = null;
this.types = null;
this.tables = new Map;
this.blocksQueue = [];
this.inProcessBlocks = false;
this.socket_index = 0;
this.currentArgs = null;
this.connected = false;
this.connecting = false;
this.connectionRetries = 0;
this.maxConnectionRetries = 100;
this.connect(this.socketAddresses[this.socket_index]);
}
connect(endpoint){
if (!this.connected && !this.connecting){
console.error(`Websocket connecting to ${endpoint}`);
this.connecting = true;
this.ws = new WebSocket(endpoint, { perMessageDeflate: false });
this.ws.on('open', () => this.onConnect());
this.ws.on('message', data => this.onMessage(data));
// this.ws.on('error', () => this.onError());
this.ws.on('close', (e) => this.onClose(e));
this.ws.on('error', (e) => {console.error(`Websocket error`, e)});
// this.ws.on('close', (e) => {console.error(`Websocket close`, e)});
}
}
disconnect() {
console.log(`Closing connection`);
this.ws.close();
}
reconnect(){
if (this.connectionRetries > this.maxConnectionRetries){
console.error(`Exceeded max reconnection attempts of ${this.maxConnectionRetries}`);
return;
}
else {
const endpoint = this.nextEndpoint();
console.log(`Reconnecting to ${endpoint}...`);
const timeout = Math.pow(2, this.connectionRetries/5) * 1000;
console.log(`Retrying with delay of ${timeout / 1000}s`);
setTimeout(() => {
this.connect(endpoint);
}, timeout);
this.connectionRetries++;
}
}
nextEndpoint(){
let next_index = ++this.socket_index;
if (next_index >= this.socketAddresses.length){
next_index = 0;
}
this.socket_index = next_index;
return this.socketAddresses[this.socket_index];
}
serialize(type, value) {
const buffer = new Serialize.SerialBuffer({ textEncoder: new TextEncoder, textDecoder: new TextDecoder });
Serialize.getType(this.types, type).serialize(buffer, value);
return buffer.asUint8Array();
}
deserialize(type, array) {
const buffer = new Serialize.SerialBuffer({ textEncoder: new TextEncoder, textDecoder: new TextDecoder, array });
let result = Serialize.getType(this.types, type).deserialize(buffer, new Serialize.SerializerState({ bytesAsUint8Array: true }));
if (buffer.readPos != array.length)
throw new Error('oops: ' + type); // todo: remove check
// {
// console.log(result.actions[0].authorization[0].actor);
// //console.log('oops: ' + type);
// }
return result;
}
toJsonUnpackTransaction(x) {
return JSON.stringify(x, (k, v) => {
if (k === 'trx' && Array.isArray(v) && v[0] === 'packed_transaction') {
const pt = v[1];
let packed_trx = pt.packed_trx;
console.log(`Compression is ${pt.compression}`);
if (pt.compression === 0)
packed_trx = this.deserialize('transaction', packed_trx);
else if (pt.compression === 1)
packed_trx = this.deserialize('transaction', zlib.unzipSync(packed_trx));
return { ...pt, packed_trx };
}
if (k === 'packed_trx' && v instanceof Uint8Array)
return this.deserialize('transaction', v);
if (v instanceof Uint8Array)
return `(${v.length} bytes)`;
return v;
}, 4)
}
send(request) {
this.ws.send(this.serialize('request', request));
}
onConnect(){
this.connected = true;
this.connecting = false;
this.connectionRetries = 0;
}
onMessage(data) {
try {
if (!this.abi) {
console.log('receiving abi')
this.rawabi = data;
this.abi = JSON.parse(data);
this.types = Serialize.getTypesFromAbi(Serialize.createInitialTypes(), this.abi);
for (const table of this.abi.tables)
this.tables.set(table.name, table.type);
if (this.receivedAbi)
this.receivedAbi();
} else {
const [type, response] = this.deserialize('result', data);
this[type](response);
}
} catch (e) {
console.log(e);
process.exit(1);
}
}
onClose(code) {
console.error(`Websocket disconnected from ${this.socketAddresses[this.socket_index]} with code ${code}`);
// this.ws.terminate();
this.abi = null;
this.types = null;
this.tables = new Map;
this.blocksQueue = [];
this.inProcessBlocks = false;
this.connected = false;
this.connecting = false;
if (code !== 1000){
// 1000 = closed by me normally
this.reconnect();
}
}
onOpen(){
this.requestBlocks(this.currentArgs)
}
requestStatus() {
this.send(['get_status_request_v0', {}]);
}
requestBlocks(requestArgs) {
if (!this.currentArgs){
this.currentArgs = {
start_block_num: 0,
end_block_num: 0xffffffff,
max_messages_in_flight: 5,
have_positions: [],
irreversible_only: false,
fetch_block: false,
fetch_traces: false,
fetch_deltas: false,
...requestArgs
};
}
this.send(['get_blocks_request_v0', this.currentArgs]);
}
get_status_result_v0(response) {
console.log(response);
}
get_blocks_result_v0(response) {
this.blocksQueue.push(response);
this.processBlocks();
}
async processBlocks() {
if (this.inProcessBlocks)
return;
this.inProcessBlocks = true;
while (this.blocksQueue.length) {
let response = this.blocksQueue.shift();
if (response.this_block){
let block_num = response.this_block.block_num;
this.currentArgs.start_block_num = block_num - 50; // replay 25 seconds
}
this.send(['get_blocks_ack_request_v0', { num_messages: 1 }]);
let block, traces = [], deltas = [];
if (this.currentArgs.fetch_block && response.block && response.block.length)
block = this.deserialize('signed_block', response.block);
if (this.currentArgs.fetch_traces && response.traces && response.traces.length)
traces = this.deserialize('transaction_trace[]', response.traces);
if (this.currentArgs.fetch_deltas && response.deltas && response.deltas.length)
deltas = this.deserialize('table_delta[]', response.deltas);
await this.receivedBlock(response, block, traces, deltas);
}
this.inProcessBlocks = false;
}
forEachRow(delta, f) {
const type = this.tables.get(delta.name);
for (let row of delta.rows) {
let data;
try {
data = this.deserialize(type, row.data);
} catch (e) {
console.error(e);
}
if (data)
f(row.present, data[1]);
}
}
dumpDelta(delta, extra) {
this.forEachRow(delta, (present, data) => {
console.log(this.toJsonUnpackTransaction({ ...extra, present, data }));
});
}
} // Connection
module.exports = {Connection}