Почему предыдущий хэш не отображается, когда я console.log тестирует блокчейн? - PullRequest
0 голосов
/ 09 января 2019

Я пытаюсь узнать больше о блокчейне, создав небольшой проект с использованием JavaScript. Может кто-нибудь объяснить мне, почему предыдущий хэш не показывает, когда я console.log тестирую блокчейн?

(npm install - сохранить crypto-js, если вам нужен SHA256)

        const SHA256 = require('crypto-js/sha256');

        class Block{
            //Index: (Optional) tells us where the block is in the chain
            //Timestamp: tells us when the block was created 
            //Data: Can include any kind of data; for a currency you could store details of the transaction(transfer amount, sender id, receiver id)
            //previousHash: String which contains the hash of the block which came before it (Ensures data integrity)

            constructor(index, timestamp, data, previousHash = ''){
                this.index = index;
                this.timestamp = timestamp;
                this.data = data;
                this.previousHash = previousHash;
                //Hash of this block
                this.hash = this.calculateHash();
            }

            //Runs values from block through a hashing function to create a hash
            calculateHash(){
                return SHA256(this.index + this.previousHash + this.timestamp + JSON.stringify(this.data)).toString();
            }
        }
        //8.44

        class Blockchain{
            //Initializes blockchain
            constructor(){
                this.chain = [this.createGenesisBlock];
            }

            // first block needs to be created manually 
            //index, timeStamp, data, previousHash(there is none in this case)
            createGenesisBlock(){
                return new Block(0, "01/01/2017", "Genesis block", "0");
            }

            //Returns most recently added block
            getLatestBlock(){
            return this.chain[this.chain.length -1];
            }

            //adds a new block to the chain
            addBlock(newBlock){
                newBlock.previousHash = this.getLatestBlock().hash;
                newBlock.hash = newBlock.calculateHash
                //The chain is just an array so you can use regular array methods
                this.chain.push(newBlock);
            }
        }

        //create instance of blockchhain
        let Coin = new Blockchain();
        Coin.addBlock(new Block(1, "10/07/2017", {amount: 4}));
        Coin.addBlock(new Block(2, "12/07/2017", {amount: 10}));

        console.log(JSON.stringify(Coin, null, 4));

Я ожидаю, что JSON-файл console.logged будет содержать предыдущий хэш, а также индекс, метку времени и данные. Содержит все, кроме previousHash.

Спасибо за помощь, которая некоторое время царапала мне голову, пытаясь понять это ...

Ответы [ 2 ]

0 голосов
/ 10 января 2019

Вы забыли прохождение в строке с: this.chain = [this.createGenesisBlock()]; строкой, таким образом, первый элемент цепочки будет ссылкой на функцию, а не экземпляром Block. Добавьте парантез, и он должен работать.

Кроме того, вы также забыли парантез при вызове другой функции: когда вы пытаетесь вызвать функцию newBlock.hash = newBlock.calculateHash()

0 голосов
/ 10 января 2019

У вас также нет hash в вашей консоли. Это строка с ошибкой:

            newBlock.hash = newBlock.calculateHash

calculateHash является функцией

            newBlock.hash = newBlock.calculateHash()

Сейчас работает:

{
    "chain": [
        null,
        {
            "index": 1,
            "timestamp": "10/07/2017",
            "data": {
                "amount": 4
            },
            "hash": "8f84adcf036e9aa052a4d7e689c7b8b06070b851eff535870f5cb8f7d53ab05a"
        },
        {
            "index": 2,
            "timestamp": "12/07/2017",
            "data": {
                "amount": 10
            },
            "previousHash": "8f84adcf036e9aa052a4d7e689c7b8b06070b851eff535870f5cb8f7d53ab05a",
            "hash": "a2479e7df8f2a61f97f3ae4830aff93c0d43041b4a7cbb8079c2309a915d8945"
        }
    ]
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...