Search code examples
pythonhashblockchainhashlibcryptocurrency

Code not hashing? <bound method Block.hash of <__main__.Block object at 0x032F04A8>>


I'm trying to make my own cryptocurrency and blockchain. Made a few edits and now it's not hashing?

Can someone with hashlib knowledge help me?

# -*- coding: utf-8 -*-

from hashlib import sha256


def updatehash(*args):
    hashing_text = ""; h = sha256()
    for arg in args:
        hashing_text += str(args)

    h.update(hashing_text.encode("utf-8"))
    return h.hexdigest()


class Block():
    data = None
    hash = None
    nonce = 0
    previous_hash = "0" * 64

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

    def hash(self):
        return updatehash(
            self.number,
            self.previous_hash,
            self.data,
            self.nonce,
        )

    def __str__(self):
        return str("Block#: %s\nHash: %s\nPrevious: %s\nData: %s\nNonce: %s\n" %(
            self.number,
            self.hash,
            self.previous_hash,
            self.data,
            self.nonce
            )
        )


class Blockchain():
    difficulty = 4

    def __init__(self, chain=[]):
        self.chain = chain

    def add(self, block):
        self.chain.append(block)

    def remove(self, block):
        self.chain.remove(block)

    def mine(self, block):
        try: block.previous_hash = self.chain[-1].hash()
        except IndexError: pass

        while True:
            if block.hash()[:self.difficulty] == "0" * self.difficulty:
                self.add(block); break
            else:
                block.nonce += 1


def main():
    blockchain = Blockchain()
    database = ["hello", "goodbye", "test", "DATA here"]

    num = 0

    for data in database:
        num += 1
        blockchain.mine(Block(data, num))

    for block in blockchain.chain:
        print(block)

if __name__ == '__main__':
    main()

This is what the first block looks like. The hash isn't showing but only saying main.Block object at 0x032C9AA8>>...

Hash: <bound method Block.hash of <__main__.Block object at 0x032C9AA8>>
Previous: 0000000000000000000000000000000000000000000000000000000000000000
Data: hello
Nonce: 78787

I need help in getting the Hash to work again...


Solution

  •     def hash(self):
    

    hash is a function. You forgot a () to get the result:

        def __str__(self):
            return str("Block#: %s\nHash: %s\nPrevious: %s\nData: %s\nNonce: %s\n" %(
                self.number,
                self.hash(),
                self.previous_hash,
                self.data,
                self.nonce
                )
            )