Blockchain is the technology behind popular cryptocurrencies including Bitcoin. The main concept behind Blockchain is to provide a distributed ledger which is not controlled by one central party. In this post I will show you how you can use iOS/MacOS to create a very basic Blockchain in Swift language.
NOTE: This post does not cover nodes/peers, validation, rewards etc.
The quickest and the easiest way to to get started is by using Swift Playgrounds. For this particular demo, I used macOS Playgrounds since it has some useful functions for generate SHA hash.
Implementing the Block Class
The first step is to implement the Block class which will represent a single block in a .. blockchain. The implementation is shown below:
The details of the Block class is shown below:
- index — The position of block in the blockchain. Index of 0 means that the block is the first block in the blockchain. Index of 1 means it is the second block in the blockchain.. you get the idea right!
- dateCreated — The date when the block was created
- previousHash — The hash value of the previous block
- hash — The current hash of the block
- nonce — Auto incremented number which plays an important role for mining the hash
- data — Any valuable asset. This can be money, medical information, real estate information etc
- key — This is a computed property which is passed to the hashed function
Implementing the Blockchain Class
The Blockchain class requires an instance of a block to initialize itself. This block is also known as genesis block, since it is the first block in the block chain. The implementation of Blockchain class is shown below:
The addBlock function adds the block to the blockchain. The next block is based on the previous block’s hash, which is one of the properties used by the key property.
The generateHash function is responsible for generating a unique hash which will be assigned to the block. But instead of just using some random hash we are going to search for a special hash that starts with “00”. This concept is also known as “Proof of Work System”. In reality the Proof of Work System will be more complicated to solve, the person who solves it gets a reward (Extra Bitcoins perhaps).
Let’s go ahead and see our basic blockchain in action.
You can download the complete source code from Gist. Copy and paste the code into macOS Playgrounds.
I am currently working on a course which will cover Blockchain programming in iOS. If you are interested then subscribe here to get a notification when the course is published.
I hope you have liked the post. If you like to support my contributions then please go ahead and enroll in one of my awesome courses. Thanks and happy programming!