main.js
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, prevHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.hash = this.calculateHash();
}
calculateHash() {
return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
class Blockchain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock() {
return new Block(0, "01/01/2021", "Genesis block", "0");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.prevHash = this.getLatestBlock().hash;
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
isChainValid() {
for(let i=1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const prevBlock = this.chain[i-1];
if(currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if(currentBlock.prevHash != prevBlock.hash) {
return false;
}
}
return true;
}
}
let tcoin = new Blockchain();
tcoin.addBlock(new Block(1, "03/09/2021", {amt: 100}));
tcoin.addBlock(new Block(1, "04/09/2021", {amt: 200}));
console.log(tcoin.isChainValid());
console.log(JSON.stringify(tcoin, null, 4));
//tempering data
tcoin.chain[2].amt = 2000;
console.log(JSON.stringify(tcoin, null, 4));
console.log(tcoin.isChainValid());
Proof of Work
const SHA256 = require('crypto-js/sha256');
class Block {
constructor(index, timestamp, data, prevHash = '') {
this.index = index;
this.timestamp = timestamp;
this.data = data;
this.prevHash = prevHash;
this.hash = this.calculateHash();
this.nonce = 0;
}
calculateHash() {
return SHA256(this.index + this.prevHash + this.timestamp + JSON.stringify(this.data) + this.nonce).toString();
}
mineBlock(complexity) {
while(this.hash.substring(0, complexity) !== Array(complexity + 1).join("0")) {
this.nonce++;
//console.log(this.nonce);
this.hash = this.calculateHash();
}
console.log(`Block mined: ${this.hash}`);
}
}
class Blockchain {
constructor(complexity = 0) {
this.chain = [this.createGenesisBlock()];
this.complexity = complexity;
}
createGenesisBlock() {
return new Block(0, "01/01/2021", "Genesis block", "0");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.prevHash = this.getLatestBlock().hash;
//newBlock.hash = newBlock.calculateHash();
newBlock.mineBlock(this.complexity);
this.chain.push(newBlock);
}
isChainValid() {
for(let i=1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const prevBlock = this.chain[i-1];
if(currentBlock.hash !== currentBlock.calculateHash()) {
return false;
}
if(currentBlock.prevHash != prevBlock.hash) {
return false;
}
}
return true;
}
}
let tcoin = new Blockchain(5);
console.log("Mining Block 1...");
tcoin.addBlock(new Block(1, "03/09/2021", {amt: 100}));
console.log("Mining Block 2...");
tcoin.addBlock(new Block(1, "04/09/2021", {amt: 200}));
console.log(JSON.stringify(tcoin, null, 4));
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://accounts.binance.info/fr/register-person?ref=T7KCZASX
Услуги по настройке https://sysadmin.guru и администрированию серверов и компьютеров. Установка систем, настройка сетей, обслуживание серверной инфраструктуры, защита данных и техническая поддержка. Помогаем обеспечить стабильную работу IT-систем.
A website with unblocked games for free online play. Popular browser games, arcades, platformers, racing games, and puzzles are available with no downloads or restrictions on any device.
Accurate weather forecast Kotor weather in February for today, tomorrow, and next week. Temperature, precipitation, wind, and humidity are all included. Follow the weather in Kotor and get up-to-date weather data online.
купить кольцо с бриллиантом кольцо для помолвки купить
Nolimit City – это про дерзкие темы, нестандартные механики и очень “нервные” бонуски, поэтому выбирать тайтлы наугад не всегда удобно: один слот может быть супер агрессивным, другой – чуть более терпимым по темпу, но всё равно с характером. Мы ведём Telegram-канал про Nolimit City: обзоры, рекомендации по играм, разборы фишек и подборки того, что реально стоит попробовать. Ссылка на канал: https://t.me/s/nolimitcity_slots
Иногда хочется зайти поиграть без лишней бюрократии: не грузить документы, не ждать проверки и не проходить десяток шагов, чтобы просто начать. Если вам актуальны проверенные казино без верификации, где можно быстро разобраться с условиями, понять про выводы и не нарваться на сомнительные площадки – загляните в наш Telegram. Там регулярно появляются свежие подборки, обновления по рабочим зеркалам, реальные нюансы по платежкам и краткие заметки “что сейчас норм, а что лучше обойти”.
Качественное SEO https://outreachseo.ru продвижение сайта для бизнеса. Наши специалисты предлагают эффективные решения для роста позиций в поисковых системах. Подробнее об услугах и стратегиях можно узнать на сайте
Любишь азарт? https://school57.ru предлагает разнообразные игровые автоматы, настольные игры и интересные бонусные программы. Платформа создана для комфортной игры и предлагает широкий выбор развлечений.
капитальный ремонт санузла ремонт ванны под ключ
ремонт ванна ванной цена ремонт ванна туалет ключ
Полная версия по ссылке: https://l-parfum.ru/catalog/testeri_duhov/Giorgio_Armani/2117/
дизайн проект частного дома цена дизайны загородных домов
Расширенный обзор: https://luma.com/user/usr-lsxcalswvt1ycz5