diff --git a/blockchain.js b/blockchain.js new file mode 100644 index 0000000..e6c0d4a --- /dev/null +++ b/blockchain.js @@ -0,0 +1,62 @@ +const crypto = require("crypto"); + +// 🔗 Klasa pojedynczego bloku +class Block { + constructor(index, timestamp, data, previousHash = "") { + this.index = index; + this.timestamp = timestamp; + this.data = data; + this.previousHash = previousHash; + this.hash = this.calculateHash(); + } + + calculateHash() { + return crypto + .createHash("sha256") + .update( + this.index + + this.previousHash + + this.timestamp + + JSON.stringify(this.data) + ) + .digest("hex"); + } +} + +// 🧠 Klasa prostego łańcucha bloków +class Blockchain { + constructor() { + this.chain = [this.createGenesisBlock()]; + } + + createGenesisBlock() { + return new Block(0, Date.now().toString(), "Genesis Block", "0"); + } + + getLatestBlock() { + return this.chain[this.chain.length - 1]; + } + + addBlock(newBlock) { + newBlock.previousHash = this.getLatestBlock().hash; + newBlock.hash = newBlock.calculateHash(); + this.chain.push(newBlock); + } + + isChainValid() { + for (let i = 1; i < this.chain.length; i++) { + const current = this.chain[i]; + const previous = this.chain[i - 1]; + + if (current.hash !== current.calculateHash()) return false; + if (current.previousHash !== previous.hash) return false; + } + return true; + } +} + +// 📦 Eksport +module.exports = { + Block, + Blockchain, +};