What is Blockchain?

In 2008 the Bitcoin paper was published by an unknown individual or group named Satoshi Nakamoto. Bitcoin came out as a peer-to-peer version of electronic cash that allowed transactions without going through centralized institutions (banks). Most people don’t know that in that same paper, Satoshi defined a distributed way of storing information, nowadays known as Blockchain. To put it simply, Blockchain is a shared, immutable digital ledger that stores transactions over a decentralized network of computers. We can divide Blockchain into two simple terms:

Block: A space where we store transactions Chain: A set of linked records

This defines Blockchain as a chain of linked blocks, where each block stores a transaction made with specific parameters. Each block is built on top of another block, creating an irreversible chain of blocks. In other words, every block depends on another. This turns out into a robust and immutable system in which anyone with the correct permissions can review integrity. Blockchain introduces an interesting set of features:

History immutability Information persistency No errors with stored data

A lot of systems currently rely on Blockchain, such as cryptocurrencies, asset transfer (NFTs), and possibly in the near future, voting. It’s worth mentioning that a Python Blockchain has not to be a complex program with thousands of lines of code. At its core, it would be a list of transactions linked to one another. Of course, this was a brief explanation, but if you want a full guide, we’ve produced a complete tutorial on Blockchain for beginners. Make sure to check it out. Without further delay, let’s build a simple Blockchain with Python.

Building a Blockchain With Python

Before starting, let’s define what we’re going to do in this tutorial:

Build simple Blockchain system written in Python Use our Blockchain with preestablished transactions represented as strings Test the immutability of our Blockchain

We’re not going to use JSON but Python lists. This will let us simplify the process and focus on applying the key concepts of a Blockchain. What you’ll need to follow this tutorial:

Understanding of classes and methods in Python Basic usage of command line

Creating the Block class

Open your favorite code editor and create a main.py file. This will be the file we’ll work with. Now, import hashlib, a module that lets us create one-way encrypted messages. Cryptography techniques like hashing make Blockchain create secure transactions. A hash function is an algorithm that takes some data (usually an encoded string) and returns a unique identifier, often named “digest” or “signature.” This last part is vital; with a hash function, a slight difference in the input produces a radically different identifier as an output. We’ll see this in action later on. For now, just import the built-in module hashlib: This module includes most of the hashing algorithms you’ll need. Just keep in mind we’ll be using the hashlib.sha256() function. Now, let’s get into the GeekCoinBlock, our totally original blockchain name. I know this may result in a clunky piece of code. Let’s break down each part in the next section.

GeekCoinBlock Explanation

First, we create a class named GeekCoinBlock, a wrapper for objects that will have certain characteristics (attributes) and behaviors (methods). Then we define the init method (also named constructor), which gets invoked each time a GeekCoinBlock object gets created. This method has three parameters:

self (the instance of each object) previous_block_hash (a reference to the previous block) transaction_list (a list of transactions made in the current block).

We store the previous hash and transaction list and create an instance variable block_data as a string. This doesn’t happen with real cryptocurrencies, in which we store that kind of data as another hash, but for simplicity purposes, we’ll store every block of data as a string. Finally, we create the block_hash, which other blocks will use to continue the chain. Here’s where hashlib comes in handy; instead of creating a custom hash function, we can use the pre-built sha256 to make immutable blocks. This function receives encoded strings (or bytes) as parameters. That’s why we’re using the block_data.encode() method. After that, we call hexdigest() to return the encoded data into hexadecimal format. I know all of this can be overwhelming, so let’s play with hashlib on a Python shell. As you can see, a slight change in the input like “Python is great” to “Python is not great” can produce a totally different hash. This has all to do with Blockchain integrity. If you introduce some little change into a blockchain, its hash will dramatically change. This is the reason why the saying “You can’t corrupt a Blockchain” is true.

Using our Block Class

We’ll build an entire Blockchain class later, but for now, let’s use our Block class to create a chain of blocks (Blockchain). In the same file, create a couple of transactions made up of simple strings stored in variables, for example: Now, build the first block of our Blockchain by using the GeekCoinBlock class and print its attributes. Take into account that the previous_hash parameter of the genesis block (first block that precedes other blocks) will always be some arbitrary string or hash, in this case, “firstblock.” Then, we do the same with the second block, but passing the first block hash as the previous_hash argument. Let’s run and analyze the output we get from this piece of code. Once again, type in your terminal: For now, you only see text and some 64 character hashes, but this resumes pretty much the mechanism of a Blockchain. You start with a genesis block, the base of all other blocks. Anyone can validate the chain’s integrity, and that’s why a Blockchain is such a secure system. For example, if we slightly modify the content of a transaction, say: We see a dramatic change in the hash of the blocks. You can see the current project on this GitHub repo.

Coding a Blockchain

It’s not that clever to base our system integrity on hand-coded variables, so we need another approach. We have the blocks. It’s time to build a class that joins them into a Blockchain. Let’s start by deleting our previous transactions and block objects, then using the code below. This is again a huge piece of code. Let’s break down each part:

self.chain — The list where all blocks are recorded. We can access each block via list indexes. generate_genesis_block — Append the genesis or first block to the chain. The previous hash of the block is “0”, and the list of transactions is simply “Genesis Block.” create_block_from_transaction — This allows us to append blocks to the chain with just a list of transactions. It would be very annoying to create a block manually every time we want to record a transaction display_chain — Prints the chain of blocks with a for loop last_block — A property that lets us access the last element of the chain. We used it on the create_block_from_transaction method.

Let’s test this Blockchain up. Now, run the main.py file. Congratulations! 🙌 You just created a simple Python Blockchain from scratch. You can now strengthen the Blockchain immutability by using getters and setters and implement other features like proof-of-work, mining, or any other concept we explained in the Bitcoin Mining fundamentals article.

Conclusion

Blockchain is the technology behind Bitcoin, Etherium, and every other cryptocurrency out there. In this article, you learned how to create a Blockchain with Python by using hash algorithms like sha256, classes, and objects. Your challenge is to create a mining system, and why not, implement it with a REST API using frameworks like Django or Flask. Many people are making fortunes from cryptocurrencies. Just imagine what you could do if you create one by yourself. 🤑 Keep Coding! 👨‍💻

How to Create a Blockchain with Python  - 50How to Create a Blockchain with Python  - 98How to Create a Blockchain with Python  - 65How to Create a Blockchain with Python  - 90How to Create a Blockchain with Python  - 80How to Create a Blockchain with Python  - 16How to Create a Blockchain with Python  - 90How to Create a Blockchain with Python  - 33How to Create a Blockchain with Python  - 33How to Create a Blockchain with Python  - 10How to Create a Blockchain with Python  - 25How to Create a Blockchain with Python  - 67How to Create a Blockchain with Python  - 95How to Create a Blockchain with Python  - 38How to Create a Blockchain with Python  - 10How to Create a Blockchain with Python  - 70How to Create a Blockchain with Python  - 79How to Create a Blockchain with Python  - 96How to Create a Blockchain with Python  - 56How to Create a Blockchain with Python  - 30How to Create a Blockchain with Python  - 96How to Create a Blockchain with Python  - 57How to Create a Blockchain with Python  - 11How to Create a Blockchain with Python  - 13