Skip to content

Instantly share code, notes, and snippets.

@Sharaal
Last active January 24, 2018 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sharaal/eb44563edd982b8a2181ffb8aee01f64 to your computer and use it in GitHub Desktop.
Save Sharaal/eb44563edd982b8a2181ffb8aee01f64 to your computer and use it in GitHub Desktop.
An example blockchain implementation in Node.js to understand the concept behind
// example usage
const blockchain = new Blockchain();
blockchain.add(1);
blockchain.add(2);
blockchain.add(3);
blockchain.verify();
console.log(blockchain);
// example output
/*
$ node blockchain.js
Blockchain {
blocks:
[ { timestamp: 2018-01-24T10:02:07.395Z,
data: 1,
hash: 'b9b92d5db0fbe77b2600ecc5bc36b7938d7185bbdb5b39e399374209e16e877e' },
{ timestamp: 2018-01-24T10:02:07.395Z,
data: 2,
hash: '569d2ccfd87b7a7b0203e2d160cd4fffc05a831c89a5f5d626cfa245e887a197' },
{ timestamp: 2018-01-24T10:02:07.395Z,
data: 3,
hash: 'adb97d934aafe7bd0cc943c2920f512baaed44e37bef5dad3177d8f798200db7' } ],
secret: '' }
*/
// example implementation
const crypto = require('crypto');
class Blockchain {
constructor(secret = '') {
this.blocks = [];
this.secret = secret;
}
hash(data) {
return crypto.createHash('sha256').update(JSON.stringify(data)).digest('hex');
}
add(data) {
const block = {
timestamp: new Date(),
data,
};
const hashData = { block };
if (this.blocks.length > 0) {
hashData.previousHash = this.blocks[this.blocks.length - 1].hash;
}
block.hash = this.hash(hashData);
this.blocks.push(block);
}
verify() {
for (const index in this.blocks) {
const block = this.blocks[index];
const hashData = { block: { timestamp: block.timestamp, data: block.data }};
if (index > 0) {
hashData.previousHash = this.blocks[index - 1].hash;
}
const hash = this.hash(hashData);
if (block.hash !== hash) {
return false;
}
}
return true;
}
}
@Sharaal
Copy link
Author

Sharaal commented Jan 24, 2018

Consense of the first reviews and feedbacks: It's not a blockchain, it's a merkle tree what I did. A blockchains needs to be centralized with the networking and syncing parts. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment