首页 > 解决方案 > Add creator name to a block

问题描述

I am practicing Blockchain and need to record timestamps of when a block is created and the block creator's name.

Link of source code. https://github.com/howCodeORG/Simple-Python-Blockchain

I have modified a few lines

import getpass # Added by me
    class Block:
        blockNo = 0
        data = None
        next = None
        hash = None
        nonce = 0
        previous_hash = 0x0
        timestamp = datetime.datetime.now()
        creator = getpass.getuser() # Added by me


        def __init__(self, data):
            self.data = data

        def hash(self):
            h = hashlib.sha256()
            h.update(
            str(self.nonce).encode('utf-8') +
            str(self.data).encode('utf-8') +
            str(self.previous_hash).encode('utf-8') +
            str(self.timestamp).encode('utf-8') +
            str(self.creator).encode('utf-8') + # Added by me
            str(self.blockNo).encode('utf-8')
            )
            return h.hexdigest()

        def __str__(self):
            return "Block Hash: " + str(self.hash()) + "\nBlockNo: " + str(self.blockNo) + "\nBlock Data: " + str(self.data) + "\nBlock Creator: " + str(self.creator) + "\nHashes: " + str(self.nonce) + "\n--------------"

Output:

Block Hash: 50339796dd060db74766426b02c57f58b591ddad6331a75e72b61081bf97ade0
BlockNo: 1
Block Data: Block 1
Block Creator: anku
Hashes: 1036355
--------------
Block Hash: 5c1d8eac7b95f4c2410681c0d2cb61eb754ff222d926778c4e1da332133107f1
BlockNo: 2
Block Data: Block 2
Block Creator: anku
Hashes: 3015159
--------------
Block Hash: ad14237eadc3be6ea1a1318fd25dc33e40216c0d37ea0bde14b8d05adf2501b9
BlockNo: 0
Block Data: Genesis
Block Creator: anku
Hashes: 0
--------------
Block Hash: 50339796dd060db74766426b02c57f58b591ddad6331a75e72b61081bf97ade0
BlockNo: 1
Block Data: Block 1
Block Creator: anku
Hashes: 1036355
--------------
Block Hash: 5c1d8eac7b95f4c2410681c0d2cb61eb754ff222d926778c4e1da332133107f1
BlockNo: 2
Block Data: Block 2
Block Creator: anku
Hashes: 3015159
--------------

Issue: The Genesis block must be the first one to be executed but it is executed in between. Can someone guide me where I am doing it wrong?

标签: pythonblockchain

解决方案


如果你看一下这个mine函数,它会打印出它挖掘的块。这就是创世块之前的块的来源。尝试删除printinmine函数。


推荐阅读