@nomiclabs/buidler
Version:
Buidler is an extensible developer tool that helps smart contract developers increase productivity by reliably bringing together the tools they want.
89 lines • 3.16 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const ethereumjs_util_1 = require("ethereumjs-util");
class Blockchain {
constructor() {
this._blocks = [];
this._blockNumberByHash = new Map();
}
getLatestBlock(cb) {
if (this._blocks.length === 0) {
cb(new Error("No block available"));
}
cb(null, this._blocks[this._blocks.length - 1]);
}
putBlock(block, cb) {
const blockNumber = ethereumjs_util_1.bufferToInt(block.header.number);
if (this._blocks.length !== blockNumber) {
cb(new Error("Invalid block number"));
return;
}
this._blocks.push(block);
this._blockNumberByHash.set(ethereumjs_util_1.bufferToHex(block.hash()), blockNumber);
cb(null, block);
}
delBlock(blockHash, cb) {
const blockNumber = this._blockNumberByHash.get(ethereumjs_util_1.bufferToHex(blockHash));
if (blockNumber === undefined) {
cb(new Error("Block not found"));
return;
}
for (let n = blockNumber; n < this._blocks.length; n++) {
const block = this._blocks[n];
this._blockNumberByHash.delete(ethereumjs_util_1.bufferToHex(block.hash()));
}
this._blocks.splice(blockNumber);
cb(null);
}
getBlock(hashOrBlockNumber, cb) {
let blockNumber;
if (ethereumjs_util_1.BN.isBN(hashOrBlockNumber)) {
blockNumber = hashOrBlockNumber.toNumber();
}
else {
const hash = ethereumjs_util_1.bufferToHex(hashOrBlockNumber);
if (!this._blockNumberByHash.has(hash)) {
cb(new Error("Block not found"));
return;
}
blockNumber = this._blockNumberByHash.get(hash);
}
cb(null, this._blocks[blockNumber]);
}
iterator(name, onBlock, cb) {
let n = 0;
const iterate = (err) => {
if (err !== null || err !== undefined) {
cb(err);
return;
}
if (n >= this._blocks.length) {
cb(null);
return;
}
onBlock(this._blocks[n], false, (onBlockErr) => {
n += 1;
iterate(onBlockErr);
});
};
iterate(null);
}
getDetails(_, cb) {
cb(null);
}
deleteAllFollowingBlocks(block) {
const blockNumber = ethereumjs_util_1.bufferToInt(block.header.number);
const actualBlock = this._blocks[blockNumber];
if (actualBlock === undefined || !block.hash().equals(actualBlock.hash())) {
// tslint:disable-next-line only-buidler-error
throw new Error("Invalid block");
}
for (let i = blockNumber + 1; i < this._blocks.length; i++) {
const blockToDelete = this._blocks[i];
this._blockNumberByHash.delete(ethereumjs_util_1.bufferToHex(blockToDelete.hash()));
}
this._blocks.splice(blockNumber + 1);
}
}
exports.Blockchain = Blockchain;
//# sourceMappingURL=blockchain.js.map
;