Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions blockchain.js
Original file line number Diff line number Diff line change
@@ -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,
};