-
Notifications
You must be signed in to change notification settings - Fork 1
/
aws-http-provider.js
68 lines (60 loc) · 2.44 KB
/
aws-http-provider.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
/////////////////////////////////////////////////////
// Authored by Carl Youngblood
// Senior Blockchain Solutions Architect, AWS
// Adapted from web3 npm package v1.3.0
// licensed under GNU Lesser General Public License
// https://github.com/ethereum/web3.js
/////////////////////////////////////////////////////
import AWS from 'aws-sdk';
import HttpProvider from 'web3-providers-http';
import XHR2 from 'xhr2';
export default class AWSHttpProvider extends HttpProvider {
send(payload, callback) {
const self = this;
const request = new XHR2(); // eslint-disable-line
request.timeout = self.timeout;
request.open('POST', self.host, true);
request.setRequestHeader('Content-Type', 'application/json');
request.onreadystatechange = () => {
if (request.readyState === 4 && request.timeout !== 1) {
let result = request.responseText; // eslint-disable-line
let error = null; // eslint-disable-line
try {
result = JSON.parse(result);
} catch (jsonError) {
let message;
if (!!result && !!result.error && !!result.error.message) {
message = `[aws-ethjs-provider-http] ${result.error.message}`;
} else {
message = `[aws-ethjs-provider-http] Invalid JSON RPC response from host provider ${self.host}: ` +
`${JSON.stringify(result, null, 2)}`;
}
error = new Error(message);
}
callback(error, result);
}
};
request.ontimeout = () => {
callback(`[aws-ethjs-provider-http] CONNECTION TIMEOUT: http request timeout after ${self.timeout} ` +
`ms. (i.e. your connect has timed out for whatever reason, check your provider).`, null);
};
try {
const strPayload = JSON.stringify(payload);
const region = process.env.AWS_DEFAULT_REGION || 'us-east-1';
const credentials = new AWS.EnvironmentCredentials('AWS');
const endpoint = new AWS.Endpoint(self.host);
const req = new AWS.HttpRequest(endpoint, region);
req.method = request._method;
req.body = strPayload;
req.headers['host'] = request._url.host;
const signer = new AWS.Signers.V4(req, 'managedblockchain');
signer.addAuthorization(credentials, new Date());
request.setRequestHeader('Authorization', req.headers['Authorization']);
request.setRequestHeader('X-Amz-Date', req.headers['X-Amz-Date']);
request.send(strPayload);
} catch (error) {
callback(`[aws-ethjs-provider-http] CONNECTION ERROR: Couldn't connect to node '${self.host}': ` +
`${JSON.stringify(error, null, 2)}`, null);
}
}
}