Skip to content

Instantly share code, notes, and snippets.

@YanLobat
Last active March 1, 2018 01:31
Show Gist options
  • Save YanLobat/40a2d4aa3034b4215d9b2c957fd251ba to your computer and use it in GitHub Desktop.
Save YanLobat/40a2d4aa3034b4215d9b2c957fd251ba to your computer and use it in GitHub Desktop.
const fs = require('fs');
const crypto = require('crypto');
const secret = 'windranger';
let blocks, block, hash, content;
if (fs.existsSync('./blocks.txt')) {
blocks = JSON.parse(fs.readFileSync('./blocks.txt'));
const blocksAmount = blocks.length;
for (let i = 0; i < blocksAmount; i++) {
const potentialHash = i > 0?
crypto
.createHmac('sha256', secret)
.update(i+'_'+blocks[i]['content']+'_'+blocks[i-1]['block_hash'])
.digest('hex'):
crypto
.createHmac('sha256', secret)
.update('0_'+blocks[0]['content'])
.digest('hex');
if (blocks[i]['block_hash'] !== potentialHash) {
throw new Error('Hash is not satisfying');
}
}
content = makeid();
hash = crypto.createHmac('sha256', secret)
.update(blocksAmount+'_'+content+'_'+blocks[blocksAmount-1]['block_hash'])
.digest('hex');
block = {
block_number: blocksAmount,
block_hash: hash,
content
}
} else {
blocks = [];
content = makeid();
hash = crypto.createHmac('sha256', secret)
.update('0_'+content)
.digest('hex');
block = {
block_number: 0,
block_hash: hash,
content
}
}
blocks.push(block);
fs.writeFileSync('./blocks.txt', JSON.stringify(blocks));
function makeid() {
let text = "";
let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment