pythonflaskblockchainpycryptodome

Error IndexError: list index out of range on my basic blockchain project


I write a basic blockchain for my school project but i encountering errors how can i fix it?

here is link to my code

blockchain_data.json

{"chain": [{"index": 0, "transactions": [], "timestamp": 1701466704.945516, "previous_hash": "0", "hash": "c6adb22cbafb1763769f2e6b606fb4eeb23e3764c3c545d7f7955fbcb66420b4", "data": "Genesis Block", "nonce": 0, "signature": "\u058a\u0011*\u0016\u000f\u001d\u0010\rFL;\u89c04\u001fl\u0015\u001d\u0002\u0484d[9} Jf1 *;e$\\\u007f0_{\u001d\"8\u0007\\\u01b5&De:\u070f\u00e0@tB\u000fxM\u0018\u8632\u001a<=\u0004<oj'.Wq12>pAuZ\u001fU0\u001a8j\u0001+_\u001f/\u06f9b:I],Y^:*(\ue3f0i1T)aO\u0019t\\K7F\u001eP\u00111\tH\u0003\u0007s\u000f<\u0013l}77XP\u0004\u0001p~\b&Rx"}]}

I send http post request to add block to chain like this curl -X POST -H "Content-Type: application/json" -d '{"data": "Example Data"}' http://localhost:5000/mine I expect it to add the block to chain but gives this error

keys already exists. Skipping...
anahtarlar yuklendi.
anahtarlar yuklendi.
Private RSA key at 0x7FB36406B910
Public RSA key at 0x7FB36406BB50
anahtarlar yuklendi.
anahtarlar yuklendi.
Can't verify chain integrityl!!!
 * Debugger is active!
 * Debugger PIN: 923-375-613
127.0.0.1 - - [10/Dec/2023 22:42:04] "POST /mine HTTP/1.1" 500 -
Traceback (most recent call last):
  File "/home/wkb/PycharmProjects/pythonProject1/venv/lib/python3.11/site-packages/flask/app.py", line 1478, in __call__
    return self.wsgi_app(environ, start_response)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wkb/PycharmProjects/pythonProject1/venv/lib/python3.11/site-packages/flask/app.py", line 1458, in wsgi_app
    response = self.handle_exception(e)
               ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wkb/PycharmProjects/pythonProject1/venv/lib/python3.11/site-packages/flask/app.py", line 1455, in wsgi_app
    response = self.full_dispatch_request()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wkb/PycharmProjects/pythonProject1/venv/lib/python3.11/site-packages/flask/app.py", line 869, in full_dispatch_request
    rv = self.handle_user_exception(e)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wkb/PycharmProjects/pythonProject1/venv/lib/python3.11/site-packages/flask/app.py", line 867, in full_dispatch_request
    rv = self.dispatch_request()
         ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/wkb/PycharmProjects/pythonProject1/venv/lib/python3.11/site-packages/flask/app.py", line 852, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/run/media/wkb/529042782E47F579/scratch.py", line 310, in mine_block
    block_index = blockchain.mine()
                  ^^^^^^^^^^^^^^^^^
  File "/run/media/wkb/529042782E47F579/scratch.py", line 143, in mine
    last_block = self.last_block
                 ^^^^^^^^^^^^^^^
  File "/run/media/wkb/529042782E47F579/scratch.py", line 87, in last_block
    return self.chain[-1]
           ^^^^^^^^^^^^^^
IndexError: list index out of range

Solution

  • The error indicate self.chain is empty , because it was not initialized at this point:

    if len(blockchain.chain) == 0:
        blockchain.create_genesis_block()
    else:
        blockchain.load_from_file('blockchain_data.json')
    

    The logic should be if it empty then load_from_file to fill self.chain from the file:

    if len(blockchain.chain) == 0:
        blockchain.load_from_file('blockchain_data.json')
    else:
        blockchain.create_genesis_block()
    

    After correcting this block , you may encounter a new error :

        166             self.chain = []
        167             for block_data in data['chain']:
    --> 168                 block = Block(
        169                     block_data['index'],
        170                     block_data['transactions'],
    
    TypeError: Block.__init__() takes 6 positional arguments but 7 were given
    

    To fix it , you should add an optional argument signature to the __init__ method of the Block class :

    class Block:
    
        def __init__(self, index, transactions, timestamp, previous_hash, data, signature=None):
            self.index = index
            self.transactions = transactions
            self.timestamp = timestamp
            self.previous_hash = previous_hash
            self.hash = self.previous_hash
            self.data = data
            self.nonce = 0
            self.signature = signature
    

    Here is the output :

    keys generated and saved succesfully
    anahtarlar yuklendi.
    Private RSA key at 0x78BAA098DD20
    Public RSA key at 0x78BAA0A63FD0
    anahtarlar yuklendi.
    Can't verify chain integrityl!!!
    <__main__.Block object at 0x78baa098eb30>
    <__main__.Block object at 0x78baa098eb30>
    anahtarlar yuklendi.
    zincir kaydedildi!
    Block mined successfully. Block index: 6