DEV Community

Arish Sethi
Arish Sethi

Posted on

Building a Basic Blockchain in Python: My Journey and Key Takeaways!

Image description
**
Blockchain technology always fascinated me, so I decided to dive in and build my own mini blockchain using Python. Here's what I learned along the way**

Blockchain is a technology that allows for the secure, transparent, and permanent recording of data and transactions across a network.

My purpose of learning blockchain is to get a good knowledge of how the blocks work and what is the significance of POW (proof of work) and cryptography .As I am always intrested in blockchain because of its significant growth in the current few years.it also help me to improve my python skills.

KEY FEATURES OF BLOCKCHAIN:-

Chaining Blocks

*Each block in your blockchain contains:

*Data or transactions (e.g., sender, receiver, amount).

*A unique identifier called a hash, generated from the block's data.

*The hash of the previous block, linking the blocks together.

This ensures that the blocks are connected in a secure and sequential manner. If someone tries to change the data in one block, it would break the chain because the hash links wouldn’t match anymore.

** Proof of Work**

*To add a new block to the blockchain, your project likely includes a

*mining process, which involves solving a mathematical puzzle.
This puzzle ensures that:

*Adding a block takes some computational effort, making it hard to tamper with the chain.

*For example, the hash of a valid block must start with a specific number of zeroes (e.g., "0000").

This process makes the blockchain secure by requiring work to add blocks, preventing spam or malicious blocks.

Hashing

*Hashing converts the block’s data into a fixed-size string of characters (a hash).

*Your project likely uses a hashing algorithm (e.g., SHA-256) to generate this hash.

*The hash is unique to the block's data, like a digital fingerprint. Even a tiny change in the block’s data will produce a completely different hash.

For example:

Block data: {"amount": 5, "sender": "Alice", "receiver": "Bob"}
Hash: d2d2d2c6a8e9a6df13b54ff2c4da9ab9e2f4a8b9e8c1d6a9b4ff0d2c

API Testing Using Postman

Your blockchain likely includes API endpoints to interact with the chain.
Endpoints allow you to:

*Add transactions: Users can submit data (e.g., transactions).

*Mine new blocks: Solve the proof of work puzzle and add the block.

*View the blockchain: Retrieve the chain's current state to verify its contents.

Using Postman, you tested these endpoints to ensure they work as expected.

CHALLENGES I FACED AND HOW I OVERCOME THAT:-
my first challenge is to understand what these term means like hashing, proof of work and what is the chain in the block[which I explained it to you above.] so to overcome this problem I use ChatGPT and Gemini to get a handful of knowledge about blockchain key components AI helps me a lot.
My second problem is the implementation of proof of work as it is very tricky for me to get used to with proof of work [pow] algorithm but as I searched it in Google and asked from AI I started learning things and can apply that in my project. I set a condition where the hash must start with '0000', ensuring security.

I have used Postman for API testing there are some images which shows you how and what I have done
the first method is to create a new request (HTTP) in Postman.
Image description
step-2 after getting chain details we now have to create a new transaction.
Image description

we have to change get method to post and then give the request (provided in image),after this you have to go in headers section where in key column we have to write content-type and in value column, application/json.then switch to body choose raw format and set the format to json. In text box write the content given in the image.

step-3 mining a new block.

Image description

*code snippets for some important topics of blockchain:- *

making new block

    def new_block(self, proof, previous_hash=None):
        block = {
            'index': len(self.chain) + 1,
            'timestamp': time(),
            'transactions': self.current_transactions,
            'proof': proof,
            'previous_hash': previous_hash or self.hash(self.chain[-1] if self.chain else '0'),
        }
Enter fullscreen mode Exit fullscreen mode

*making new transaction
*

    def new_transaction(self, sender, recipient, amount):
        # Add a new transaction to the list of transactions
        self.current_transactions.append({
            'sender': sender,
            'recipient': recipient,
            'amount': amount,
        })
        return self.last_block['index'] + 1  # Return the index of the block that will hold this transaction
Enter fullscreen mode Exit fullscreen mode

for hashing

 @staticmethod
    def hash(block):
        # Creates a SHA-256 hash of a Block
        block_string = json.dumps(block, sort_keys=True).encode()
        return hashlib.sha256(block_string).hexdigest()
Enter fullscreen mode Exit fullscreen mode

proof of work mechanism

def proof_of_work(self, last_proof):
        proof = 0
        while self.valid_proof(last_proof, proof) is False:
            proof += 1
        return proof

    @staticmethod 

def valid_proof(last_proof, proof):
        # Validates the Proof by checking if hash(last_proof, proof) has 4 leading zeroes
        guess = f"{last_proof}{proof}".encode()
        guess_hash = hashlib.sha256(guess).hexdigest()
        return guess_hash[:4] == "0000"
Enter fullscreen mode Exit fullscreen mode

Check out my GitHub repo for the full code and documentation and also for more interesting projects like this. I'd love to hear your feedback or ideas for improvement!" -https://github.com/Arish2008/CodeSphere

I’m always looking to improve and learn. If you have suggestions, ideas, or improvements, drop a comment below or create an issue on GitHub.

🤝 Let’s Collaborate!

Are you working on something exciting in AI, web development, blockchain, or Python? I’d love to connect and collaborate. You can reach me on:

  • Twitter: [@arish_seth]

Thank you for reading, and I can’t wait to hear your thoughts! 🚀

Top comments (0)