Skip to content

Instantly share code, notes, and snippets.

@baryon
Last active January 2, 2019 10:17
Show Gist options
  • Save baryon/43bf2de4b73ef9c7314407ec987acb60 to your computer and use it in GitHub Desktop.
Save baryon/43bf2de4b73ef9c7314407ec987acb60 to your computer and use it in GitHub Desktop.
A blockchain demo
const tracer = require('tracer').colorConsole()
const console = tracer
const bitcoin = require('bsv')
const maxTried = 100000//Number.MAX_VALUE
class Block {
constructor(data, previousHash, difficulty) {
this.data = data.toString()
this.previousHash = previousHash
this.timestamp = Date.now().toString()
this.difficulty = difficulty
this.mine()
}
hash256() {
const str = this.previousHash + this.data + this.timestamp + this.answer.toString()
return bitcoin.crypto.Hash.sha256(Buffer.from(str, 'utf8')).toString('hex')
}
mine() {
this.answer = -1
do {
this.answer++
if(this.answer >= maxTried) {
throw Error('No Answer')
}
this.hash = this.hash256()
} while(this.hash.substr(0, this.difficulty) !== '0'.repeat(this.difficulty))
}
}
class Blockchain {
constructor(genesis) {
this.chain = [genesis]
}
isValid() {
for(let i=1; i<this.chain.length; i++) {
const currentBlock = this.chain[i]
const previoudBlock = this.chain[i-1]
if(currentBlock.hash != currentBlock.hash256()) {
console.debug(currentBlock.hash, currentBlock.hash256())
return false
}
if(previoudBlock.hash != currentBlock.previousHash) {
console.debug(previoudBlock.hash, currentBlock.previousHash)
return false
}
if(currentBlock.hash.substr(0, currentBlock.difficulty) !== '0'.repeat(currentBlock.difficulty)) {
console.debug(currentBlock.hash.substr(0, currentBlock.difficulty) , '0'.repeat(currentBlock.difficulty))
return false
}
}
return true
}
append(data, difficulty) {
const newBlock = new Block(data, this.chain[this.chain.length-1].hash, difficulty)
this.chain.push(newBlock)
}
}
const genesisBlock = new Block('Born', 0, 0)
const blockchain = new Blockchain(genesisBlock)
blockchain.append('Love', 1)
blockchain.append('Marry', 2)
blockchain.append('Life', 3)
blockchain.append('How to change your wife(life) in 21 days', 5)
console.log(blockchain.chain)
console.log(blockchain.isValid())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment