Python Blockchain – Introduction

Python Blockchain – Introduction ”; Previous Next In the tutorial on Blockchain, we have learnt in detail about the theory behind blockchain. The blockchain is the fundamental building block behind the world’s most popular digital currency Bitcoin. The tutorial deeply dealt with the intricacies of Bitcoin explaining fully the blockchain architecture. The next step is to build our own blockchain. Satoshi Nakamoto created the first virtual currency in the world called Bitcoin. Looking at the success of Bitcoin, many others created their own virtual currencies. To name a few − Litecoin, Zcash, and so on. Now, you may also like to launch your own currency. Let us call this as TPCoin (TutorialsPoint Coin). You will write a blockchain to record all transactions that deal with TPCoin. The TPCoin can be used for buying Pizzas, Burgers, Salads, etc. There may be other service providers who would join your network and start accepting TPCoin as the currency for giving out their services. The possibilities are endless. In this tutorial, let us understand how to construct such a system and launch your own digital currency in the market. Components Involved in Blockchain Project Development The entire blockchain project development consists of three major components − Client Miners Blockchain Client The Client is the one who will buy goods from other vendors. The client himself may become a vendor and will accept money from others against the goods he supplies. We assume here that the client can both be a supplier and a recipient of TPCoins. Thus, we will create a client class in our code that has the ability to send and receive money. Miner The Miner is the one who picks up the transactions from a transaction pool and assembles them in a block. The miner has to provide a valid proof-of-work to get the mining reward. All the money that miner collects as a fee will be for him to keep. He may spend that money on buying goods or services from other registered vendors on the network, just the way a Client described above does. Blockchain Finally, a Blockchain is a data structure that chains all the mined blocks in a chronological order. This chain is immutable and thus temper-proof. You may follow this tutorial by typing out the code presented in each step in a new Jupyter notebook. Alternatively, you may download the entire Jupyter notebook from www.anaconda.com. In the next chapter, we will develop a client that uses our blockchain system. Print Page Previous Next Advertisements ”;

Creating Multiple Transactions

Creating Multiple Transactions ”; Previous Next The transactions made by various clients are queued in the system; the miners pick up the transactions from this queue and add it to the block. They will then mine the block and the winning miner would have the privilege of adding the block to the blockchain and thereby earn some money for himself. We will describe this mining process later when we discuss the creation of the blockchain. Before we write the code for multiple transactions, let us add a small utility function to print the contents of a given transaction. Displaying Transaction The display_transaction function accepts a single parameter of transaction type. The dictionary object within the received transaction is copied to a temporary variable called dict and using the dictionary keys, the various values are printed on the console. def display_transaction(transaction): #for transaction in transactions: dict = transaction.to_dict() print (“sender: ” + dict[”sender”]) print (”—–”) print (“recipient: ” + dict[”recipient”]) print (”—–”) print (“value: ” + str(dict[”value”])) print (”—–”) print (“time: ” + str(dict[”time”])) print (”—–”) Next, we define a transaction queue for storing our transaction objects. Transaction Queue To create a queue, we declare a global list variable called transactions as follows − transactions = [] We will simply append each newly created transaction to this queue. Please note that for brevity, we will not implement the queue management logic in this tutorial. Creating Multiple Clients Now, we will start creating transactions. First, we will create four clients who will send money to each other for obtaining various services or goods from others. Dinesh = Client() Ramesh = Client() Seema = Client() Vijay = Client() At this point, we have four clients called Dinesh, Ramesh, Seema, and Vijay. We currently assume that each of these clients hold some TPCoins in their wallets for transacting. The identity of each of these clients would be specified by using the identity property of these objects. Creating First Transaction Now, we initiate our first transaction as follows − t1 = Transaction( Dinesh, Ramesh.identity, 15.0 ) In this transaction Dinesh sends 5 TPCoins to Ramesh. For transaction to be successful, we will have to ensure that Dinesh has sufficient money in his wallet for this payment. Note that, we will need a genesis transaction to start TPCoin circulation in the system. You will write the transaction code for this genesis transaction very shortly as you read along. We will sign this transaction using Dinesh’s private key and add it to the transaction queue as follows − t1.sign_transaction() transactions.append(t1) After the first transaction made by Dinesh, we will create several more transactions between different clients that we created above. Adding More Transactions We will now create several more transactions, each transaction given out a few TPCoins to another party. When somebody spends money, it is not necessary that he has to check for sufficient balances in this wallet. The miner in anyway would be validating each transaction for the balance that the sender has while initiating the transaction. In case of insufficient balance, the miner will mark this transaction as invalid and would not add it to this block. The following code creates and adds nine more transactions to our queue. t2 = Transaction( Dinesh, Seema.identity, 6.0 ) t2.sign_transaction() transactions.append(t2) t3 = Transaction( Ramesh, Vijay.identity, 2.0 ) t3.sign_transaction() transactions.append(t3) t4 = Transaction( Seema, Ramesh.identity, 4.0 ) t4.sign_transaction() transactions.append(t4) t5 = Transaction( Vijay, Seema.identity, 7.0 ) t5.sign_transaction() transactions.append(t5) t6 = Transaction( Ramesh, Seema.identity, 3.0 ) t6.sign_transaction() transactions.append(t6) t7 = Transaction( Seema, Dinesh.identity, 8.0 ) t7.sign_transaction() transactions.append(t7) t8 = Transaction( Seema, Ramesh.identity, 1.0 ) t8.sign_transaction() transactions.append(t8) t9 = Transaction( Vijay, Dinesh.identity, 5.0 ) t9.sign_transaction() transactions.append(t9) t10 = Transaction( Vijay, Ramesh.identity, 3.0 ) t10.sign_transaction() transactions.append(t10) When you run the above code, you will have ten transactions in the queue for the miners to create their blocks. Dumping Transactions As a blockchain manager, you may periodically like to review the contents of transaction queue. For this purpose, you can use the display_transaction function that we developed earlier. To dump all transactions in the queue, just iterate the transactions list and for each referenced transaction, call the display_transaction function as shown here − for transaction in transactions: display_transaction (transaction) print (”————–”) The transactions are separated by a dashed line for distinction. If you run the above code, you would see the transaction list as shown below − sender: 30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c49214 4a9f463480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329e c86794b04d773eb4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b 47e5157f8fe56c2ce3279c657f9c6a80500073b0be8093f748aef667c03e64f04f84d311 c4d866c12d79d3fc3034563dfb0203010001 —– recipient: 30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e 674abe7abdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8ad d126b6e1a1308fb98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa93977 04de625d1836d3f42c7ee5683f6703259592cc24b09699376807f28fe0e00ff882974484 d805f874260dfc2d1627473b910203010001 —– value: 15.0 —– time: 2019-01-14 16:18:01.859915 —– ————– sender: 30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c49214 4a9f463480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329e c86794b04d773eb4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b 47e5157f8fe56c2ce3279c657f9c6a80500073b0be8093f748aef667c03e64f04f84d311 c4d866c12d79d3fc3034563dfb0203010001 —– recipient: 30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae14 3cbe59b3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fb d9ee74b9e7ea12334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0 961b4f212d1fd5b5e49ae09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d0623 75799742a359b8f22c5362e5650203010001 —– value: 6.0 —– time: 2019-01-14 16:18:01.860966 —– ————– sender: 30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e 674abe7abdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8ad d126b6e1a1308fb98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa93977 04de625d1836d3f42c7ee5683f6703259592cc24b09699376807f28fe0e00ff882974484 d805f874260dfc2d1627473b910203010001 —– recipient: 30819f300d06092a864886f70d010101050003818d0030818902818100cba097c0854876 f41338c62598c658f545182cfa4acebce147aedf328181f9c4930f14498fd03c0af6b0cc e25be99452a81df4fa30a53eddbb7bb7b203adf8764a0ccd9db6913a576d68d642d8fd47 452590137869c25d9ff83d68ebe6d616056a8425b85b52e69715b8b85ae807b84638d8f0 0e321b65e4c33acaf6469e18e30203010001 —– value: 2.0 —– time: 2019-01-14 16:18:01.861958 —– ————– For brevity, I have printed only first few transactions in the list. In the above code, we print all transactions beginning with the very first transaction except for the genesis transaction which was never added to this list. As the transactions are added to the blocks periodically, you will generally be interested in viewing only the list of transactions which are yet to be mined. In that case, you will need to create an appropriate for loop to iterate through the transactions which are not yet mined. So far, you have learned how to create clients, allow them to among themselves and maintain a queue of the pending transactions which are to be mined. Now, comes the most important part of this tutorial and that is creating a blockchain itself. You will learn this in the next lesson. Print Page Previous Next Advertisements ”;

Blockchain – Developing Client

Python Blockchain – Developing Client ”; Previous Next A client is somebody who holds TPCoins and transacts those for goods/services from other vendors on the network including his own. We should define a Client class for this purpose. To create a globally unique identification for the client, we use PKI (Public Key Infrastructure). In this chapter, let us talk about this in detail. The client should be able to send money from his wallet to another known person. Similarly, the client should be able to accept money from a third party. For spending money, the client would create a transaction specifying the sender’s name and the amount to be paid. For receiving money, the client will provide his identity to the third party − essentially a sender of the money. We do not store the balance amount of money the client holds in his wallet. During a transaction, we will compute the actual balance to ensure that the client has sufficient balance to make the payment. To develop the Client class and for the rest of the code in the project, we will need to import many Python libraries. These are listed below − # import libraries import hashlib import random import string import json import binascii import numpy as np import pandas as pd import pylab as pl import logging import datetime import collections In addition to the above standard libraries, we are going to sign our transactions, create hash of the objects, etc. For this, you will need to import the following libraries − # following imports are required by PKI import Crypto import Crypto.Random from Crypto.Hash import SHA from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 In the next chapter, let us talk about client class. Print Page Previous Next Advertisements ”;

Python Blockchain – Home

Python Blockchain Tutorial PDF Version Quick Guide Resources Job Search Discussion Blockchain is the current buzz that is dominating the software development trends. The development and designing of Blockchain involves three major components: client, miner and blockchain. This tutorial is aimed to give you a crisp understanding of the process of building your own blockchain. Audience Any programming enthusiast who wants to keep in pace with the recent trend of Blockchain development can gain from this tutorial. If you are a learner interested to learn the basics of Blockchain Development, this tutorial aptly suits your needs. Prerequisites This tutorial is written assuming that the learner has an idea on programming in Python and a basic idea on Blockchain. If you are new to any of these concepts, we suggest you to pick tutorials based on these concepts first before you plunge into this tutorial. Print Page Previous Next Advertisements ”;

Blockchain – Scope & Conclusion

Python Blockchain – Scope and Conclusion ”; Previous Next In this tutorial, we have learnt how to construct a blockchain project in Python. There are many areas where you need to add further functionality to this project. For instance, you will need to write functions for managing the transactions queue. After the transactions are mined and the mined block is accepted by the system, they need not be stored any more. Also, the miners would certainly prefer to pick up the transactions with the highest fee. At the same time, you will have to ensure that the transactions with low or no fee would not starve forever. You will need to develop algorithms for managing the queue. Also, the current tutorial does not include the client interface code. You will need to develop this for both normal clients and the miners. The full-fledged blockchain project would run into several more lines of code and is beyond the scope of this tutorial. The interested reader may download the bitcoin source for further study. Conclusions This crisp tutorial should get you started on creating your own blockchain project. For full-fledged blockchain project development, you can learn more from the bitcoin source. For larger commercial or non-commercial projects, you may consider using Ethereum − a ready to use blockchain app platform. Print Page Previous Next Advertisements ”;

Blockchain – Transaction Class

Python Blockchain – Transaction Class ”; Previous Next In this chapter, let us create a Transaction class so that a client will be able to send money to somebody. Note that a client can be both a sender or a recipient of the money. When you want to receive money, some other sender will create a transaction and specify your public address in it. We define the initialization of a transaction class as follows − def __init__(self, sender, recipient, value): self.sender = sender self.recipient = recipient self.value = value self.time = datetime.datetime.now() The init method takes three parameters − the sender’s public key, the recipient’s public key, and the amount to be sent. These are stored in the instance variables for use by other methods. Additionally, we create one more variable for storing the time of transaction. Next, we write a utility method called to_dict that combines all the four above-mentioned instance variables in a dictionary object. This is just to put the entire transaction information accessible through a single variable. As you know from the earlier tutorial that the first block in the blockchain is a Genesis block. The Genesis block contains the first transaction initiated by the creator of the blockchain. The identity of this person may be kept a secret like in the case of Bitcoins. So when this first transaction is created, the creator may just send his identity as Genesis. Thus, while creating the dictionary, we check if the sender is Genesis and if so we simply assign some string value to the identity variable; else, we assign the sender’s identity to the identity variable. if self.sender == “Genesis”: identity = “Genesis” else: identity = self.sender.identity We construct the dictionary using following line of code return collections.OrderedDict({ ”sender”: identity, ”recipient”: self.recipient, ”value”: self.value, ”time” : self.time}) The entire code for the to_dict method is shown below − def to_dict(self): if self.sender == “Genesis”: identity = “Genesis” else: identity = self.sender.identity return collections.OrderedDict({ ”sender”: identity, ”recipient”: self.recipient, ”value”: self.value, ”time” : self.time}) Finally, we will sign this dictionary object using the private key of the sender. As before, we use the built-in PKI with SHA algorithm. The generated signature is decoded to get the ASCII representation for printing and storing it in our blockchain. The sign_transaction method code is shown here − def sign_transaction(self): private_key = self.sender._private_key signer = PKCS1_v1_5.new(private_key) h = SHA.new(str(self.to_dict()).encode(”utf8”)) return binascii.hexlify(signer.sign(h)).decode(”ascii”) We will now test this Transaction class. Testing Transaction Class For this purpose, we will create two users, called Dinesh and Ramesh. Dinesh will send 5 TPCoins to Ramesh. For this first we create the clients called Dinesh and Ramesh. Dinesh = Client() Ramesh = Client() Remember that when you instantiate a Client class, the public and private keys unique to the client would be created. As Dinesh is sending payment to Ramesh, he will need the public key of Ramesh which is obtained by using the identity property of the client. Thus, we will create the transaction instance using following code − t = Transaction( Dinesh, Ramesh.identity, 5.0 ) Note that the first parameter is the sender, the second parameter is the public key of the recipient and the third parameter is the amount to be transferred. The sign_transaction method retrieves the sender’s private key from the first parameter for singing the transaction. After the transaction object is created, you will sign it by calling its sign_transaction method. This method returns the generated signature in the printable format. We generate and print the signature using following two lines of code − signature = t.sign_transaction() print (signature) When you run the above code, you will see the output similar to this − 7c7e3c97629b218e9ec6e86b01f9abd8e361fd69e7d373c38420790b655b9abe3b575e343c7 13703ca1aee781acd7157a0624db3d57d7c2f1172730ee3f45af943338157f899965856f6b0 0e34db240b62673ad5a08c8e490f880b568efbc36035cae2e748f1d802d5e8e66298be826f5 c6363dc511222fb2416036ac04eb972 Now as our basic infrastructure of creating a client and a transaction is ready, we will now have multiple clients doing multiple transactions as in a real life situation. Print Page Previous Next Advertisements ”;