Skip to content

Commit

Permalink
test: fix or update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
IlyasRidhuan committed Nov 19, 2021
1 parent 7d4e8ed commit 14622af
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 71 deletions.
56 changes: 26 additions & 30 deletions test/e2e/nightfall-sdk.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,9 @@ describe('Testing the Nightfall SDK', () => {

it('should get the address of the test ERC contract stub', async function () {
const res = await nf3User1.getContractAddress('ERCStub');
ercAddress = res;
// Lowercase is useful here because BigInt(ercAddress).toString(16) applies a lowercase check
// we will use this as a key in our dictionary so it's important they match.
ercAddress = res.toLowerCase();
expect(res).to.be.a('string').and.to.include('0x');
});

Expand Down Expand Up @@ -273,8 +275,7 @@ describe('Testing the Nightfall SDK', () => {
describe('Balance tests', () => {
it('should increment the balance after deposit some crypto', async function () {
let balances = await nf3User1.getLayer2Balances();
const currentPkdBalance =
balances[nf3User1.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)];
const currentPkdBalance = balances[nf3User1.zkpKeys.compressedPkd][ercAddress];
// We do 2 deposits of 10 each
for (let i = 0; i < txPerBlock; i++) {
// eslint-disable-next-line no-await-in-loop
Expand All @@ -289,8 +290,7 @@ describe('Testing the Nightfall SDK', () => {
}
eventLogs.shift();
balances = await nf3User1.getLayer2Balances();
const afterPkdBalance =
balances[nf3User1.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)];
const afterPkdBalance = balances[nf3User1.zkpKeys.compressedPkd][ercAddress];
expect(afterPkdBalance - currentPkdBalance).to.be.equal(txPerBlock * value);
});

Expand All @@ -309,9 +309,8 @@ describe('Testing the Nightfall SDK', () => {
eventLogs.shift();

let balances = await nf3User1.getLayer2Balances();
const currentPkdBalancePkd =
balances[nf3User1.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)];
const currentPkdBalancePkd2 = 0; // balances[compressedPkd2][BigInt(ercAddress).toString(16)];
const currentPkdBalancePkd = balances[nf3User1.zkpKeys.compressedPkd][ercAddress];
const currentPkdBalancePkd2 = 0; // balances[compressedPkd2][ercAddress];
for (let i = 0; i < txPerBlock; i++) {
// eslint-disable-next-line no-await-in-loop
res = await nf3User1.transfer(
Expand All @@ -333,10 +332,8 @@ describe('Testing the Nightfall SDK', () => {
}
eventLogs.shift();
balances = await nf3User1.getLayer2Balances();
const afterPkdBalancePkd =
balances[nf3User1.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)];
const afterPkdBalancePkd2 =
balances[nf3User2.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)];
const afterPkdBalancePkd = balances[nf3User1.zkpKeys.compressedPkd][ercAddress];
const afterPkdBalancePkd2 = balances[nf3User2.zkpKeys.compressedPkd][ercAddress];
expect(afterPkdBalancePkd - currentPkdBalancePkd).to.be.equal(-txPerBlock * value);
expect(afterPkdBalancePkd2 - currentPkdBalancePkd2).to.be.equal(txPerBlock * value);
});
Expand All @@ -345,9 +342,7 @@ describe('Testing the Nightfall SDK', () => {
describe('Get commitments tests', () => {
it('should get current commitments for the account', async function () {
const commitments = await nf3User1.getLayer2Commitments();
expect(commitments[nf3User1.zkpKeys.compressedPkd]).to.have.property(
BigInt(ercAddress).toString(16),
);
expect(commitments[nf3User1.zkpKeys.compressedPkd]).to.have.property(ercAddress);
});
});

Expand Down Expand Up @@ -458,6 +453,7 @@ describe('Testing the Nightfall SDK', () => {
eventLogs.shift();

let latestWithdrawTransactionHash = ''; // for instant withdrawals
console.log(`instant withdrawal call`);
await nf3User1.withdraw(
false,
ercAddress,
Expand All @@ -468,6 +464,7 @@ describe('Testing the Nightfall SDK', () => {
fee,
);
latestWithdrawTransactionHash = nf3User1.getLatestWithdrawHash();
console.log(`ilatestWithdrawTransactionHash: ${latestWithdrawTransactionHash}`);
expect(latestWithdrawTransactionHash).to.be.a('string').and.to.include('0x');

if (eventLogs[0] !== 'blockProposed') {
Expand Down Expand Up @@ -548,13 +545,11 @@ describe('Testing the Nightfall SDK', () => {
describe('Get pending withdraw commitments tests', () => {
it('should get current pending withdraw commitments for the account (with 0 valid commitments)', async function () {
const commitments = await nf3User1.getPendingWithdraws();
console.log(`commitments: ${JSON.stringify(commitments)}`);
expect(commitments[nf3User1.zkpKeys.compressedPkd][ercAddress].length).to.be.greaterThan(0);
expect(
commitments[nf3User1.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)].length,
).to.be.greaterThan(0);
expect(
commitments[nf3User1.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)].filter(
c => c.valid === true,
).length,
commitments[nf3User1.zkpKeys.compressedPkd][ercAddress].filter(c => c.valid === true)
.length,
).to.be.equal(0);
});
});
Expand Down Expand Up @@ -582,23 +577,24 @@ describe('Testing the Nightfall SDK', () => {
let endBalance;

it('should get a valid withdraw commitment with a time-jump capable test client (because sufficient time has passed)', async function () {
if (nodeInfo.includes('TestRPC')) await timeJump(3600 * 24 * 10); // jump in time by 10 days
if (nodeInfo.includes('TestRPC')) await timeJump(3600 * 24 * 10); // jump in time by 50 days
console.log(`timeJump`);
for (let i = 0; i < txPerBlock; i++) {
// eslint-disable-next-line no-await-in-loop
await nf3User1.deposit(ercAddress, tokenType, value, tokenId, fee);
}
const commitments = await nf3User1.getPendingWithdraws();
expect(commitments[nf3User1.zkpKeys.compressedPkd][ercAddress].length).to.be.greaterThan(0);
expect(
commitments[nf3User1.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)].length,
).to.be.greaterThan(0);
expect(
commitments[nf3User1.zkpKeys.compressedPkd][BigInt(ercAddress).toString(16)].filter(
c => c.valid === true,
).length,
commitments[nf3User1.zkpKeys.compressedPkd][ercAddress].filter(c => c.valid === true)
.length,
).to.be.greaterThan(0);
});

it('should create a passing finalise-withdrawal with a time-jump capable test client (because sufficient time has passed)', async function () {
if (nodeInfo.includes('TestRPC')) await timeJump(3600 * 24 * 10); // jump in time by 10 days
startBalance = await getBalance(nf3User1.ethereumAddress);
// now we need to sign the transaction and send it to the blockchain
// this will only work if we're using Ganache, otherwiise expect failure
startBalance = await getBalance(nf3User1.ethereumAddress);
if (nodeInfo.includes('TestRPC')) {
const res = await nf3User1.finaliseWithdrawal(transactions[0]);
expect(res).to.have.property('transactionHash');
Expand Down
8 changes: 2 additions & 6 deletions test/http.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -638,9 +638,7 @@ describe('Testing the http API', () => {
let endBalance;
it('Should create a failing finalise-withdrawal (because insufficient time has passed)', async function () {
const res = await chai.request(senderUrl).post('/finalise-withdrawal').send({
block, // block containing the withdraw transaction
transactions, // transactions in the withdraw block
index, // index of the withdraw transaction in the transactions
transactionHash: transactions[index].transactionHash,
});
txDataToSign = res.body.txDataToSign;
expect(txDataToSign).to.be.a('string');
Expand All @@ -656,9 +654,7 @@ describe('Testing the http API', () => {
it('Should create a passing finalise-withdrawal with a time-jump capable test client (because sufficient time has passed)', async function () {
if (nodeInfo.includes('TestRPC')) await timeJump(3600 * 24 * 10); // jump in time by 10 days
const res = await chai.request(senderUrl).post('/finalise-withdrawal').send({
block,
transactions,
index,
transactionHash: transactions[index].transactionHash,
});
txDataToSign = res.body.txDataToSign;
expect(txDataToSign).to.be.a('string');
Expand Down
86 changes: 51 additions & 35 deletions test/instant-withdrawal.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import chai from 'chai';
import chaiHttp from 'chai-http';
import chaiAsPromised from 'chai-as-promised';
import WebSocket from 'ws';
import { generateMnemonic } from 'bip39';
import {
closeWeb3Connection,
submitTransaction,
Expand All @@ -25,8 +26,7 @@ describe('Test instant withdrawals', () => {
let withdrawTransaction;
let connection; // WS connection
let nodeInfo;
const zkpPrivateKey = '0xc05b14fa15148330c6d008814b0bdd69bc4a08a1bd0b629c42fa7e2c61f16739'; // the zkp private key we're going to use in the tests.
const url = 'http://localhost:8080';
const senderUrl = 'http://localhost:8080';
const optimistUrl = 'http://localhost:8081';
const optimistWsUrl = 'ws:localhost:8082';
const tokenId = '0x00';
Expand All @@ -43,17 +43,22 @@ describe('Test instant withdrawals', () => {
const BLOCK_STAKE = 1000000000000000000; // 1 ether
const txPerBlock = 2;
const eventLogs = [];
let ask1;
let nsk1;
let ivk1;
let pkd1;

before(async function () {
const web3 = await connectWeb3();

shieldAddress = (await chai.request(url).get('/contract-address/Shield')).body.address;
shieldAddress = (await chai.request(senderUrl).get('/contract-address/Shield')).body.address;

stateAddress = (await chai.request(url).get('/contract-address/State')).body.address;
stateAddress = (await chai.request(senderUrl).get('/contract-address/State')).body.address;

proposersAddress = (await chai.request(url).get('/contract-address/Proposers')).body.address;
proposersAddress = (await chai.request(senderUrl).get('/contract-address/Proposers')).body
.address;

ercAddress = (await chai.request(url).get('/contract-address/ERCStub')).body.address;
ercAddress = (await chai.request(senderUrl).get('/contract-address/ERCStub')).body.address;

nodeInfo = await web3.eth.getNodeInfo();

Expand All @@ -63,6 +68,32 @@ describe('Test instant withdrawals', () => {
// For event tracking, we use only care about the logs related to 'blockProposed'
if (log.topics[0] === topicEventMapping.BlockProposed) eventLogs.push('blockProposed');
});

// Generate a random mnemonic (uses crypto.randomBytes under the hood), defaults to 128-bits of entropy
// For entropy, crypto.randomBytes uses /dev/urandom (unix, MacOS) or CryptoGenRandom (windows)
// Crypto.getRandomValues() is suitable for browser needs
const mnemonic = generateMnemonic();

({
ask: ask1,
nsk: nsk1,
ivk: ivk1,
pkd: pkd1,
} = (
await chai
.request(senderUrl)
.post('/generate-keys')
.send({ mnemonic, path: `m/44'/60'/0'/0` })
).body);

await chai
.request(senderUrl)
.post('/incoming-viewing-key')
.send({
ivks: [ivk1],
nsks: [nsk1],
});

const myAddress = (await getAccounts())[0];
// register a proposer d
const res = await chai
Expand All @@ -85,18 +116,16 @@ describe('Test instant withdrawals', () => {
};
});

describe('', () => {
let block;
let transactions;
let index;
describe('Test Instant Withdrawal', () => {
let withdrawTransactionHash;
before(async () => {
const depositTransactions = (
await Promise.all(
Array.from({ length: txPerBlock * 2 - 1 }, () =>
chai
.request(url)
.request(senderUrl)
.post('/deposit')
.send({ ercAddress, tokenId, tokenType, value, zkpPrivateKey, fee }),
.send({ ercAddress, tokenId, tokenType, value, pkd: pkd1, nsk: nsk1, fee }),
),
)
).map(res => res.body);
Expand All @@ -109,16 +138,18 @@ describe('Test instant withdrawals', () => {
// eslint-disable-next-line no-await-in-loop
await new Promise(resolve => setTimeout(resolve, 3000));
}
await new Promise(resolve => setTimeout(resolve, 3000));
});

it('should trigger a withdraw', async () => {
const res = await chai.request(url).post('/withdraw').send({
const res = await chai.request(senderUrl).post('/withdraw').send({
ercAddress,
tokenId,
tokenType,
value,
senderZkpPrivateKey: zkpPrivateKey,
recipientAddress,
nsk: nsk1,
ask: ask1,
});
withdrawTransaction = res.body.transaction;
const receipt = await submitTransaction(
Expand All @@ -127,36 +158,24 @@ describe('Test instant withdrawals', () => {
shieldAddress,
gas,
);
withdrawTransactionHash = withdrawTransaction.transactionHash;
expect(receipt).to.have.property('transactionHash');
expect(receipt).to.have.property('blockHash');
while (eventLogs.length !== 2) {
// eslint-disable-next-line no-await-in-loop
await new Promise(resolve => setTimeout(resolve, 3000));
}
});

it('Should find the block containing the withdraw transaction', async () => {
do {
// eslint-disable-next-line no-await-in-loop
const res = await chai
.request(optimistUrl)
.get(`/block/transaction-hash/${withdrawTransaction.transactionHash}`);
({ block, transactions, index } = res.body);
// eslint-disable-next-line no-await-in-loop
await new Promise(resolve => setTimeout(resolve, 3000));
} while (block === null);
expect(block).not.to.be.undefined; // eslint-disable-line
expect(Object.entries(block).length).not.to.equal(0); // empty object {}
await new Promise(resolve => setTimeout(resolve, 3000));
});

it('should setAdvanceWithdrawalFee', async () => {
const startAccount1Balance = await getBalance((await getAccounts())[0]);
// const account2Balance = await getBalance((await getAccounts())[1]);

const res = await chai
.request(url)
.request(senderUrl)
.post('/set-instant-withdrawal')
.send({ block, transactions, index });
.send({ transactionHash: withdrawTransactionHash });
const { txDataToSign } = res.body;
expect(txDataToSign).to.be.a('string');
const receipt = await submitTransaction(
Expand All @@ -176,7 +195,6 @@ describe('Test instant withdrawals', () => {
});

it('should advance the withdrawal', async () => {
const withdrawTransactionHash = withdrawTransaction.transactionHash;
const res = await chai
.request(optimistUrl)
.post('/transaction/advanceWithdrawal')
Expand All @@ -191,10 +209,8 @@ describe('Test instant withdrawals', () => {
// jump in time by 10 days
if (nodeInfo.includes('TestRPC')) await timeJump(3600 * 24 * 10);
else this.skip();
const res = await chai.request(url).post('/finalise-withdrawal').send({
block,
transactions,
index,
const res = await chai.request(senderUrl).post('/finalise-withdrawal').send({
transactionHash: withdrawTransactionHash,
});
const { txDataToSign } = res.body;
expect(txDataToSign).to.be.a('string');
Expand Down

0 comments on commit 14622af

Please sign in to comment.