This repository has been archived by the owner on Jun 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
all.integration.js
578 lines (486 loc) · 16.3 KB
/
all.integration.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
'use strict'
const BN = require('bn.js')
const _ = require('lodash')
const compileContracts = require('./helpers/compile-contracts')
const crypto = require('crypto')
const initEventHandlers = require('./helpers/event-handlers')
const jayson = require('jayson/promise')
const log4js = require('log4js')
const makeEthPlatform = require('@appliedblockchain/k0-eth')
const makeK0 = require('@appliedblockchain/k0')
const makePlatformState = require('@appliedblockchain/k0-in-memory-platform-state')
const makeSecretStore = require('@appliedblockchain/k0-in-memory-secret-store')
const makeServerClient = require('@appliedblockchain/k0-server-client')
const sendSignedTransaction = require('./helpers/send-signed-transaction')
const sendTransaction = require('./helpers/send-transaction')
const serverReady = require('./helpers/ready')
const signTransaction = require('./helpers/sign-transaction')
const testUtil = require('./helpers/util')
const u = require('@appliedblockchain/k0-util')
const waitPort = require('wait-port')
const { expect } = require('code')
const assert = require('assert')
const serverEndpoints = [
process.env.ALICE_SERVER_ENDPOINT || 'http://localhost:4000/',
process.env.BOB_SERVER_ENDPOINT || 'http://localhost:4000/',
process.env.CAROL_SERVER_ENDPOINT || 'http://localhost:4000/'
]
const mtserverEndpoints= [
process.env.ALICE_MTSERVER_ENDPOINT || 'http://localhost:4100',
process.env.BOB_MTSERVER_ENDPOINT || 'http://localhost:5100',
process.env.CAROL_MTSERVER_ENDPOINT || 'http://localhost:6100'
]
let web3
describe('Ethereum integration test', function ethIntegrationTest() {
this.timeout(3600 * 1000)
let alice, bob, carol // web3 accounts, and secretKeys
let artefacts
const addresses = {} // contract and user addresses, indexed by name
let dollarCoin, carToken, mvppt, moneyShower
let verifierAddresses
let tokenMaster, carManufacturer
const carId = 1
const numInitialNotes = 2
// close web3 websocket so the test can exit
after(function after() {
if (web3 && web3.currentProvider) {
web3.currentProvider.connection.close()
}
})
// Make the accounts, deploy the contracts
before(async function before() {
const logger = log4js.getLogger()
logger.level = process.env.LOG_LEVEL || 'info'
process.on('unhandledRejection', error => {
logger.error(error)
process.exit(1)
})
web3 = testUtil.initWeb3()
// DollarCoin minter
tokenMaster = web3.eth.accounts.create()
// CarToken minter
carManufacturer = web3.eth.accounts.create()
// contract artefacts
artefacts = await compileContracts()
// ERC-20 payment token
addresses.dollarCoin = await testUtil.deployContract(
web3,
artefacts.DollarCoin,
[],
tokenMaster
)
dollarCoin = new web3.eth.Contract(
artefacts.DollarCoin.abi,
u.buf2hex(addresses.dollarCoin)
)
// ERC-721 token representing cars
addresses.carToken = await testUtil.deployContract(
web3,
artefacts.CarToken,
[],
carManufacturer
)
carToken = new web3.eth.Contract(
artefacts.CarToken.abi,
u.buf2hex(addresses.carToken)
)
verifierAddresses = await Promise.all(
[
'CommitmentVerifier',
'AdditionVerifier',
'TransferVerifier',
'WithdrawalVerifier'
].map(name => testUtil.deployContract(web3, artefacts[name]))
)
verifierAddresses = verifierAddresses.map(u.buf2hex)
;[ alice, bob, carol ] = _.times(3, () => {
const account = web3.eth.accounts.create()
return { account }
})
alice.platformState = await makePlatformState(mtserverEndpoints[0])
bob.platformState = await makePlatformState(mtserverEndpoints[1])
carol.platformState = await makePlatformState(mtserverEndpoints[2])
const helperServer = makeServerClient(serverEndpoints[0])
const initialRoot = await alice.platformState.merkleTreeRoot()
// Deploying coin contract
addresses.mvppt = await testUtil.deployContract(web3, artefacts.MVPPT, [
u.buf2hex(addresses.dollarCoin),
...verifierAddresses,
(await helperServer.pack256Bits(initialRoot)).map(u.bn2string)
])
mvppt = new web3.eth.Contract(
artefacts.CarToken.abi,
addresses.mvppt
)
addresses.moneyShower = await testUtil.deployContract(
web3,
artefacts.MoneyShower
)
moneyShower = new web3.eth.Contract(
artefacts.MoneyShower.abi,
u.buf2hex(addresses.moneyShower)
)
logger.info('Minting DollarCoin...')
await sendTransaction(
web3,
addresses.dollarCoin,
u.hex2buf(dollarCoin.methods
.mint(
tokenMaster.address,
'1000000000000000000000000000000000000000'
)
.encodeABI()),
50000000,
u.hex2buf(tokenMaster.privateKey)
)
await sendTransaction(
web3,
addresses.dollarCoin,
u.hex2buf(
dollarCoin.methods
.approve(
u.buf2hex(addresses.moneyShower),
web3.utils.toWei((numInitialNotes * 3000000).toString())
)
.encodeABI()
),
50000000,
u.hex2buf(tokenMaster.privateKey)
)
logger.info('Transferring DollarCoin to Alice and Bob...')
await sendTransaction(
web3,
addresses.moneyShower,
u.hex2buf(moneyShower.methods.transfer(
u.buf2hex(addresses.dollarCoin),
_.map([ alice, bob ], x => x.account.address),
_.times(2, () => '1000000000000')
).encodeABI()),
5000000,
u.hex2buf(tokenMaster.privateKey)
)
logger.info('Making a car for Carol...')
await sendTransaction(
web3,
addresses.carToken,
u.hex2buf(
carToken.methods.mint(carol.account.address, carId).encodeABI()
),
5000000,
u.hex2buf(carManufacturer.privateKey)
)
addresses.alice = u.hex2buf(alice.account.address)
addresses.bob = u.hex2buf(alice.account.address)
addresses.carol = u.hex2buf(alice.account.address)
alice.k0Eth = await makeEthPlatform(web3, addresses.mvppt, serverEndpoints[0])
bob.k0Eth = await makeEthPlatform(web3, addresses.mvppt, serverEndpoints[1])
carol.k0Eth = await makeEthPlatform(web3, addresses.mvppt, serverEndpoints[2])
alice.secretKey = crypto.randomBytes(32)
bob.secretKey = crypto.randomBytes(32)
carol.secretKey = crypto.randomBytes(32)
alice.k0 = await makeK0(serverEndpoints[0])
bob.k0 = await makeK0(serverEndpoints[1])
carol.k0 = await makeK0(serverEndpoints[2])
while (!(await alice.k0.ready())) {
logger.info('Waiting for the server to become ready.')
await u.wait(1000)
}
async function initSecretStore(agent) {
const { a_pk, sk_enc, pk_enc } =
await agent.k0.deriveKeys(agent.secretKey)
return makeSecretStore(agent.secretKey, a_pk, sk_enc, pk_enc)
}
alice.secretStore = await initSecretStore(alice)
bob.secretStore = await initSecretStore(bob)
carol.secretStore = await initSecretStore(carol)
alice.emitter = initEventHandlers(
alice.platformState,
alice.secretStore,
alice.k0Eth,
alice.k0
)
bob.emitter = initEventHandlers(
bob.platformState,
bob.secretStore,
bob.k0Eth,
bob.k0
)
carol.emitter = initEventHandlers(
carol.platformState,
carol.secretStore,
carol.k0Eth,
carol.k0
)
console.log('Test Suite Initialized.')
})
async function checkRootsConsistency(tries = 10) {
if (tries = 0) {
throw new Error('Roots not equal')
}
const ethRoot = await alice.k0Eth.merkleTreeRoot()
const [ root1, root2, root3 ] = await Promise.all([
alice.platformState.merkleTreeRoot(),
bob.platformState.merkleTreeRoot(),
carol.platformState.merkleTreeRoot()
])
if (!(ethRoot.equals(root1) && ethRoot.equals(root2) && ethRoot.equals(root3))) {
console.log("Roots don't match (yet). Waiting a bit...")
await u.wait(300)
await checkRootsConsistency(tries - 1)
}
}
// Consume $coin in exchange for CMs
async function approveAndDeposit(
user,
values
) {
// aprove an amounts to mvptt
const total = values.reduce((acc, el) => acc.add(el), new BN('0'))
const approveTx = await signTransaction(
web3,
addresses.dollarCoin,
u.hex2buf(
dollarCoin.methods
.approve(u.buf2hex(addresses.mvppt), total.toString())
.encodeABI()
),
5000000,
u.hex2buf(user.account.privateKey)
)
await sendSignedTransaction(web3, approveTx)
for (let i = 0; i < values.length; i++) {
const v = values[i]
const data = await user.k0.prepareDeposit(
user.platformState,
user.secretStore.getAddress(),
v
)
const waitForDeposit = testUtil.awaitEvent(user.emitter, 'depositProcessed')
const depositTx = await user.k0Eth.deposit(
u.hex2buf(user.account.privateKey),
v,
data.k,
data.cm,
data.ciphertext,
data.nextRoot,
data.commitmentProofAffine,
data.additionProofAffine
)
await sendSignedTransaction(web3, depositTx)
await waitForDeposit
}
}
let values
it('Can mint the CMS', async () => {
// DEPOSIT TEST
values = _.times(
numInitialNotes,
() => new BN(_.random(50).toString() + '000')
)
await approveAndDeposit(
alice,
values
)
await checkRootsConsistency()
// check that we have now "numInitialNotes" cm in the merkle tree
expect(await alice.platformState.currentState().cmList.length).to.equal(
numInitialNotes
)
await approveAndDeposit(
bob,
values
)
await checkRootsConsistency()
})
async function getInputNote(platformState, secretStore, index) {
const cm = platformState.cmAtIndex(new BN(index))
const info = secretStore.getNoteInfo(cm)
return {
address: new BN(index),
cm,
...info
}
}
it('allows alice to transfer funds to bob', async () => {
await checkRootsConsistency()
const in0 = await getInputNote(alice.platformState, alice.secretStore, 0)
const in1 = await getInputNote(alice.platformState, alice.secretStore, 1)
const totalValue = in0.v.add(in1.v)
const out0 = {
address: bob.secretStore.getAddress(),
v: totalValue,
rho: crypto.randomBytes(32),
r: crypto.randomBytes(48)
}
const out1 = {
address: alice.secretStore.getAddress(),
v: new BN('0'),
rho: crypto.randomBytes(32),
r: crypto.randomBytes(48)
}
// zero address since we are not trading
const callee = u.hex2buf(u.ZERO_ADDRESS)
const transferData = await alice.k0.prepareTransfer(
alice.platformState,
alice.secretStore,
new BN(0), // cms index
new BN(1),
out0,
out1,
u.hex2buf(u.ZERO_ADDRESS),
callee
)
alice.secretStore.addSNToNote(in0.cm, transferData.input_0_sn)
alice.secretStore.addSNToNote(in1.cm, transferData.input_1_sn)
const rootBefore = await alice.platformState.merkleTreeRoot()
const labelBefore = bob.platformState.currentStateLabel()
const tmpLabel =
'temporary_mt_addition_' + crypto.randomBytes(16).toString('hex')
await alice.platformState.add(
tmpLabel,
[],
[ transferData.output_0_cm, transferData.output_1_cm ]
)
const newRoot = await alice.platformState.merkleTreeRoot()
await alice.platformState.rollbackTo(labelBefore)
const finalRoot = await alice.platformState.merkleTreeRoot()
assert(finalRoot.equals(rootBefore))
const ethParams = [
crypto.randomBytes(32),
transferData.input_0_sn,
transferData.input_1_sn,
transferData.output_0_cm,
transferData.output_1_cm,
transferData.output_0_ciphertext,
transferData.output_1_ciphertext,
newRoot,
callee,
transferData.proofAffine
]
const tx = await alice.k0Eth.transfer(...ethParams)
const avNotesBefore = [alice, bob, carol].map(who => {
return [
who.secretStore.getAPk(),
who.secretStore.getAvailableNotes().length
]
})
const transferProcessed = testUtil.awaitEvent(bob.emitter, 'transferProcessed')
const txHash = await sendSignedTransaction(web3, tx)
const receipt = await web3.eth.getTransactionReceipt(u.buf2hex(txHash))
expect(receipt.status).to.equal(true)
await transferProcessed
const avNotesAfter = [alice, bob, carol].map(who => {
return [
who.secretStore.getAPk(),
who.secretStore.getAvailableNotes().length
]
})
expect(
bob.secretStore.getAvailableNotes().length
).to.equal(numInitialNotes + 1)
})
it('allows carol to sell her car to bob', async () => {
// Deploying The trading contract
const bobNotes = bob.secretStore.getAvailableNotes()
const [ in0, in1 ] = bobNotes
const in0V = bobNotes[0].v
const in1V = bobNotes[1].v
// average between the bigest one and the sum
const carPrice = in0V.gt(in1V) ?
in0V.add(in0V.add(in1V)).div(new BN(2)) :
in1V.add(in1V.add(in0V)).div(new BN(2))
const change = in0V.add(in1V).sub(carPrice)
const { rho, r, cm } = await carol.k0.generatePaymentData(
carol.secretStore,
carPrice
)
const cmPacked = await alice.k0.pack256Bits(cm)
addresses.tradeContract = await testUtil.deployContract(
web3,
artefacts.HiddenPriceCarTrade,
[
u.buf2hex(addresses.carToken),
u.buf2hex(addresses.mvppt),
(new BN(carId)).toString(),
u.buf2hex(cmPacked[0]),
u.buf2hex(cmPacked[1])
],
carol.account
)
const tradeContract = new web3.eth.Contract(
artefacts.HiddenPriceCarTrade.abi,
u.buf2hex(addresses.tradeContract)
)
// Aprove the car to the trading contract
const approvalTxData = carToken.methods.approve(
u.buf2hex(addresses.tradeContract), carId.toString()
).encodeABI()
const txData = await carol.account.signTransaction({
to: carToken.address,
data: approvalTxData,
gas: 1000000
})
await sendSignedTransaction(web3, u.hex2buf(txData.rawTransaction))
const out0 = {
address: carol.secretStore.getAddress(),
v: carPrice,
rho, // Generated payment data in step1
r // Generated payment data in step1
}
const out1 = { // Change back to bob
address: bob.secretStore.getAddress(),
v: change,
rho: crypto.randomBytes(32),
r: crypto.randomBytes(48)
}
const in0Id = bob.platformState.indexOfCM(in0.cm)
const in1Id = bob.platformState.indexOfCM(in1.cm)
// Prepare the transfer
const transferData = await bob.k0.prepareTransfer(
bob.platformState,
bob.secretStore,
in0Id, // cms index in the Merkle Tree
in1Id,
out0,
out1,
addresses.tradeContract
)
// execute the transfer
bob.secretStore.addSNToNote(in0.cm, transferData.input_0_sn)
bob.secretStore.addSNToNote(in1.cm, transferData.input_1_sn)
const rootBefore = await bob.platformState.merkleTreeRoot()
const labelBefore = await bob.platformState.currentStateLabel()
const tmpLabel =
'temporary_mt_addition_' + crypto.randomBytes(16).toString('hex')
await bob.platformState.add(
tmpLabel,
[],
[ transferData.output_0_cm, transferData.output_1_cm ]
)
const newRoot = await bob.platformState.merkleTreeRoot()
await bob.platformState.rollbackTo(labelBefore)
const finalRoot = await bob.platformState.merkleTreeRoot()
assert(finalRoot.equals(rootBefore))
const ethParams = [
u.hex2buf(bob.account.privateKey),
transferData.input_0_sn,
transferData.input_1_sn,
transferData.output_0_cm,
transferData.output_1_cm,
transferData.output_0_ciphertext,
transferData.output_1_ciphertext,
newRoot,
addresses.tradeContract,
transferData.proofAffine
]
const tx = await bob.k0Eth.transfer(...ethParams)
const transferProcessed = testUtil.awaitEvent(bob.emitter, 'transferProcessed')
const txHash = await sendSignedTransaction(web3, tx)
const receipt = await web3.eth.getTransactionReceipt(u.buf2hex(txHash))
expect(receipt.status).to.equal(true)
await transferProcessed
// Test that the ownership got transfered
const carOwner = await carToken.methods.ownerOf(carId).call()
expect(carOwner).to.equal(bob.account.address)
})
})