forked from BlueWallet/BlueWallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtorrific.js
290 lines (251 loc) · 8.37 KB
/
torrific.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
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
import Tor from 'react-native-tor';
const tor = Tor({
bootstrapTimeoutMs: 35000,
numberConcurrentRequests: 1,
});
/**
* TOR wrapper mimicking Frisbee interface
*/
class Torsbee {
baseURI = '';
static _testConn;
static _resolveReference;
static _rejectReference;
constructor(opts) {
opts = opts || {};
this.baseURI = opts.baseURI || this.baseURI;
}
async get(path, options) {
console.log('TOR: starting...');
const socksProxy = await tor.startIfNotStarted();
console.log('TOR: started', await tor.getDaemonStatus(), 'on local port', socksProxy);
if (path.startsWith('/') && this.baseURI.endsWith('/')) {
// oy vey, duplicate slashes
path = path.substr(1);
}
const response = {};
try {
const uri = this.baseURI + path;
console.log('TOR: requesting', uri);
const torResponse = await tor.get(uri, options?.headers || {}, true);
response.originalResponse = torResponse;
if (options?.headers['Content-Type'] === 'application/json' && torResponse.json) {
response.body = torResponse.json;
} else {
response.body = Buffer.from(torResponse.b64Data, 'base64').toString();
}
} catch (error) {
response.err = error;
console.warn(error);
}
return response;
}
async post(path, options) {
console.log('TOR: starting...');
const socksProxy = await tor.startIfNotStarted();
console.log('TOR: started', await tor.getDaemonStatus(), 'on local port', socksProxy);
if (path.startsWith('/') && this.baseURI.endsWith('/')) {
// oy vey, duplicate slashes
path = path.substr(1);
}
const uri = this.baseURI + path;
console.log('TOR: posting to', uri);
const response = {};
try {
const torResponse = await tor.post(uri, JSON.stringify(options?.body || {}), options?.headers || {}, true);
response.originalResponse = torResponse;
if (options?.headers['Content-Type'] === 'application/json' && torResponse.json) {
response.body = torResponse.json;
} else {
response.body = Buffer.from(torResponse.b64Data, 'base64').toString();
}
} catch (error) {
response.err = error;
console.warn(error);
}
return response;
}
testSocket() {
return new Promise((resolve, reject) => {
this.constructor._resolveReference = resolve;
this.constructor._rejectReference = reject;
(async () => {
console.log('testSocket...');
try {
if (!this.constructor._testConn) {
// no test conenctino exists, creating it...
await tor.startIfNotStarted();
const target = 'explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion:110';
this.constructor._testConn = await tor.createTcpConnection({ target }, (data, err) => {
if (err) {
return this.constructor._rejectReference(new Error(err));
}
const json = JSON.parse(data);
if (!json || typeof json.result === 'undefined')
return this.constructor._rejectReference(new Error('Unexpected response from TOR socket: ' + JSON.stringify(json)));
// conn.close();
// instead of closing connect, we will actualy re-cyce existing test connection as we
// saved it into `this.constructor.testConn`
this.constructor._resolveReference();
});
await this.constructor._testConn.write(
`{ "id": 1, "method": "blockchain.scripthash.get_balance", "params": ["716decbe1660861c3d93906cb1d98ee68b154fd4d23aed9783859c1271b52a9c"] }\n`,
);
} else {
// test connectino exists, so we are reusing it
await this.constructor._testConn.write(
`{ "id": 1, "method": "blockchain.scripthash.get_balance", "params": ["716decbe1660861c3d93906cb1d98ee68b154fd4d23aed9783859c1271b52a9c"] }\n`,
);
}
} catch (error) {
this.constructor._rejectReference(error);
}
})();
});
}
}
/**
* Wrapper for react-native-tor mimicking Socket class from NET package
*/
class TorSocket {
constructor() {
this._socket = false;
this._listeners = {};
}
setTimeout() {}
setEncoding() {}
setKeepAlive() {}
setNoDelay() {}
on(event, listener) {
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
}
removeListener(event, listener) {
this._listeners[event] = this._listeners[event] || [];
const newListeners = [];
let found = false;
for (const savedListener of this._listeners[event]) {
// eslint-disable-next-line eqeqeq
if (savedListener == listener) {
// found our listener
found = true;
// we just skip it
} else {
// other listeners should go back to original array
newListeners.push(savedListener);
}
}
if (found) {
this._listeners[event] = newListeners;
} else {
// something went wrong, lets just cleanup all listeners
this._listeners[event] = [];
}
}
connect(port, host, callback) {
console.log('connecting TOR socket...', host, port);
(async () => {
console.log('starting tor...');
try {
await tor.startIfNotStarted();
} catch (e) {
console.warn('Could not bootstrap TOR', e);
await tor.stopIfRunning();
this._passOnEvent('error', 'Could not bootstrap TOR');
return false;
}
console.log('started tor');
const iWillConnectISwear = tor.createTcpConnection({ target: host + ':' + port, connectionTimeout: 15000 }, (data, err) => {
if (err) {
console.log('TOR socket onData error: ', err);
// this._passOnEvent('error', err);
return;
}
this._passOnEvent('data', data);
});
try {
this._socket = await Promise.race([iWillConnectISwear, new Promise(resolve => setTimeout(resolve, 21000))]);
} catch (e) {}
if (!this._socket) {
console.log('connecting TOR socket failed'); // either sleep expired or connect threw an exception
await tor.stopIfRunning();
this._passOnEvent('error', 'connecting TOR socket failed');
return false;
}
console.log('TOR socket connected:', host, port);
setTimeout(() => {
this._passOnEvent('connect', true);
callback();
}, 1000);
})();
}
_passOnEvent(event, data) {
this._listeners[event] = this._listeners[event] || [];
for (const savedListener of this._listeners[event]) {
savedListener(data);
}
}
emit(event, data) {}
end() {
console.log('trying to close TOR socket');
if (this._socket && this._socket.close) {
console.log('trying to close TOR socket SUCCESS');
return this._socket.close();
}
}
destroy() {}
write(data) {
if (this._socket && this._socket.write) {
try {
return this._socket.write(data);
} catch (error) {
console.log('this._socket.write() failed so we are issuing ERROR event', error);
this._passOnEvent('error', error);
}
} else {
console.log('TOR socket write error, socket not connected');
this._passOnEvent('error', 'TOR socket not connected');
}
}
}
module.exports.getDaemonStatus = async () => {
try {
return await tor.getDaemonStatus();
} catch (_) {
return false;
}
};
module.exports.stopIfRunning = async () => {
try {
Torsbee._testConn = false;
return await tor.stopIfRunning();
} catch (_) {
return false;
}
};
module.exports.startIfNotStarted = async () => {
try {
return await tor.startIfNotStarted();
} catch (_) {
return false;
}
};
module.exports.testSocket = async () => {
const c = new Torsbee();
return c.testSocket();
};
module.exports.testHttp = async () => {
const api = new Torsbee({
baseURI: 'http://explorerzydxu5ecjrkwceayqybizmpjjznk5izmitf2modhcusuqlid.onion:80/',
});
const torResponse = await api.get('/api/tx/a84dbcf0d2550f673dda9331eea7cab86b645fd6e12049755c4b47bd238adce9', {
headers: {
'Content-Type': 'application/json',
},
});
const json = torResponse.body;
if (json.txid !== 'a84dbcf0d2550f673dda9331eea7cab86b645fd6e12049755c4b47bd238adce9')
throw new Error('TOR failure, got ' + JSON.stringify(torResponse));
};
module.exports.Torsbee = Torsbee;
module.exports.Socket = TorSocket;