-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapp.js
257 lines (226 loc) · 5.94 KB
/
app.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
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-console */
const Web3 = require('web3');
const HDWalletProvider = require('truffle-hdwallet-provider');
const createDrizzleUtils = require('@drizzle-utils/core');
const heiswapArtifact = require('./contracts/Heiswap.json');
// REST API
const express = require('express');
const cors = require('cors');
const asyncHandler = require('express-async-handler');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
// ECC
const BN = require('bn.js');
const { strTo64BN, bn128 } = require('./utils/AltBn128.js');
const bnZero = new BN('0', 10);
// Check Environment variables
let hasEnv = true;
if (process.env.INFURA_PROJECT_ID === undefined) {
hasEnv = false;
console.log('Missing Env variable: INFURA_PROJECT_ID');
}
if (process.env.ETH_SK === undefined) {
hasEnv = false;
console.log('Missing Env variable: ETH_SK');
}
if (hasEnv === false) {
process.exit(1);
}
// Get web3
const customProvider = new HDWalletProvider(
[process.env.ETH_SK],
`https://ropsten.infura.io/v3/${process.env.INFURA_PROJECT_ID}`
);
const web3 = new Web3(customProvider);
// Middlewares
app.use(bodyParser.json());
app.use(cors());
// Relayer logic
app.post('/', asyncHandler(async (req, res) => {
// Set timeout (10 mins max)
req.setTimeout(600000);
const postParams = req.body;
// Debug
console.log(`Request received: ${JSON.stringify(postParams)}`);
// Extract out post params
const {
message, signedMessage, receiver, ethAmount, ringIdx, c0, keyImage, s
} = postParams;
if (
message === undefined
|| signedMessage === undefined
|| receiver === undefined
|| ethAmount === undefined
|| ringIdx === undefined
|| c0 === undefined
|| keyImage === undefined
|| s === undefined
) {
res
.status(400)
.send({
errorMessage: 'Invalid payload',
txHash: null
});
return;
}
const accounts = await web3.eth.getAccounts();
const sender = accounts[0];
const drizzleUtils = await createDrizzleUtils({ web3 });
const heiswapInstance = await drizzleUtils.getContractInstance({ artifact: heiswapArtifact });
// Make sure sender authorized this tx
const signatureAddress = await web3.eth.personal.ecRecover(message, signedMessage);
if (
signatureAddress.toLowerCase() !== receiver.toLowerCase()
|| message.toLowerCase().indexOf(receiver.toLowerCase()) === -1
) {
res
.status(400)
.send({
errorMessage: 'Invalid Message Signature',
txHash: null
});
return;
}
// Verify signature before sending it of to the EVM
// (saves GAS if invalid tx that way)
// Checks if ring is closed
const ringHash = await heiswapInstance
.methods
.getRingHash(ethAmount, ringIdx)
.call();
const ringHashBuf = Buffer.from(
ringHash.slice(2), // Remove the '0x'
'hex'
);
const ethAddressBuf = Buffer.from(
receiver.slice(2), // Remove the '0x'
'hex'
);
const msgBuf = Buffer.concat([
ringHashBuf,
ethAddressBuf
]);
const publicKeys = await heiswapInstance
.methods
.getPublicKeys(ethAmount, ringIdx)
.call();
const publicKeysBN = publicKeys
.map(x => {
return [
// Slice the '0x'
new BN(Buffer.from(x[0].slice(2), 'hex')),
new BN(Buffer.from(x[1].slice(2), 'hex'))
];
})
.filter(x => x[0].cmp(bnZero) !== 0 && x[1].cmp(bnZero) !== 0);
const ringSignature = [
strTo64BN(c0),
s.map(x => strTo64BN(x)),
[
strTo64BN(keyImage[0]),
strTo64BN(keyImage[1])
]
];
const validRingSig = bn128.ringVerify(
msgBuf,
publicKeysBN,
ringSignature
);
if (!validRingSig) {
console.log(`Invalid Ring Signature: ${JSON.stringify(postParams)}`);
res
.status(400)
.send({
errorMessage: 'Invalid Ring Signature',
txHash: null
});
return;
}
// Convert to bytecode to estimate GAS
let dataBytecode;
try {
dataBytecode = heiswapInstance
.methods
.withdraw(
receiver,
ethAmount,
ringIdx,
c0,
keyImage,
s
).encodeABI();
} catch (e) {
console.log(`Invalid payload: ${JSON.stringify(postParams)}`);
res
.status(400)
.send({
errorMessage: 'Payload invalid format',
txHash: null
});
return;
}
// Passes in-built checks, time to estimate GAS
let gas;
try {
// If estimating the gas throws an error
// then likely invalid params (i.e. ringIdx is closed or user deposited or keys not valid)
gas = await web3.eth.estimateGas({
to: heiswapInstance._address,
data: dataBytecode
});
} catch (e) {
console.log(`EVM revert: ${JSON.stringify(postParams)}`);
res.status(400)
.send({
errorMessage: 'EVM revert on GAS estimation (likely invalid input params).',
txHash: null
});
return;
}
const tx = {
from: sender,
to: heiswapInstance._address,
gas,
data: dataBytecode,
nonce: await web3.eth.getTransactionCount(sender)
};
// txR has response type of
/**
* { blockHash: string,
* blockNumber: number,
* contractAddress: Maybe string,
* cumulativeGasUsed: 1325121,
* from: string,
* gasUsed: number,
* logs: [events],
* logsBloom: string,
* status: boolean,
* to: string,
* transactionHash: string,
* transactionIndex: number }
*/
// Try and send transaction
console.log('Sending tx...');
try {
const txR = await web3.eth.sendTransaction(tx);
res
.status(200)
.send({
txHash: txR.transactionHash
});
} catch (e) {
const txR = JSON.parse(e.message.split(':').slice(1).join(':'));
res
.status(200)
.send({
errorMessage: e.message.split(':').slice(0, 1),
txHash: txR.transactionHash
});
}
console.log('Tx sent...');
}));
console.log(`Listening on port ${port}`);
app.listen(port, '0.0.0.0');