Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.