DEV Community

Cover image for Simple Code for Blockchain using python
Nichervan Essa
Nichervan Essa

Posted on

Simple Code for Blockchain using python

import hashlib

class Block:
def init(self, data, previous_hash):
self.data = data
self.previous_hash = previous_hash
self.hash = self.calculate_hash()

def calculate_hash(self):
    hash_digest = hashlib.sha256()
    hash_digest.update(str(self.data).encode('utf-8'))
    hash_digest.update(str(self.previous_hash).encode('utf-8'))
    return hash_digest.hexdigest()
Enter fullscreen mode Exit fullscreen mode

def create_genesis_block():
return Block('Genesis block', '0')

def next_block(previous_block):
return Block('Block 2', previous_block.hash)

genesis_block = create_genesis_block()
block_1 = next_block(genesis_block)
block_2 = next_block(block_1)

print(genesis_block.hash)
print(block_1.hash)
print(block_2.hash)

Top comments (2)

Collapse
 
nichervanessa profile image
Nichervan Essa

If you have any question or additional coding you can comments below the posts.

Collapse
 
parth51199 profile image
parth51199

What are some other applications of blockchain technology that could be implemented in Python?