-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (66 loc) · 1.78 KB
/
index.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
const axios = require('axios')
const crypto = require('crypto')
/**
* BTU Reward Initialization
*
* @param {string} privateKeyString Private key
* @param {string} publicKeyString Public key
* @param {string} url Server url
*/
function BTUSender(privateKeyString, publicKeyString, url) {
this.privateKey = crypto.createPrivateKey(privateKeyString)
this.publicKey = crypto.createPublicKey(publicKeyString)
this.publicKeyString = publicKeyString
this.url = url
this.route = 'sender'
}
/**
* Calculates the signature on some data
*
* @param data The data to calculate the signature on
* @return {string} The calculated signature
*/
BTUSender.prototype._createSignature = function(data) {
const sign = crypto.createSign('SHA256')
sign.write(JSON.stringify(data, Object.keys(data).sort()))
sign.end()
return sign.sign(this.privateKey, 'hex')
}
/**
* Post payload to BTU API
*
* @param {Object} payload
*/
BTUSender.prototype._postRequest = async function(payload) {
const authHeader = ''
const opts = {
method: 'POST',
url: this.url + '/' + this.route,
headers: authHeader,
json: true,
data: payload,
}
try {
const req = await axios.request(opts)
return req.data
} catch (e) {
return (e.response.data)
}
}
/**
* Create a new request
*
* @param {Object} payload
* @return {Object}
*/
BTUSender.prototype.sendRequest = async function (payload) {
// Add timestamp to payload
payload.timestamp = new Date().getTime()
// Calculate signature on payload
payload.signature = this._createSignature(payload)
// Add public key to payload
payload.key = this.publicKeyString
// Post request
return this._postRequest(payload)
}
module.exports = BTUSender