Gold BlogBlockchain Explained in 7 Python Functions

It wasn’t until I wrote my own simple Blockchain, that I truly understood what it is and the potential applications for it. So without further ado, lets set up our 7 functions!



By Tom Cusack, Data Scientist in the Banking Sector

Header image

I think for many people out there, Blockchain is this phenomenon, which is hard to get your head around. I started watching videos and reading articles, but for me personally, it wasn’t until I wrote my own simple Blockchain, that I truly understood what it is and the potential applications for it.

The way I think about blockchain is it is an encrypted database that is public. If you were Amazon and you wanted to use the technology to track your stock levels, would using Blockchain make sense? Probably not, since your customers won’t want to expend their resources verifying your blockchain, since they state on their website, ‘Only 1 left!’, anyway.

I’ll leave you to think about future applications. So without further ado, lets set up our 7 functions!

def hash_function(k):
    """Hashes our transaction."""
    if type(k) is not str:
        k = json.dumps(k, sort_keys=True)

    return hashlib.sha256(k).hexdigest()


At the heart of the blockchain is the hashing function. Without encryption, the blockchain will be easily manipulable and transactions will be able to be fraudulently inserted.

def update_state(transaction, state):
    state = state.copy()

    for key in transaction:
        if key in state.keys():
            state[key] += transaction[key]
        else:
            state[key] = transaction[key]

    return state


The ‘state’ is the record of who owns want. For example, I have 10 coins and I give 1 to Medium, then the state will be the value of the dictionary below.

{‘transaction’: {‘Tom’: 9, ‘Medium’: 1}}


The important thing to note is that overdrafts cannot exist. If there are only 10 coins in existence, then I cannot give 11 coins to someone. The below function verifies that the transaction we attempt to make is indeed valid. Also, a transaction must balance. I cannot give 5 coins and have the recipient receive 4 coins, since that would allow the destruction and creation of coins.

def valid_transaction(transaction, state):
    """A valid transaction must sum to 0."""
    if sum(transaction.values()) is not 0:
        return False

    for key in transaction.keys():
        if key in state.keys():
            account_balance = state[key]
        else:
            account_balance = 0

        if account_balance + transaction[key] < 0:
            return False

    return True


Now, we can make our block. The information from the previous block is read, and used to link it to the new block. This, too, is central to the idea of blockchain. Seemingly valid transactions can be attempted to fraudulently be inserted into the blockchain, but decrypting all the previous blocks is computationally (nearly) impossible, which preserves the integrity of the blockchain.

def make_block(transactions, chain):
    """Make a block to go into the chain."""
    parent_hash = chain[-1]['hash']
    block_number = chain[-1]['contents']['block_number'] + 1

    block_contents = {
        'block_number': block_number,
        'parent_hash': parent_hash,
        'transaction_count': block_number + 1,
        'transaction': transactions
    }

    return {'hash': hash_function(block_contents), 'contents': block_contents}


Below is a small helper function to check the hash of the previous block:

def check_block_hash(block):
    expected_hash = hash_function(block['contents'])

    if block['hash'] is not expected_hash:
        raise

    return


Once we have assembled everything together, its time to create our block. We will now update the blockchain.

def check_block_validity(block, parent, state):
    parent_number = parent['contents']['block_number']
    parent_hash = parent['hash']
    block_number = block['contents']['block_number']

    for transaction in block['contents']['transaction']:
        if valid_transaction(transaction, state):
            state = update_state(transaction, state)
        else:
            raise

    check_block_hash(block)  # Check hash integrity

    if block_number is not parent_number + 1:
        raise

    if block['contents']['parent_hash'] is not parent_hash:
        raise

    return state


Before we are finished, the chain must be verified:

def check_chain(chain):
    """Check the chain is valid."""
    if type(chain) is str:
        try:
            chain = json.loads(chain)
            assert (type(chain) == list)
        except ValueError:
            # String passed in was not valid JSON
            return False
    elif type(chain) is not list:
        return False

    state = {}

    for transaction in chain[0]['contents']['transaction']:
        state = update_state(transaction, state)

    check_block_hash(chain[0])
    parent = chain[0]

    for block in chain[1:]:
        state = check_block_validity(block, parent, state)
        parent = block

    return state


Finally, need a transaction function, which hangs all of the above together:

def add_transaction_to_chain(transaction, state, chain):
    if valid_transaction(transaction, state):
        state = update_state(transaction, state)
    else:
        raise Exception('Invalid transaction.')

    my_block = make_block(state, chain)
    chain.append(my_block)

    for transaction in chain:
        check_chain(transaction)

    return state, chain


So, now we have our 7 functions. How do we interact with it? Well, first we need to start our chain with a Genesis Block. This is the inception of our new coin (or stock inventory, etc). For the purposes of this article, I will say that I, Tom, will start off with 10 coins.

genesis_block = {
    'hash': hash_function({
        'block_number': 0,
        'parent_hash': None,
        'transaction_count': 1,
        'transaction': [{'Tom': 10}]
    }),
    'contents': {
        'block_number': 0,
        'parent_hash': None,
        'transaction_count': 1,
        'transaction': [{'Tom': 10}]
    },
}

block_chain = [genesis_block]
chain_state = {'Tom': 10}


Now, look what happens when I give some coin to Medium:

chain_state, block_chain = add_transaction_to_chain(transaction={'Tom': -1, 'Medium': 1}, state=chain_state, chain=block_chain)


The state gets updated to show who has what:

{'Medium': 1, 'Tom': 9}


And the blockchain looks like this:

[{'contents': {'block_number': 0,
               'parent_hash': None,
               'transaction': [{'Tom': 10}],
               'transaction_count': 1},
  'hash': '064d0b480b3b92761f31831d30ae9f01954efaa62371b4b44f11465ec22abe93'},
 {'contents': {'block_number': 1,
               'parent_hash': '064d0b480b3b92761f31831d30ae9f01954efaa62371b4b44f11465ec22abe93',
               'transaction': {'Medium': 1, 'Tom': 9},
               'transaction_count': 2},
  'hash': 'b4ae25f0cc0ee0b0caa66b9a3473e9a108652d53b1dc22a40962fef5c8c0f08c'}]


Our first new transaction has been created and inserted to the top of the stack. Now, I hope I have piqued your curiosity, and are interested in copying the code down and playing with it. In my opinion, this is the best way to learn a new technology — Get inside it.

Play with the code and make your own coin. What happens if you try and give more coins than exist? What happens to the state if you keep creating new payees?

Can you think of future applications for blockchain? Feel free to ask me anything in the comments, and I’ll try and help.

 
Bio: Tom Cusack is a Data Scientist in the Banking Sector.

Original. Reposted with permission.

Related: