Привет, у меня есть этот простой код для создания BlockChain. Когда я запускаю код, он выдает ошибку.
Это ошибка
import {sha256} из 'js -sha256' ; ^
SyntaxError: неожиданный токен {...}
Я думаю, что ошибка в функции "sha256" Я уже установил все пакеты для "js -ша256" .
код
import { sha256 } from 'js-sha256';
class Block {
constructor(timestamp, data, previousHash = '') {
this.timestamp = timestamp;
this.data = data;
this.previousHash = previousHash;
this.hash = this.calculateHash(); }
calculateHash() {
return sha256(this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
}
}
class BlockChain {
constructor() {
this.chain = [this.createGenesisBlock()];
}
createGenesisBlock(){
return new Block("2018-11-11 00:00:00", "Genesis block of simple chain", "");
}
getLatestBlock() {
return this.chain[this.chain.length - 1];
}
addBlock(newBlock) {
newBlock.hash = newBlock.calculateHash();
this.chain.push(newBlock);
}
isChainValid() {
//Traverse all the blocks
for (let i = 1; i < this.chain.length; i++) {
const currentBlock = this.chain[i];
const previousBlock = this.chain[i - 1];
if (currentBlock.hash !== currentBlock.calculateHash()) {
console.error("hash not equal: " + JSON.stringify(currentBlock));
return false;
}
if (currentBlock.previousHash !== previousBlock.calculateHash) {
console.error("previous hash not right: " + JSON.stringify(currentBlock));
return false;
}
}
return true;
}
}
let simpleChain = new BlockChain();
simpleChain.addBlock(new Block("2018-11-11 00:00:01", {amount: 10}));
simpleChain.addBlock(new Block("2018-11-11 00:00:02", {amount: 20}));
console.log(JSON.stringify(simpleChain, null, 4));
console.log("is the chain valid? " + simpleChain.isChainValid());