lisk-framework
Version:
Lisk blockchain application platform
81 lines • 3.04 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.BFTParametersCache = exports.deleteBFTParameters = exports.getBFTParameters = void 0;
const lisk_codec_1 = require("@liskhq/lisk-codec");
const lisk_cryptography_1 = require("@liskhq/lisk-cryptography");
const errors_1 = require("./errors");
const schemas_1 = require("./schemas");
const getBFTParameters = async (paramsStore, height) => {
const start = lisk_cryptography_1.utils.intToBuffer(0, 4);
const end = lisk_cryptography_1.utils.intToBuffer(height, 4);
const results = await paramsStore.iterate({
limit: 1,
gte: start,
lte: end,
reverse: true,
});
if (results.length !== 1) {
throw new errors_1.BFTParameterNotFoundError();
}
const [result] = results;
return lisk_codec_1.codec.decode(schemas_1.bftParametersSchema, result.value);
};
exports.getBFTParameters = getBFTParameters;
const deleteBFTParameters = async (paramsStore, height) => {
const start = lisk_cryptography_1.utils.intToBuffer(0, 4);
const end = lisk_cryptography_1.utils.intToBuffer(height, 4);
const results = await paramsStore.iterate({
gte: start,
lte: end,
});
if (results.length <= 1) {
return;
}
for (let i = 0; i < results.length - 1; i += 1) {
await paramsStore.del(results[i].key);
}
};
exports.deleteBFTParameters = deleteBFTParameters;
class BFTParametersCache {
constructor(paramsStore) {
this._paramsStore = paramsStore;
this._cache = new Map();
}
async cache(from, to) {
const start = lisk_cryptography_1.utils.intToBuffer(from, 4);
const end = lisk_cryptography_1.utils.intToBuffer(to, 4);
const results = await this._paramsStore.iterateWithSchema({
gte: start,
lte: end,
reverse: true,
}, schemas_1.bftParametersSchema);
if (from > 0) {
const nextLowest = await (0, exports.getBFTParameters)(this._paramsStore, from);
results.push({
key: lisk_cryptography_1.utils.intToBuffer(from, 4),
value: nextLowest,
});
}
for (let height = from; height <= to; height += 1) {
const paramKV = results.find(r => {
const keyHeight = r.key.readUInt32BE(0);
return keyHeight <= height;
});
if (!paramKV) {
throw new Error('Invalid state. BFT parameters should always exist in cache range');
}
this._cache.set(height, paramKV.value);
}
}
async getParameters(height) {
const cachedValue = this._cache.get(height);
if (cachedValue) {
return cachedValue;
}
const params = await (0, exports.getBFTParameters)(this._paramsStore, height);
this._cache.set(height, params);
return params;
}
}
exports.BFTParametersCache = BFTParametersCache;
//# sourceMappingURL=bft_params.js.map
;