@lighthouse-web3/kavach
Version:
Encryption SDK: Build your trustless, decentralized and fault resistance Application using distributed key shades with threshold cryptography
63 lines (62 loc) • 2.08 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.recoverShards = void 0;
const util_1 = require("../../util");
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function randSelect(k, n) {
if (k > n) {
throw new Error("k cannot be greater than n");
}
const numbers = Array.from({ length: n }, (_, i) => i + 1);
const shuffledNumbers = shuffleArray(numbers);
return shuffledNumbers.slice(0, k).sort((a, b) => a - b);
}
const recoverShards = async (address, cid, auth_token, numOfShards = 3, dynamicData = {}) => {
try {
const nodeIndexSelected = randSelect(numOfShards, 5);
const nodeUrl = nodeIndexSelected.map((elem) => `/api/retrieveSharedKey/${elem}`);
// send encryption key
const requestData = async (url, index) => {
try {
const response = await (0, util_1.API_NODE_HANDLER)(url, "POST", auth_token, {
address,
cid,
dynamicData,
});
return response;
}
catch (error) {
throw new Error(error?.message || "Unknown error");
}
};
const recoveredShards = [];
for (const [index, url] of nodeUrl.entries()) {
const response = await requestData(url, index);
await new Promise((resolve) => setTimeout(resolve, 1000));
recoveredShards.push(response?.payload);
}
return {
shards: recoveredShards,
error: null,
};
}
catch (err) {
if (err.message.includes("null")) {
return {
shards: [],
error: `cid not found`,
};
}
return {
shards: [],
error: JSON.parse(err?.message),
};
}
};
exports.recoverShards = recoverShards;
;