Skip to content

Instantly share code, notes, and snippets.

@jsphdnl
Created January 9, 2018 13:32
Show Gist options
  • Save jsphdnl/e24979c99d1e6dc3b493c39a60d84267 to your computer and use it in GitHub Desktop.
Save jsphdnl/e24979c99d1e6dc3b493c39a60d84267 to your computer and use it in GitHub Desktop.
BlockChain from Scratch Part 01 - javascript
var crypto = require('crypto')
, shasum = crypto.createHash('sha1');
/*
* Install "cyrpto" lib dependeny to compute the hash
* `npm install crypto`
*/
class TRBlock {
/**
* constructor for creating a block
* @param {Number} index - the index of the Block
* @param {Number} timestamp - epoch time, secs from Jan 1 1972
* @param {Object} data - the data to be stored on block chain
* @param {String} prevHash - hash of the previous block
* @param {String} nonce - the string to be mined
* @param {Number} target - the Number of leading zeros to mine nonce
*/
constructor(index, timestamp, data, prevHash, nonce, target){
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.nonce = nonce;
this.target = target;
}
/**
* Compute sha-1 hash and return hexadeicmal hash
* @return SHA-1 hexadeicmal hash
*/
computeHash(){
shasum.update(JSON.stringify(this));
return shasum.digest("hex");
}
}
var block = new TRBlock(0, 1514528022, "Hello World",
"000000000000000000000000000", "Random nonce", 8);
console.log(block.computeHash());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment