How to Build Blockchain For a Financial Product

Vadym Zakovinko
codeburst
Published in
8 min readSep 4, 2018

--

Note: the code samples may be displayed improperly because of markdown. I recommend to continue reading the original article on our blog to make sure all the examples are displayed properly.

It amuses me that the most promising technology of the decade is associated with speculations and financial fraud. That’s really weird. Instead of trying to apply it correctly, we have Fashion Blockchain Conferences and stories about successful ICOs. Luckily, there are some entrepreneurs and engineers bold enough to try to apply blockchain so that many could benefit from it.

I’m not going to be talking about digital revolutions and ‘Let’s change the words’ kind of things, but instead, I’ll (1) share my thoughts on why finance can benefit from blockchain more than any other industry, and (2) teach you how to build a simple blockchain in Python.

You Are No Industry for Him. Who is Ready For Blockchain

In most articles, I’ve read about ‘Why products fail,’ authors always mention high prices, weak marketing campaigns, lack of products uniqueness, targeting the wrong market. Few, however, have written anything about products being released at the wrong time. The most prominent example is the Internet: it became available in the early ’90s but most people, entrepreneurs included, couldn’t figure out how to apply it to benefit.

Why did it happen? Partly because people weren’t ready for such a significant step towards globalization; partly because few attempted to study how to use the Internet for their own benefit, although everybody knew it existed.

Something like that is happening to blockchain — many are talking about it, fewer understand it, and much fewer know how to use it. How come it’s been around for over a decade and still there’s no global blockchain-based app? Nobody has the answer to that. But at least we know where to use it. Let me explain.

Source: Microsoft Azure

A person is less reliable than a machine. That’s why the spheres that are most subject to human error (forgery and fraud) needed a technology that could exclude those factors. The most troublesome area is finance because it deals with money, and people love money. We all know that sometimes it’s difficult to resist the temptation to earn more.

That’s why fintech startups are trying to implement blockchain in finance — to make sure no fraud will take place. It’s blockchain that can exclude third-parties from trading operations, optimize person authentication, track financial transaction and ensure the document is genuine.

Read: What you need to consider before building a fintech product

It doesn’t mean that every fintech startups need blockchain. Here’s a simple quiz.

Read Our Fintech Case Studies:

You don’t need blockchain if the following is true for you:

  • You have no budget for experiments. Implementing blockchain is always risky so there’s no guarantee you’ll profit.
  • You’re conservative. Blockchain may result in major changes in organization structure, so unless you’re ready for it, I wouldn’t suggest it.
  • You want the results right now. Blockchain is all about the long-term perspective. Don’t expect any results in less than a year.

On the other hand, you shall try blockchain in these cases:

  • You want to get investments. Since blockchain is a buzzword, it attracts more investments than any other promised feature.
  • You want to increase your competitiveness in the market. Build a financial product on blockchain will demonstrate your competence in the area. This will increase your company attractiveness to both investors and customers.
  • You can afford experiments. Contrary to what I’ve written above, if your budget allows you to hire blockchain developers and you have a strong vision about your future product, go for it.

Now, to prove that blockchain isn’t actually that difficult, I’ll give you step-by-step instructions on how to build it.

Application of blockchain in fintech

‘Frameworks’ to use

CryptoNote

CryptoNote is an open-source technology that allows you to create tokens. It has a simple, guide to creating a cryptocurrency, and launching requires two nodes which you’ll use to run the Monero server.

Useful links:

How to create a token., How to create a wallet

Ethereum

An open platform for building decentralized apps with the focus on running the programming code. “…Applications that run exactly as programmed without any possibility of downtime, censorship, fraud or third party interference.

ZeroNet

Use ZeroNet to create decentralized websites. The system uses the Bitcoin addressing and verification mechanisms, and the BitTorrent distributed content delivery network to build sites that can’t be censored, blocked or forged.

How to create simple blockchain

So now that you know the tools let’s build a simple blockchain. I’ll use Python in this example. First, I’ll explain the core elements required to build a block.

Date of creation

It’s the current and time in unix format. You’ll need it later — when you have many running nodes, and you add a new block to your branch, the node will choose which block to use based on Date of Creation.

Nonce

It’s a set of symbols that we need to add to the block to build the checksum that fits the requirement. For instance, if the nonce value is 5, then we have to add 5 zeros (00000) to the data block to calculate the right checksum.

Checksum

It’s block data with nonce plus checksum of the previous block. SHA256 protects the chain from being rewritten. How it works: Node calculates the checksum and compares to the one of the new blocks — if they match, the block is added to the blockchain.

Data

A piece of data that’ll be stored in a block and signed. It can contain any sort of data: a list of transactions (not only the last transaction); the information about the computer that created the block (like its MAC address); a detailed date of creation (the time zone).

Proof of work

Proof of work (PoW) is a unique consensus algorithm in a blockchain network. It’s used to validate the operations and the creation of new chains in the blockchain. The main idea of PoW is to add complexity to building a block on the client side and reduce the load on the server side. For example, I say checksum has to have 5 lead zeros; it means that we’ll increase nonce until checksum has 5 lead zeros.

Let’s start with a code

First, I’ll create a class for a block. It’ll be a very simple class with a constructor — a method for calculating the checksum and property to check that the block is valid. We’ll have two constants, one for number of lead zeros in the checksum and the second to identify which symbol we’ll use with the nonce.

import time
from hashlib import sha256

class Block:
CHECKSUM_LEAD_ZEROS = 5
NONCE_SYMBOL = 'Z'

def __init__(self, prev_block, data):
self._prev_block = prev_block
self.data = data
self.checksum = None
self.nonce = 0
self.timestamp = time.time()

@property
def is_valid(self):
checksum = self.calculate_checksum()

return (
checksum[:self.CHECKSUM_LEAD_ZEROS] == '0' * self.CHECKSUM_LEAD_ZEROS
and checksum == self.checksum
)

def calculate_checksum(self):
data = '|'.join([
str(self.timestamp),
self.data,
self._prev_block.checksum,
])
data += self.NONCE_SYMBOL * self.nonce

return sha256(bytes(data, 'utf-8')).hexdigest()

Constructor

Constructor accepts only 2 parameters — the first is the previous block, and the second is the current block data. Constructor also creates the time mark and sets nonce to zero as its initial value.

Is valid

A property that calculates the checksum and compares if the current one is equal to the calculated and has the right number of zeros.

Calculate checksum

The most complicated method in our code. This method packs the time mark, data, and the checksum of the previous block to one string. Then we add a nonce string; in our case, it’ll be a list of ‘Z’s. Then it calculates the checksum of the result string.

Now we have a simple yet functional block. Let’s move on and create a chain of blocks. For now, a simple chain without the ability to store and load data will go.

import json

class Chain:

def __init__(self):
self._chain = [
self._get_genesis_block(),
]

def is_valid(self):
prev_block = self._chain[0]
for block in self._chain[1:]:
assert prev_block.checksum == self._prev_block.checksum
assert block.is_valid()
prev_block = block

def add_block(self, data):
block = Block(self._chain[-1], data)
block = self._find_nonce(block)
self._chain.append(block)

return block

@staticmethod
def _get_genesis_block():
genesis_block = Block(None, None)
genesis_block.checksum = '00000453880b6f9179c0661bdf8ea06135f1575aa372e0e70a19b04de0d4cbc7'

return genesis_block

@staticmethod
def _find_nonce(block):
beginning = '0' * Block.CHECKSUM_LEAD_ZEROS
while True:
checksum = block.calculate_checksum()
if checksum[:Block.CHECKSUM_LEAD_ZEROS] == beginning:
break
block.nonce += 1
block.checksum = checksum

return block

Let’s take a look at the methods in our chain class:

Constructor

I created a chain with only one block — a genesis block. Genesis block is the first block of the chain and has only a checksum. This block is required to add the first real block to the chain because the real block requires the checksum of the last block in the chain.

Adding a new block

It has only one parameter — data for a new block. This method creates a new block with the given data and run method to find the correct nonce value. Only then it’ll append a new block to the chain.

Find the nonce

This method aims to find the right nonce for a block. It has an infinite loop where I increase the nonce and calculate a new checksum. Then it compares the checksum with the rules — for now, it’s only the number of zeros.

Validate the chain

This method shows if the chain is valid — It goes through all blocks in the chain and checks each block individually.

Bottom Line

The main message I wanted to convey is this: blockchain is a young technology yet we have everything to study it. Having found its best practical application in fintech, blockchain can help businesses protect the information, increase the speed of data transmission, and most important — exclude the human factor.

To learn how to build a blockchain, study my examples of code, write it in your preferred language and try to play with it. Who know, maybe your product will be the next game changer?

Stay tuned for the next part about blockchain and fintech, with more complex pieces of code and suggestions on its practical application in fintech.

This article about financial product blockchain is originally posted on Django Stars blog.

If you find this post useful, please tap 👏 button below :)

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--