Last active
May 16, 2018 09:22
-
-
Save max-lt/87226452faef6a316df7d9dab41a248f to your computer and use it in GitHub Desktop.
Simple blockchain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Blockchain() { | |
const blocks = this.blocks = [] | |
const getBlockId = (i) => blocks[i] && blocks[i].id || '00000000' | |
function hash(str) { | |
const hash = Array(8).fill(0); | |
for (let i = 0; i < str.length; i++) | |
hash[i % 8] ^= str.charCodeAt(i) | |
return hash.map((e) => e % 10).join('') | |
} | |
this.push = (str) => blocks.push({id: hash(getBlockId(blocks.length - 1) + str), data: str}) | |
this.check = () => blocks.every((b, i) => b.id === hash(getBlockId(i - 1) + b.data)) | |
} | |
const b = new Blockchain | |
b.push('test') | |
b.push('test') | |
b.push('testing long string') | |
console.log(b.blocks, `valid=${b.check()}`) | |
// Corrupting blochchain | |
b.blocks[1].data = 'TEST' | |
b.blocks[1].id = '82086666' | |
console.log(b.blocks, `valid=${b.check()}`) | |
// $ node blockchain.js | |
// [ { id: '85788888', data: 'test' }, | |
// { id: '60866666', data: 'test' }, | |
// { id: '14677370', data: 'testing long string' } ] 'valid=true' | |
// [ { id: '85788888', data: 'test' }, | |
// { id: '82086666', data: 'TEST' }, | |
// { id: '14677370', data: 'testing long string' } ] 'valid=false' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment