forked from ethereum/mist
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb3Http.js
More file actions
130 lines (98 loc) · 3.17 KB
/
web3Http.js
File metadata and controls
130 lines (98 loc) · 3.17 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
const Q = require('bluebird');
const EventEmitter = require('events').EventEmitter;
const got = require('got');
const SocketBase = require('./base');
const STATE = SocketBase.STATE;
const Web3SocketBase = require('./web3Base');
class HttpSocket extends EventEmitter {
constructor(_parentSocket) {
super();
this._log = _parentSocket._log.create('HttpSocket');
}
connect(connectConfig) {
this._log.trace('Connect', connectConfig);
this._hostPort = connectConfig.hostPort;
const payload = JSON.stringify({
jsonrpc: '2.0',
id: 0,
method: 'eth_accounts',
params: [],
});
this._call(payload)
.then(() => {
this._log.trace('Connection successful');
this.emit('connect');
})
.catch((err) => {
this._log.trace('Connection failed', err);
this.emit.bind(this, new Error('Unable to connect to HTTP RPC'));
});
}
destroy() {
this._log.trace('Destroy');
this._hostPort = null;
this.emit('close');
}
write(data) {
this._log.trace('Write data', data);
this._call(data)
.then((body) => {
this._log.trace('Got response', body);
this.emit('data', body);
})
.catch(this.emit.bind(this, 'error'));
}
setEncoding(enc) {
this._log.trace('Set encoding', enc);
this._encoding = enc;
}
_call(dataStr) {
return got.post(this._hostPort, {
encoding: this._encoding,
headers: {
'Content-Type': 'application/json',
},
body: dataStr,
})
.then((res) => {
return res.body;
});
}
}
module.exports = class Web3HttpSocket extends Web3SocketBase {
/**
* Reset socket.
*/
_resetSocket() {
this._log.debug('Resetting socket');
return Q.try(() => {
if (STATE.CONNECTED === this._state) {
this._log.debug('Disconnecting prior to reset');
return this.disconnect();
}
})
.then(() => {
this._socket = new HttpSocket(this);
this._socket.setEncoding('utf8');
this._socket.on('close', (hadError) => {
// if we did the disconnection then all good
if (STATE.DISCONNECTING === this._state) {
return;
}
this.emit('close', hadError);
});
this._socket.on('data', (data) => {
this._log.trace('Got data');
this.emit('data', data);
});
this._socket.on('error', (err) => {
// connection errors will be handled in connect() code
if (STATE.CONNECTING === this._state) {
return;
}
this._log.error(err);
this.emit('error', err);
});
});
}
};