skip to Main Content

This is a blockchain test. It seems that it was OK the last time I ran it. When I came to run the project today, the following error occurred. I want to know why.

import vorpal from "vorpal";

import BlockChain from "/D:/MyProject/JSProject/BlockChain/lab-01/Blockchain.js";
const blockChain = new BlockChain()

vorpal
    .command('mine','mine1')
    .action(function(args,callback){
        const newBlock = blockChain.mine()
        if(newBlock){
            console.log(newBlock)
        }
        callback
    })

console.log('welcome to BlockChain')
vorpal.exec('help')

2

Answers


  1. Chosen as BEST ANSWER

    Here are my Blockchain.js and myVorpal.js files.

    import SHA256 from "sha256";
    
    class Blockchain{
        //1.constructor function is used to initialize the chain and pendingTransactions arrays
        constructor () {
            this.chain = [this.createGenesisBlock()];//The chain array will contain every block or transaction group added to the network.
            this.pendingTransactions = [];//The pendingTransactions array will store all transactions that have not been added to a block yet.
        }
    
        //2.Build the createGenesisBlock function (used to return the genesis block)
        createGenesisBlock() {
            return {
              index: 1,
              timestamp: 0,
              transactions: [],
              nonce: 0,
              hash: "hash",
              previousBlockHash: "previousBlockHash",
            };
          }
    
          //3.Get the last block
          getLastBlock() {
            return this.chain[this.chain.length - 1];
          };
    
          //4.Calculate the hash value of the block
          generateHash(previousBlockHash, timestamp, pendingTransactions) {
            let hash = "";
            let nonce = 0;
        
            while (hash.substring(0, 3) !== "000") {
              nonce++;
              hash = SHA256(
                previousBlockHash +
                  timestamp +
                  JSON.stringify(pendingTransactions) +
                  nonce
              ).toString();
            }
        
            return { hash, nonce };
          }
    
          //5.Create a transaction and add it to the pending transactions list
          createNewTransaction(amount, sender, recipient) {
            const newTransaction = {
              amount,
              sender,
              recipient,
            };
        
            this.pendingTransactions.push(newTransaction);
          }
    
    
          //6.Generate a new block
          generateNewBlock(){
            const timestamp = Date.now();
            const transactions = this.pendingTransactions;
            const previousBlockHash = this.getLastBlock().hash;
            const generateHash = this.generateHash(
              previousBlockHash,
              timestamp,
              transactions
            );
    
            return {
              index: this.chain.length + 1,
              timestamp,
              transactions,
              nonce: generateHash.nonce,
              hash: generateHash.hash,
              previousBlockHash,
            };
          }
    
          //7.Validate the block
          isValidBlock(newBlock){
            // Logic:
            // 1.The index of the new block = the index of the last block + 1
            // 2.The timestamp of the new block > the timestamp of the last block
            // 3.The preHash of the new block = the hash of the last block
            // 4.The hash of the new block meets the difficulty requirements
            // 5.The nonce verification method of the new block: whether the hash value calculation of the new block is correct
            if(newBlock.index !== this.getLastBlock().index + 1){
              return false
            }
    
            if(newBlock.timestamp <= this.getLastBlock().timestamp){
              return false;
            }
            
            if(newBlock.previousBlockHash !== this.getLastBlock().hash){
              return false;
            }
            
            // let difficulty = 3; //This should be consistent with the difficulty when generating a new block
            // if(newBlock.hash.substring(0, difficulty) !== "0".repeat(difficulty)){
            //   return false;
            // }
            
            let generateHash = this.generateHash(
                newBlock.previousBlockHash,
                newBlock.timestamp,
                newBlock.transactions
              );
              
             if(generateHash.hash !== newBlock.hash){
               return false;
             }
    
            return true
    
          }
    
          //8.Validate the blockchain
          isValidChain(chain = this.chain){
            //Validate blocks other than the genesis block
            //Logic: For each block, call isValdBlock() to validate, if one of the blocks fails to validate, return false
            for(let i=chain.length-1;i>1;i--){
              if(!this.isValidBlok(chain[i])){
                return false
              }
            }
    
            //Validate the genesis block, because the genesis block is fixed
    
            if(JSON.stringify(chain[0]) !== JSON.stringify(this.createGenesisBlock())){
              return false;
            }
            
            return true; //If all blocks are validated successfully, return true
    
          }
    
          //9.createNewBlock will enable us to add pending transactions to a block, calculate the hash value, and add the block to the chain
          createNewBlock() {
            
            const newBlock = this.generateNewBlock()
            
            //Validate block legality & blockchain legality
            if(this.isValidBlock(newBlock)&&this.isValidChain()){
              this.pendingTransactions = [];
              this.chain.push(newBlock);
            }
          
            return newBlock;
          }
    }
    //Export class
    export default Blockchain;

    import vorpal from "vorpal";//Import vorpal and instantiate a Vorpal object
    
    //Import the blockchain file and use new to assign the BlockChain instance value to blockchain
    import BlockChain from "./Blockchain.js";
    const blockChain = new BlockChain()//Create instance
    
    //Add mining command line
    vorpal
        .command('mine','Mining')
        .action(function(args,callback){
            const newBlock = blockChain.mine()
            if(newBlock){
                console.log(newBlock)
            }
            callback
        })
    
    console.log('welcome to BlockChain')
    vorpal.exec('help')//vorpal.exec() method is used to execute the specified command.

    These two files are actually in the same directory. Vorpal has indeed downloaded them and importing them should be no problem. I'm sorry that I really can't find any obvious problems. I can provide too little information.


  2. The problem appears to be connected to how you import the BlockChain class in your JavaScript code. The location you provided appears to be a Windows file path (D:/MyProject/JSProject/BlockChain/lab-01/Blockchain.js), which may cause problems when running your code with Node.js. Make sure your Blockchain.js file is in the same directory as your main JavaScript project, or import the Blockchain class using a relative path.

    import vorpal from "vorpal";
    import BlockChain from "./Blockchain"; // Use a relative path
    
    const blockChain = new BlockChain();
    
    vorpal
        .command('mine', 'mine1')
        .action(function(args, callback) {
            const newBlock = blockChain.mine();
            if (newBlock) {
                console.log(newBlock);
            }
            callback();
        });
    
    console.log('Welcome to BlockChain');
    vorpal.exec('help');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search