Skip to content

Commit

Permalink
Merge pull request #2 from SummerOfBitcoin/fix
Browse files Browse the repository at this point in the history
fix : remove unwanted code
  • Loading branch information
ajaysehwal authored Apr 27, 2024
2 parents 2d10435 + 364b905 commit 33235d6
Show file tree
Hide file tree
Showing 25 changed files with 7,869 additions and 8,616 deletions.
42 changes: 15 additions & 27 deletions dist/block.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Block = exports.BLOCK_SUBSIDY = exports.EMPTY_SCRIPT = exports.BLOCK_VERSION = exports.BTC = void 0;
exports.Block = exports.BLOCK_SUBSIDY = exports.EMPTY_SCRIPT = exports.BLOCK_VERSION = void 0;
const buffer_1 = require("./buffer");
const merkleRoot_1 = require("./merkleRoot");
const transaction_1 = require("./transaction");
const utils_1 = require("./utils");
exports.BTC = 100000000; // Number of blocks before a coinbase transaction can be spent
exports.BLOCK_VERSION = 4; // Current Bitcoin block version
exports.BLOCK_VERSION = 4;
exports.EMPTY_SCRIPT = new Uint8Array([0x00]);
exports.BLOCK_SUBSIDY = 6.25; // Empty script
exports.BLOCK_SUBSIDY = 6.25;
class Block {
constructor(previousHash, transaction, bits = BigInt(0x1f00fff)) {
this.transactions = []; // List of transactions included in the block
this.hash = '';
this.transactions = [];
this.hash = "";
this.version = exports.BLOCK_VERSION;
this.previousHash = previousHash;
this.timestamp = Math.ceil(Date.now() / 1000);
Expand All @@ -26,7 +25,8 @@ class Block {
this.calculateBlockWeight();
}
get difficulty() {
return ((this.bits & BigInt(0x00ffffff)) * BigInt(2) ** (BigInt(8) * ((this.bits >> BigInt(24)) - BigInt(3))));
return ((this.bits & BigInt(0x00ffffff)) *
BigInt(2) ** (BigInt(8) * ((this.bits >> BigInt(24)) - BigInt(3))));
}
calculateHash() {
const headerHex = this.headerBuffer();
Expand All @@ -36,12 +36,12 @@ class Block {
const buffer = Buffer.allocUnsafe(80);
const writer = new buffer_1.BitcoinWriter(buffer);
writer.writeUint32(this.version);
writer.writeBuffer(Buffer.from(this.previousHash, 'hex').reverse());
writer.writeBuffer(Buffer.from(this.previousHash, "hex").reverse());
writer.writeBuffer(Buffer.from(this.merkleRoot, "hex").reverse());
writer.writeUint32(this.timestamp);
writer.writeUint32(Number(this.bits));
writer.writeUint32(this.nonce);
console.log(buffer.toString('hex'));
console.log(buffer.toString("hex"));
return buffer;
}
createTransaction(tx) {
Expand All @@ -54,7 +54,6 @@ class Block {
for (const tx of transaction) {
totalFee += tx.fee;
}
console.log("TotalFee", totalFee);
return totalFee;
}
addTransaction(transaction) {
Expand All @@ -67,26 +66,23 @@ class Block {
tx.vout[0].value += this.totalfees;
const startstring = "6a24aa21a9ed";
const commitment = this.getwtxidCommitment();
const scriptPubKey = Buffer.from(startstring + commitment, 'hex');
tx.vout[1].scriptpubkey = scriptPubKey.toString('hex');
console.log("coinbase", tx.getTx());
console.log("Coinbase", tx.getTxId());
const scriptPubKey = Buffer.from(startstring + commitment, "hex");
tx.vout[1].scriptpubkey = scriptPubKey.toString("hex");
this.transactions.unshift(tx.getTx());
this.merkleRoot = this.getmerkleRoot(this.transactions);
this.txCount++;
return { serializeCoinbase: tx.serializeWithWitness() };
}
getwtxidCommitment() {
const wxidRoot = Buffer.from(this.witnessMerkleRoot, 'hex').reverse();
console.log("Find--------", wxidRoot.toString('hex'));
const wxidRoot = Buffer.from(this.witnessMerkleRoot, "hex").reverse();
const witnessNullVector = Buffer.alloc(32).reverse();
const commitment = (0, utils_1.doubleSHA256)(Buffer.concat([wxidRoot, witnessNullVector]));
return commitment.toString('hex');
return commitment.toString("hex");
}
reverseByteOrder(hexString) {
const hexBytes = Buffer.from(hexString, 'hex');
const hexBytes = Buffer.from(hexString, "hex");
const reversedBytes = Buffer.from(hexBytes.reverse());
const reversedHexString = reversedBytes.toString('hex');
const reversedHexString = reversedBytes.toString("hex");
return reversedHexString;
}
calculatewTxidRoot(transactions) {
Expand All @@ -99,7 +95,6 @@ class Block {
for (let tx of this.transactions) {
txweight += tx.weight;
}
console.log("-------------------weight of block", 320 + txweight);
}
getmerkleRoot(transactions) {
if (transactions.length === 0) {
Expand All @@ -108,12 +103,5 @@ class Block {
const txids = transactions.map((el) => el.txid);
return (0, merkleRoot_1.calualateMerkleRoot)(txids);
}
getTarget() {
const bits = parseInt('0x' + this.bits, 16);
const exponent = bits >> 24;
const mantissa = bits & 0xFFFFFF;
const target = (mantissa * (2 ** (8 * (exponent - 3)))).toString(16);
return Buffer.from('0'.repeat(64 - target.length) + target, 'hex');
}
}
exports.Block = Block;
2 changes: 0 additions & 2 deletions dist/blockchain.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ class Blockchain {
return this.chain.length;
}
addBlock(block) {
console.log("Successfully Start Block Mining...");
this.chain.push(block);
console.log("new Block Successfully minied");
}
}
exports.Blockchain = Blockchain;
12 changes: 2 additions & 10 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,9 @@ const coinbase_1 = require("./coinbase");
const utils_1 = require("./utils");
exports.BLOCK_SUBSIDY = 1250000000;
class MineBlock {
constructor(chain, block, difficulty) {
constructor(chain, block) {
this.chain = chain;
this.block = block;
this.difficulty = difficulty;
this.started = Date.now();
this.ended = Date.now();
this.hashes = 0;
Expand All @@ -72,7 +71,6 @@ class MineBlock {
header.writeUInt32LE(this.block.nonce, 80 - 4);
this.block.hash = (0, utils_1.doubleSHA256)(header).toString("hex");
this.hashes++;
// console.log(this.block.nonce, this.block.hash);
}
console.log("Block mined", this.block.hash, `in ${this.hashes} iterations`);
});
Expand All @@ -90,28 +88,22 @@ class Miner {
const validtransaction = this.getValidTransactions();
const block = new block_1.Block("0".repeat(64), validtransaction, BigInt(0x1f00ffff));
const { serializeCoinbase } = block.addCoinbaseTransaction(coinbase);
const mineBlock = new MineBlock(chain, block, "");
console.log(`Start mining of ${block.transactions.length} transactions with of 12.5 BTC`);
const mineBlock = new MineBlock(chain, block);
yield mineBlock.start();
chain.addBlock(block);
const txids = block.transactions.map((tx) => tx.txid);
const reversedTxids = txids.map((txid) => { var _a, _b; return ((_b = (_a = txid.match(/.{2}/g)) === null || _a === void 0 ? void 0 : _a.reverse()) === null || _b === void 0 ? void 0 : _b.join("")) || ""; });
const wtxids = block.transactions.map((tx) => tx.wtxid);
const reversedwTxids = wtxids.map((wtxid) => { var _a, _b; return ((_b = (_a = wtxid.match(/.{2}/g)) === null || _a === void 0 ? void 0 : _a.reverse()) === null || _b === void 0 ? void 0 : _b.join("")) || ""; });
const output = `${block
.headerBuffer()
.toString("hex")}\n${serializeCoinbase}\n${reversedTxids.join("\n")}`;
fs.writeFileSync("output.txt", output);
fs.writeFileSync('test.txt', reversedwTxids.join('\n'));
console.log(chain);
});
}
getValidTransactions() {
const transactionsToValidate = [];
this.memoryPool.getTransactions().forEach((tx) => {
transactionsToValidate.push(tx);
});
console.log("start validating transactions.../../");
const validator = new validate_1.Validator();
this.validTransactions = validator.validateBatch(transactionsToValidate);
return this.validTransactions;
Expand Down
17 changes: 11 additions & 6 deletions dist/memorypool.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,17 @@ class MemoryPool {
return this.transactions;
}
loadTransactions() {
fs_1.default.readdirSync(this.mempoolFolder).forEach((file) => {
const data = fs_1.default.readFileSync(`${this.mempoolFolder}/${file}`, "utf-8");
const transactionData = JSON.parse(data);
const transaction = new transaction_1.Transaction(transactionData);
this.transactions.push(transaction);
});
try {
fs_1.default.readdirSync(this.mempoolFolder).forEach((file) => {
const data = fs_1.default.readFileSync(`${this.mempoolFolder}/${file}`, "utf-8");
const transactionData = JSON.parse(data);
const transaction = new transaction_1.Transaction(transactionData);
this.transactions.push(transaction);
});
}
catch (err) {
throw err;
}
}
}
exports.MemoryPool = MemoryPool;
14 changes: 6 additions & 8 deletions dist/merkleRoot.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,18 @@ exports.calualateMerkleRoot = void 0;
const crypto_1 = __importDefault(require("crypto"));
function reverseHex(hex) {
var _a, _b;
return (_b = (_a = hex.match(/.{2}/g)) === null || _a === void 0 ? void 0 : _a.reverse().join('')) !== null && _b !== void 0 ? _b : '';
return (_b = (_a = hex.match(/.{2}/g)) === null || _a === void 0 ? void 0 : _a.reverse().join("")) !== null && _b !== void 0 ? _b : "";
}
function hash256(hex) {
const binary = Buffer.from(hex, 'hex');
const hash1 = crypto_1.default.createHash('sha256').update(binary).digest();
const hash2 = crypto_1.default.createHash('sha256').update(hash1).digest();
return hash2.toString('hex');
const binary = Buffer.from(hex, "hex");
const hash1 = crypto_1.default.createHash("sha256").update(binary).digest();
const hash2 = crypto_1.default.createHash("sha256").update(hash1).digest();
return hash2.toString("hex");
}
function calualateMerkleRoot(txids) {
// console.log(txids.length,txids)
if (txids.length === 0) {
throw new Error('Transaction IDs array cannot be empty');
throw new Error("Transaction IDs array cannot be empty");
}
const reversedTxids = txids.map(reverseHex);
let tree = txids.slice();
while (tree.length > 1) {
const newTree = [];
Expand Down
8 changes: 0 additions & 8 deletions dist/scripts/p2pkh.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,14 +96,6 @@ class P2PKH {
}
return true;
}
HextoNumber(hexString) {
const byteValues = [];
for (let i = 0; i < hexString.length; i += 2) {
const byte = hexString.substr(i, 2);
byteValues.push(parseInt(byte, 16));
}
return byteValues[0];
}
getmessageHash(transaction, inputindex, hashType = 0x01) {
const txclone = transaction.clone();
const hashTypeBuffer = new Uint8Array([hashType, 0, 0, 0]); //LE
Expand Down
Loading

0 comments on commit 33235d6

Please sign in to comment.