1

Hi, I have this simple code for creating a 'BlockChain'. When I run the code it gives me an error.

This is the error

import { sha256 } from 'js-sha256'; ^

SyntaxError: Unexpected token {...}

I think the error in "sha256" function I have already install all the packages for "js-sha256".

The code

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

2 Answers2

1

Node v11 does not officially support ES modules, but only some of it, and only with the --experimental-modules flag, and only with .mjs extensions.

So to my knowledge, you can either:

  • Rename your JS file(s) with .mjs and run it node --experimental-modules index.mjs (not really recommended, but works with the little edit mentioned in the end of this answer)
  • Use babel-node (definitely NOT recommended)
  • Use babel and @babel/register in dev and build a production code to deploy.

By the way, it seems to be the default export you are looking for, not a named export, i.e.:

import sha256 from 'js-sha256';

laruiss
  • 3,780
  • 1
  • 18
  • 29
  • I didn't understand the last part about ' import sha256 from 'js-sha256';' ? –  Jan 25 '20 at 14:08
  • 1
    You wrote `import { sha256 } from 'js-sha256';`, I left out the curly brackets. See https://stackoverflow.com/questions/46913851/why-and-when-to-use-default-export-over-named-exports-in-es6-modules – laruiss Jan 25 '20 at 14:31
0

In modern browser, just use built-in Crypto API:

const text = 'hello';

async function digestMessage(message) {
  const msgUint8 = new TextEncoder().encode(message);                           // encode as (utf-8) Uint8Array
  const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);           // hash the message
  const hashArray = Array.from(new Uint8Array(hashBuffer));                     // convert buffer to byte array
  const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join(''); // convert bytes to hex string
  return hashHex;
}

const result = await digestMessage(text);
console.log(result)

Then you could verify the result via online sha256 tool.

cwtuan
  • 1,718
  • 1
  • 18
  • 20