Blockchain Demo

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));

15 Replies to “Blockchain Demo”

  1. Услуги по настройке https://sysadmin.guru и администрированию серверов и компьютеров. Установка систем, настройка сетей, обслуживание серверной инфраструктуры, защита данных и техническая поддержка. Помогаем обеспечить стабильную работу IT-систем.

  2. Nolimit City – это про дерзкие темы, нестандартные механики и очень “нервные” бонуски, поэтому выбирать тайтлы наугад не всегда удобно: один слот может быть супер агрессивным, другой – чуть более терпимым по темпу, но всё равно с характером. Мы ведём Telegram-канал про Nolimit City: обзоры, рекомендации по играм, разборы фишек и подборки того, что реально стоит попробовать. Ссылка на канал: https://t.me/s/nolimitcity_slots

  3. Иногда хочется зайти поиграть без лишней бюрократии: не грузить документы, не ждать проверки и не проходить десяток шагов, чтобы просто начать. Если вам актуальны проверенные казино без верификации, где можно быстро разобраться с условиями, понять про выводы и не нарваться на сомнительные площадки – загляните в наш Telegram. Там регулярно появляются свежие подборки, обновления по рабочим зеркалам, реальные нюансы по платежкам и краткие заметки “что сейчас норм, а что лучше обойти”.

  4. Качественное SEO https://outreachseo.ru продвижение сайта для бизнеса. Наши специалисты предлагают эффективные решения для роста позиций в поисковых системах. Подробнее об услугах и стратегиях можно узнать на сайте

  5. Любишь азарт? https://school57.ru предлагает разнообразные игровые автоматы, настольные игры и интересные бонусные программы. Платформа создана для комфортной игры и предлагает широкий выбор развлечений.

Leave a Reply to GeorgeLed Cancel reply

Your email address will not be published.