Blockchain And How To Build One

in #blockchain7 years ago (edited)

A hunter’s guide to one of the most influential technologies on earth

“Any sufficiently advanced technology is indistinguishable from magic “— Arthur C. Clarke

What is a Blockchain?


Essentially, we can say, the Blockchain is a way we store information using cryptographic functions, linked data structure, and certain governance protocols in a decentralized manner. Basically, that’s it. But let’s break down this simple definition using the keywords visible.

Cryptographic Functions

The blockchain uses cryptography to create hashes for data units on the blockchain. Hashes are unique long complex numbers. They are usually represented as hexadecimal generated from cryptographic algorithms. They work in a sense that when you put A in F(A). It returns X. If you do it for an infinite number of times, F(A) will still return X. Unless you change the contents of A and call it Aa. Then, when used the modified data inside F(Aa) produces a different result, for example, Y. With this, we can identify a particular piece of data as original and the other as fake. An example of such cryptographic function is the SHA-256 hash.

Linked Data Structure

Hashed information on the blockchain is stored in a linked manner. Such that each data block relies on the previous data block to create a new hash identity. Except the first data block called the genesis block. This is what we call a chain. Imagine hashed data organized in blocks. And linked together to produce a single axis called the blockchain. By this way, we realize a hereditary pattern. Because the hash identifier of a previous block added to the created block generates the hash identifier of the next data block. Hence we can witness the parent-child relationship between blocks.

Decentralized Manner

One important feature of the blockchain is how data decentralizes among the nodes. It means each node in the network has a copy of the blockchain and that enhances the security of the blockchain. Data syncs among the nodes and if for some reason, one node goes rogue, it is easy to identify and actions are taken. The more the nodes, the more secure the blockchain.

Let’s build one !

Now that we have a fair idea of what the blockchain is, why don’t we build our own blockchain solution for business use. I will use python to build. The source code can be found here. Note this part requires you to have basic programming concepts to grasp.

Case

Our business firm stores critical business documents that are vital to our clients. They cannot be tampered with. We want to take advantage of the security and distributed nature of a blockchain. This will keep our documents secure and away from loss and tampering. So we are building a new way of storing our documents on the blockchain. Which will make our storage immutable, distributed and practically uncrackable.

Design

Our blockchain is for private and business use. So it should be permission based. This means one has to be registered on the network to be able to add documents to the blockchain. Also, since we are building j small-scale solution and an experimental one. I will use very simple protocols to govern how the blockchain validates data added. I will use a protocol I came up with called the Block Limit Protocol to validate blocks. Block Limit Protocol maintains that documents in a single block should be less than 5 and shouldn’t be empty. Else the system will reject the block. Since it is permission-based, only registered users can create and submit new docs signed in their name.

The Code

from hashlib import sha256
from time import time
import json


class Blockchain:

    def __init__(self, authors, name="blockchain"):
        """
        Creates a blockchain with genesis block
        :param authors: <list> a list of registered users
        :param name: <str> name of the blockchain,default is 'blockchain'
        :return: <object> blockchain object
        """
        self.name = name
        self.authors = authors
        self.chain = []
        self.current_docs = []
        self.blocksize = 5

        # create genesis block
        genesis = self.create_block(parent_hash=1)
        self.add_block(genesis)

    @staticmethod
    def hash_it(hash_item):
        """
        Creates a hash for a block or doc item
        :param hash_item: <dict> Block item or doc item
        :return: <str> The hash value of hash item
        """
        hash_item = json.dumps(hash_item, sort_keys=True).encode()
        return sha256(hash_item).hexdigest()

    def create_doc(self, author, content):
        """
        Creates a new document
        :param author: <str> Name of author
        :param content: <str> DOcument contents
        :return: <dict> Created block
        """
        doc = {
            "author": author,
            "content": content,
            "timestamp": time(),
        }

        doc_hash = self.hash_it(doc)

        return {"doc_hash": doc_hash, "doc": doc}

    def is_valid_doc(self, doc):
        """
        Checks doc validation
        :param doc: <dict> Document
        """
        if doc["doc"]["author"] in self.authors:
            return True
        else:
            return False

    def add_doc(self, doc):
        if self.is_valid_doc(doc):
            self.current_docs.append(doc)
            print("added to docs pool")
        else:
            print("doc invalid, unregistered author")

    def create_block(self, parent_hash=None):
        """
        Creates a new block
        :param parent_hash: <str> (Optional), used once to create 
                            genesis block
        :return: <dict> Created block
        """
        block = {
            "index": len(self.chain) + 1,
            "parent_block_hash": parent_hash or self.chain[-1]["block_hash"],
            "timestamp": time(),
            "docs": self.current_docs,
        }

        block_hash = self.hash_it(block)

        return {"block_hash": block_hash, "block": block}

    def is_valid_block(self, block):
        """
        Checks if a given block passes the block limit protocol
        :param block: <dict> Block item
        :return: <bool> True for valid and False for invalid
        """
        docs_total = len(self.current_docs)
        if docs_total > 0 and docs_total <= self.blocksize:
            return True
        else:
            return False

    def add_block(self, block):
        """
        Adds created block to the blockchain if valid
        :param block: <dict> Block item
        :return: <str> Block item info if valid and warning if not
        """
        if self.is_valid_block(block):
            self.chain.append(block)
            self.current_docs = []
            return "success \n {}".format(block)
        else:
return "invalid block"

Creating the blockchain

I have created a blueprint for creating our blockchain. On instantiation, the creator must register authors/users since it is permission-based. Also, we can give it a name. While we set by default the block size to 5 and create an empty chain. As well as empty docs buffer to hold current docs added to create a block. You can see that we create a genesis block and add to the chain right after we create the chain. Our genesis block is hashed but has no parent hash so we give it a value of 1 (this means we don’t have a parent hash)

Creating hashes for docs and blocks

We need to define a static method named hash_it() that we will use to hash our blocks and documents to be able to link them. Remember hashes help us identify the true identity of these items. This helps us to know that our items have tampered or not. We dwell on python’s hashing library to draw in the sha256 hashing function. This is what the Bitcoin blockchain uses too.

Creating and adding a document

This part is where we define how we create our document. So a document is of a timestamp, author, and content, and a doc item is of the document and the document hash. We store all this information in a dictionary format. For a document to be valid, it needs to be signed by a registered user. So we define the create_doc() add_doc() is_valid_doc() methods to deal with this for us.

Creating and adding a block

Here, we create functions that deal with collecting docs from the current docs pool. If the block passes the Block Limit Protocol, it gets added to the chain. The added block contains the hash of the previous block and also its own hash, index, and collection of docs in the block. So here we see the connection between all blocks in the chain down to the genesis block.

Interacting with our Blockchain

# Initialize Blockchain with new users
BasicX = Blockchain(name="BasicX", authors=["Kwaku", "Ama"])

# create 3 documents and add them to the pool
BasicX.add_doc(BasicX.create_doc("Kwaku", "The days of Ra"))
BasicX.add_doc(BasicX.create_doc("Ama", "20012 rock ages"))
BasicX.add_doc(BasicX.create_doc("Ama", "Freedom for all"))

# Create a new block and add to the blockchain
BasicX.add_block(Mufasa.create_block())

# See contents of the Blockchain
print(BasicX.chain)

Create more documents and add them to the blockchain. Try to break the protocol and see what happens. Also, try changing document contents in the blockchain. Witness that the chain will break and deemed invalid because the hashes will change. A good way to interact with the blockchain is to build API endpoints to access the methods on the blockchain. Security is more strengthened when we create Consensus protocol. Where by we add more nodes and sync the data between them so that. When data on one node changes or goes rogue , it will be easy to track and verify, but we can do that later ;) .

My goal for writing this article was to make you understand the basic features that make up a blockchain and this is my first post on STEEMIT. You can follow me for more in the future if you liked it. Thank you.

Sort:  

Great first post. I wish I had learned more about coding when I was in school but that was the 1980's and computers couldn't do many interesting things. I could learn now but it would of been much easier back then. Funny how you don't realize what's important when you're in school, the subjects I worked hard at are no use to me now :)

It's never too late buddy. You can still learn now as it is much easier now. I advice you to try out https://freecodecamp.com . There are so many resources around and if you can hit me up anytime on twitter. Link in my profile. Thanks for the complement.

Hi! I am a robot. I just upvoted you! I found similar content that readers might be interested in:
https://medium.com/we-are-orb/blockchain-and-how-to-build-one-811ac8da518f

Thank you, Mr robot ;)