Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix proof caching to speed up tests (#15) #17

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions lib/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const {
const { Scalar, ZqField } = require("ffjavascript");
const { TransactionKeeper } = require('./transactionKeeper.js');
const { SelfGriefingError, AmountMismatchError } = require('./utils.js');
const { ProofCache } = require('./proofCache.js');

// Initialize ZqField for MiMC Sponge
const F = new ZqField(
Expand Down Expand Up @@ -40,6 +41,7 @@ class NodeResult {
class Node {
constructor() {
this.getSender = async function() { return 0x0; };
this.proofCache = new ProofCache();
}

async initialize(getLatestLeaves, getSender) {
Expand All @@ -64,26 +66,57 @@ class Node {

// create an insert commitment with fake root containing just the commitment
async lock(asset, amount, salt) {
const inputs = {
type: 'lock',
asset,
amount,
salt
};

// Try to get cached proof
const cachedProof = this.proofCache.getProof(inputs);
if (cachedProof) {
return cachedProof;
}

// sanity check
if (amount > 0 && salt == 0) {
throw new SelfGriefingError('disallowing self-griefing by using 0 salt with a non-zero amount', { asset, amount, salt });
}

const { commitment, proof } = await this.transactionKeeper.insert(asset, amount, salt);
return new NodeResult({
const result = new NodeResult({
asset,
amount,
commitment: ethers.BigNumber.from(this._commitmentHash(commitment)),
proof
}, {
inserted: [commitment]
});

// Cache the proof
this.proofCache.saveProof(inputs, result);

return result;
}

// unlock a commitment
async unlock(amount, remainderSalt, inputCommitments) {
const inputs = {
type: 'unlock',
amount,
remainderSalt,
inputCommitments
};

// Try to get cached proof
const cachedProof = this.proofCache.getProof(inputs);
if (cachedProof) {
return cachedProof;
}

const { asset, remainderCommitment, nullifiedCommitments, proof } = await this.transactionKeeper.drop(amount, remainderSalt, inputCommitments);
return new NodeResult({
const result = new NodeResult({
asset,
amount,
remainderCommitment: ethers.BigNumber.from(this._commitmentHash(remainderCommitment)),
Expand All @@ -93,6 +126,11 @@ class Node {
inserted: [remainderCommitment],
nullified: nullifiedCommitments
});

// Cache the proof
this.proofCache.saveProof(inputs, result);

return result;
}

// bridge a commitment
Expand Down
68 changes: 68 additions & 0 deletions lib/proofCache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

class ProofCache {
constructor(cacheDir = 'cache') {
this.cacheDir = cacheDir;
// Create cache directory if it doesn't exist
if (!fs.existsSync(cacheDir)) {
fs.mkdirSync(cacheDir, { recursive: true });
}
}

// Generate a unique cache key based on proof inputs
generateCacheKey(inputs) {
const inputString = JSON.stringify(inputs, Object.keys(inputs).sort());
return crypto.createHash('sha256').update(inputString).digest('hex');
}

// Try to get cached proof
getProof(inputs) {
const cacheKey = this.generateCacheKey(inputs);
const cachePath = path.join(this.cacheDir, `${cacheKey}.json`);

if (fs.existsSync(cachePath)) {
try {
const cachedData = fs.readFileSync(cachePath, 'utf8');
return JSON.parse(cachedData);
} catch (error) {
console.warn(`Failed to read cache file: ${error.message}`);
return null;
}
}
return null;
}

// Save proof to cache
saveProof(inputs, proof) {
const cacheKey = this.generateCacheKey(inputs);
const cachePath = path.join(this.cacheDir, `${cacheKey}.json`);

try {
fs.writeFileSync(cachePath, JSON.stringify(proof, null, 2));
return true;
} catch (error) {
console.warn(`Failed to write cache file: ${error.message}`);
return false;
}
}

// Clear all cached proofs
clearCache() {
try {
const files = fs.readdirSync(this.cacheDir);
for (const file of files) {
if (file.endsWith('.json')) {
fs.unlinkSync(path.join(this.cacheDir, file));
}
}
return true;
} catch (error) {
console.warn(`Failed to clear cache: ${error.message}`);
return false;
}
}
}

module.exports = { ProofCache };
72 changes: 72 additions & 0 deletions test/unit/cache-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
const { expect } = require("chai");
const { ProofCache } = require('../../lib/proofCache.js');
const fs = require('fs');
const path = require('path');

describe("Proof Cache Tests", function () {
let proofCache;
const testCacheDir = 'test-cache';

beforeEach(() => {
// Create a fresh cache instance for each test
proofCache = new ProofCache(testCacheDir);
});

afterEach(() => {
// Clean up test cache directory after each test
if (fs.existsSync(testCacheDir)) {
fs.rmSync(testCacheDir, { recursive: true });
}
});

it("should generate consistent cache keys", () => {
const inputs1 = { a: 1, b: 2, c: 3 };
const inputs2 = { c: 3, b: 2, a: 1 };
const key1 = proofCache.generateCacheKey(inputs1);
const key2 = proofCache.generateCacheKey(inputs2);

// Same inputs in different order should generate same key
expect(key1).to.equal(key2);
});

it("should save and retrieve proofs", () => {
const inputs = { amount: 100, salt: "0x123" };
const proof = {
result: "success",
hash: "0xabc",
timestamp: Date.now()
};

// Save the proof
const saved = proofCache.saveProof(inputs, proof);
expect(saved).to.be.true;

// Retrieve the proof
const retrieved = proofCache.getProof(inputs);
expect(retrieved).to.deep.equal(proof);
});

it("should return null for non-existent proofs", () => {
const inputs = { amount: 100, salt: "0x123" };
const retrieved = proofCache.getProof(inputs);
expect(retrieved).to.be.null;
});

it("should clear cache successfully", () => {
// Save some proofs
const inputs1 = { amount: 100, salt: "0x123" };
const inputs2 = { amount: 200, salt: "0x456" };
const proof = { result: "success" };

proofCache.saveProof(inputs1, proof);
proofCache.saveProof(inputs2, proof);

// Clear cache
const cleared = proofCache.clearCache();
expect(cleared).to.be.true;

// Verify proofs are cleared
expect(proofCache.getProof(inputs1)).to.be.null;
expect(proofCache.getProof(inputs2)).to.be.null;
});
});