Building a Blockchain using PythonBefore we start building a blockchain using the Python programming language, let us go back to the very beginning. In 2008, an author (or authors) under the pseudonym Satoshi Nakamoto released a white paper describing a purely peer-to-peer version of electronic cash. Exclusive to this electronic cash system, transactions wouldn't have to depend on third-party verifications to ensure the security of every transaction. Instead, every transaction would be timestamped, then hashed into an ongoing chain of proof-of-work based on the hash. Thus, what are hashing and proof-of-work? We will introduce these concepts in the following tutorial and understand how they establish the groundwork for an encrypted electronic cash system or cryptocurrency. Satoshi Nakamoto described the particular form of electronic currency in his (or her) paper became Bitcoin, the first cryptocurrency. However, how is this useful when attempting to build a blockchain using Python? In the following tutorial, we will understand the same. Understanding the BlockchainThe system that Bitcoin depends upon - a growing list of records (that is, blocks) that are connected to one another - is called Blockchain. Bitcoin was the first successful application of this system, and soon after its growth in fame, other cryptocurrencies were established on the same beliefs. However, this system is not limited to collecting financial information. Instead, the stored type of data is inconsequential and independent of the Blockchain network. Fundamentally, the data stored in a blockchain should have consisted of the following characteristics:
A blockchain is an open-source application that is shared between thousands of computers. These computers follow a set of rules in order to track money that has been sent from accounts tied to the blockchain software. These qualities are mandatory in order to maintain the Blockchain's integrity and the network security within which the transactions occur. Every block is a set of data that says, for instance, "Tom paid Harry $500 on Tuesday, 14th." On the Blockchain, we can send the money without using a bank. In order to illustrate the simplicity and elegance of such a system and to describe the nuances, we will understand the process of creating our very own Blockchain using the Python programming language. For the following project, we will only need Python. Also, remember that our Blockchain will be a simplified, high-level introduction. We won't be building an entire Bitcoin blockchain. Instead, we will be creating functions in order to add blocks, transactions, and encryption so that our data is temper-proof. Let's get started. Building a blockchain in PythonWe have divided the process of building a blockchain into several steps for better understanding. These steps are as follows: Step 1: Creating a Blockchain class Step 2: Writing a Function to build New Blocks Step 3: Writing Functions to create New Transactions and get the Last Block Step 4: Writing a Function to "Hash" the Blocks Step 5: Creating a New Blockchain and Sending some money Now, we will discuss these steps in the following sections. Creating a Blockchain classWe will start by importing the required libraries. In this case, we will be needing the hashlib library for the encryption, the JSON library for our blocks formatting, and the time library for the timestamp of each block. We will then be creating a class and initializing the following variables:
Let us consider the following snippet of code demonstrating the same. Example: Explanation: In the above snippet of code, we have imported the required libraries and created the Block_chain class where we initialized the different variables described earlier. Writing a Function to construct New BlocksNow that we have initialized an empty chain, let us begin inserting blocks into it. We will then define the JSON object with the following properties:
Once we add the above properties to the new block, we will include them in the chain. Initially, we empty the pending list of transactions and then add the new block to the self.chain and return it. Let us understand the above using the snippet of code shown below. Example: Explanation: The code begins by importing essential libraries: hashlib, json, and time. These libraries are fundamental for the operations within a blockchain. hashlib provides the SHA-256 hashing function, which ensures the security and immutability of each block. The json library is used to serialize Python objects into a consistent JSON format, allowing us to create a reliable and standardized representation of each block. The time function is employed to timestamp each block, recording when it was created. The Blockchain class is then defined, representing the core structure of the blockchain. In the __init__ method, two lists are initialized: self.chain to store the sequence of blocks and self.pendingTransactions to hold transactions that are waiting to be added to the next block. The newBlock method is responsible for creating a new block and adding it to the blockchain. It takes two arguments: the_proof, which is a value that validates the block, and previousHash, which links this block to the previous one. Inside this method, a dictionary called the_block is created, containing the block’s index, timestamp, transactions, proof, and the hash of the previous block. Once the block is created, the list of pending transactions is cleared, as they are now included in the block, and the new block is appended to the blockchain. The method then returns the newly created block. The hash method generates a SHA-256 hash for a given block. It first converts the block into a JSON string with keys sorted to ensure consistent ordering. This string is then encoded and passed through the SHA-256 function to produce a unique hash that identifies the block. Finally, the example usage section demonstrates how to create a blockchain instance and add a new block to it using the newBlock method. This simple example highlights the basic operations of creating and appending blocks in a blockchain. Let us consider the following snippet of code demonstrating the same. Example: Explanation: In the above snippet of code, we defined the method as lastBlock(), which returns the most recent block added. We have then defined the function as newTransaction(), within which we have defined the JSON object as the_transaction and included the addresses to the sender, recipient, and amount. We added this JSON object to the pendingTransaction and returned the last block. Writing a Function to "Hash" the BlocksNow, let us add Cryptography to the program. As we know, Bitcoin and many other blockchains utilize SHA-256, an encryption hash function, which accepts some text string (stored as a Unicode value) and spits out a 64-character long encrypted string. In a blockchain, the text that we encrypt is considered a block. For instance, the encrypted string, or "hash", of the Bitcoin genesis block appears like this: fbc13b85c4ade52e2def26eae950f3b55b174df887ad0f0fb5ebfd56881f7fcb Blockchains are considered tamper-proof as every block consists of a copy of the previous hash of the block. And as the new hash is derived from the last block, we cannot change any aspect of a block without altering every single hash in front of it. Suppose that someone downloaded the Bitcoin blockchain to their computer and wrote "Satoshi sends Alex 7,236,000 Bitcoin!" into the genesis block and broadcasted this to the Bitcoin network and claimed that he is a secret billionaire. However, as soon as any self-respecting miner compares their current copy of the blockchain, especially the hash values stored in each block, with his copy of the chain, they will notice that he is a liar, refusing to validate it and run him off the network. We will define the method that accepts the new block and alter its key/value pairs into strings. We will then convert that string into Unicode, which we will pass into the SHA256 method from the hashlib library and create a hexadecimal string from its return value. We will then return the new hash. Let us understand the same using the following snippet of code. Example: Explanation: In the above snippet of code, we have defined the hash() function and accepts one block and turned them into Strings and then into Unicode for hashing. We have then used the SHA256() function for encryption and then translated the Unicode into a Hexadecimal string. Creating a New Blockchain and Sending some MoneySince we have created a class for the blockchain and included various methods in order to build a new block and a new transaction, along with a custom method utilized to hash any block with SHA256 encryption, let us begin building the chain. We will initialize an instance of the Block_chain class and perform some dummy transactions. Make sure to list them in some blocks that we include in the chain. Let us consider the following snippet of code demonstrating the same. Example: Explanation: We have instantiated the Block_chain() class in the above snippet of code. We have then performed some transactions and printed them for the users. Now, let us have a look at a complete code for the project of building blockchain using Python. Complete Project CodeFile: buildingBlockchain.py Output: Genesis block: [ {'index': 1, 'timestamp': 1640067926.584454, 'transactions': [], 'proof': 100, 'previous_hash': 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks.'}, {'index': 2, 'timestamp': 1640067926.584454, 'transactions': [ {'sender': 'Satoshi', 'recipient': 'Alex', 'amount': '10 BTC'}, {'sender': 'Alex', 'recipient': 'Satoshi', 'amount': '2 BTC'}, {'sender': 'Satoshi', 'recipient': 'James', 'amount': '10 BTC'} ], 'proof': 10123, 'previous_hash': 'a1b0cf063d43989421eb4b28d9be8f82c2e2e9e40bc9814321e3cbb70b00530a'}, {'index': 3, 'timestamp': 1640067926.584454, 'transactions': [ {'sender': 'Alex', 'recipient': 'Lucy', 'amount': '2 BTC'}, {'sender': 'Lucy', 'recipient': 'Justin', 'amount': '1 BTC'}, {'sender': 'Justin', 'recipient': 'Alex', 'amount': '1 BTC'} ], 'proof': 10384, 'previous_hash': '23699917fdcc013a85bbb5872251768e976bfcc2cd8403565c04970bca24a871'} ] Explanation: In the above output, we can observe that our blockchain contains three blocks right now: The genesis block (with an index of 1 and no transactions), in addition to the 2 that we added ourselves. We can also notice that the encrypted hashes (derived from every preceding block) and the timestamps do not match each other. Granted, the computer constructed each block almost simultaneously as we executed the program and generated blocks at almost the same time; however, Bitcoin blocks are created approximately every ten minutes. Does anyone of us notice any account balances? Blockchains are not banks, and here is a good example to distinguish between the two. A cryptocurrency wallet will estimate the balance by scanning the complete chain and summing up how many coins we received and spent. We do not have to rely on a bank to tell us the amount present in the account. We are only trusting the network instead of one mega-corporation. Isn't it fascinating? Summing UpIn the following tutorial, we have successfully built a blockchain that we can fill with blocks full of transactions of cryptocurrency; however, this is not a secure network. First, we created a block any time somebody calls newBlock(), and there are no conditions. The newBlock() method requires a parameter called proof; however, that can be anything in our case. It can either be by a number or string saying, "hello world", or literally anything. In the network of Bitcoin, there is a consensus mechanism in a place called Proof of Work, which illustrates the rules by which security is achieved. A proof is a random number that is very difficult to find unless we have some dedicated high-performance machines working around the clock. There are many other details we are missing, such as fees for the miners to collect, a count of the transaction, public/private key, a Merkle tree structure, and more. However, the above walkthrough was helpful for us as a fundamental example of the moving segments in a blockchain. Next TopicHuffman Coding using Python |