tovarish-relayer/lib/services/treeCache.js

61 lines
2.3 KiB
JavaScript
Raw Permalink Normal View History

2024-11-13 04:42:13 +03:00
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TreeCache = void 0;
const bloomfilter_js_1 = __importDefault(require("bloomfilter.js"));
const data_1 = require("./data");
class TreeCache {
userDirectory;
PARTS_COUNT;
2024-11-19 13:22:27 +03:00
constructor({ userDirectory, PARTS_COUNT = 4 }) {
2024-11-13 04:42:13 +03:00
this.userDirectory = userDirectory;
this.PARTS_COUNT = PARTS_COUNT;
}
2024-11-19 13:22:27 +03:00
static getInstanceName({ netId, amount, currency, }) {
return `deposits_${netId}_${currency}_${amount}`;
2024-11-13 04:42:13 +03:00
}
2024-11-19 13:22:27 +03:00
async createTree({ netId, amount, currency, events, tree, }) {
2024-11-13 04:42:13 +03:00
const bloom = new bloomfilter_js_1.default(events.length);
2024-11-19 13:22:27 +03:00
const instance = TreeCache.getInstanceName({ netId, amount, currency });
console.log(`Creating cached tree for ${instance}\n`);
2024-11-13 04:42:13 +03:00
// events indexed by commitment
const eventsData = events.reduce((acc, { leafIndex, commitment, ...rest }, i) => {
if (leafIndex !== i) {
throw new Error(`leafIndex (${leafIndex}) !== i (${i})`);
}
acc[commitment] = { ...rest, leafIndex };
return acc;
}, {});
const slices = tree.getTreeSlices(this.PARTS_COUNT);
await Promise.all(slices.map(async (slice, index) => {
const metadata = slice.elements.reduce((acc, curr) => {
if (index < this.PARTS_COUNT - 1) {
bloom.add(curr);
}
acc.push(eventsData[curr]);
return acc;
}, []);
const dataString = JSON.stringify({
...slice,
metadata,
}, null, 2) + '\n';
2024-11-19 13:22:27 +03:00
const fileName = `${instance}_slice${index + 1}.json`;
2024-11-13 04:42:13 +03:00
await (0, data_1.saveUserFile)({
fileName,
userDirectory: this.userDirectory,
dataString,
});
}));
const dataString = bloom.serialize() + '\n';
2024-11-19 13:22:27 +03:00
const fileName = `${instance}_bloom.json`;
2024-11-13 04:42:13 +03:00
await (0, data_1.saveUserFile)({
fileName,
userDirectory: this.userDirectory,
dataString,
});
}
}
exports.TreeCache = TreeCache;