Skip to content

Instantly share code, notes, and snippets.

@oilsinwater
Created December 18, 2017 21:31
Show Gist options
  • Save oilsinwater/24c2e489301bec29c9665b249fb2f70b to your computer and use it in GitHub Desktop.
Save oilsinwater/24c2e489301bec29c9665b249fb2f70b to your computer and use it in GitHub Desktop.
philCoin
// import of library for hash functions
const SHA256 = require('crypto-js/sha256');
// class to determine what the blockchain will look like
class Block {/* */
// data would store terms of currency would store sender and receiver information
// previoushash ensure integrity of data
constructor(index, timestamp, data, previoushash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.previoushash = previoushash;
// hash of our block calculation
this.hash = this.calculateHash();
}
a
// method to identify block on chain
// using .toString otherwise it returns an object, more readable
calculateHash() {
return SHA256(this.index + this.previoushash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
class Blockchain {
// responsible for initializing the blockchain
constructor() {
// area of blocks
this.chain = [this.createGenesisBlock()];
}
// first block should be added manually
createGenesisBlock() {
return new Block(0, "01/01/2017", "Gensis block", "0");
}
// returns latest block in the chain, returning the last element
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
// pushes block onto the array, 'chain'
addBlock(newBlock) {
// must set the hash first
newBlock.previoushash = this.getLatestBlock().hash;
// must recalculate for new chain with a new hash function
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
// check validity of the chain by looping through it comparing hashes
isChainValid() {
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
//check if hash of currentBlock is still valid
if (currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
//check if block points to correct previousBlock
if (currentBlock.previoushash !== previousBlock.hash) {
return false;
}
}
return true;
}
}
// instance of the block, to test
let philCoin = new Blockchain();
philCoin.addBlock(new Block, (1, "10/07/2017", { amount: 4 }));
philCoin.addBlock(new Block, (2, "11/07/2017", { amount: 10 }));
// data tampering example, adding tokens to override data
philCoin.chain[1].data = { amount: 100 };
// attempt tamper by recalcualting the hash
philCoin.chain[1].hash = philCoin.chain[1].calculateHash();
console.log(JSON.stringify(philCoin, null, 4));
// data tampering makes false
console.log(' Is chain valid? ' + philCoin.isChainValid());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment