In my last post I discussed the basic implementation of Blockchain in Swift language. In this post I will take the Blockchain implementation to the cloud using server side Swift framework, Vapor. We will build the Blockchain Web API over the HTTP protocols, providing necessary functionality using different routes. This post assumes that you have installed Vapor framework on your computer and have basic knowledge of Swift Language.
The first step is to create necessary models for the Blockchain Web API. These models will consist of the following.
Block: A block class represents a single block which can contain inputs and outputs represented by transactions.
The properties of Block class are explained 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
- message — Memo attached to each block. This is just for our purposes
- nonce — Auto incremented number which plays an important role for mining the hash
- transactions — An array of transactions. Each transaction represents a transfer of goods/value
- key — This is a computed property which is passed to the hashed function
Transaction: Transaction consists of the sender, recipient and the amount being transferred. The implementation is shown below:
The Transaction class is self explanatory. It consists of from, to and amount fields. For the sake of simplicity we will be using dummy names for from and to fields, in reality these fields will consist of wallet ID.
Blockchain: Blockchain is the main class which represents a list of blocks. Each block points back to the previous block in the chain. Each block can contain multiple transactions, representing the credit or debit.
Each model adheres to the Codable protocol which allows it to easily convert to JSON represented object. If you have followed the last article then the implementation above is very similar. Next step is to configure routes for our Web API, this is implemented in the new section using the Vapor framework.
Implementing Web API Using Vapor
There are several different ways of implementing the Web API using Vapor. Instead of adding all the code in the Routes class, I proceeded by adding a custom controller which will handle all Blockchain requests. The implementation of BlockchainController is shown below:
We will start by three basic endpoints for the Web API.
- Mining: This endpoint will initiate the mining proess. Mining will allow us to satisfy the proof of work and add the block to the Blockchain.
- Transaction: This endpoint is used to add a new transaction. The transaction will contain information about sender, receiver and the amount.
- Blockchain: This endpoint returns the complete blockchain.
The BlockchainController uses the BlockChainService to perform the required operations. The implementation of BlockChainService is shown below:
Let’s go ahead and check out out Web API end points. Start the Vapor server and send a request to “mine” end point.
The proof of work algorithm generates a hash value starting with “000”. Once, the block has been mined we return it by converting it into JSON format. This is performed by using the Swift 4.0 Codable Protocols.
Now, we can add our transaction to the blockchain. Here is a simple transaction which transfers $10 from Alex to Mary.
The final step is to check out our blockchain with the newly added block. Visit the endpoint “blockchain” to view the complete chain.
Hooray! Our Blockchain Web API is now working correctly.
Unfortunately, the whole point of blockchain is to be decentralized and currently, we don’t have any mechanism to add new nodes. In the next section we are going to update our blockchain implementation so it can support multiple nodes.
Adding Nodes to Blockchain
Before allows the blockchain to add new nodes, we must define what a node looks like. The implementation of a node model is shown below:
The BlockChainNode class simply consists of an address property which represents the URL of the node server. We update the BlockchainController to add the ability to register new nodes. This is shown below:
The BlockchainService also gets updated to accommodate registering of the new nodes.
Let’s go ahead and test it out. Start the new Vapor server and try to register new nodes.
Once, the node(s) has been registered, you can fetch it using the nodes end point as shown below:
Now, that we can register new nodes we should focus on resolving the conflicts between the nodes. A conflict happens when the blockchain on one node gets larger as compared to the other nodes. In this scenario, we always takes the neighboring nodes and updates them with the larger blockchain.
Resolving Conflicts Between Nodes
In order to create a conflict we need to run a second server or run the server on a separate port. We are going to use the later approach and start the Vapor server on a different port. Once, the two nodes are initiated, we will create transactions on both nodes which will add blocks to the blockchain. Finally, we will call a resolve end point which will resolve the conflicts between nodes and update the node to the larger blockchain.
The BlockchainController has been updated to add a new end point for resolving conflicts.
We have used the async response feature of Vapor framework which will allow us to process the response asyncronously. The BlockchainService has also been updated to support the conflict resolution. The implementation is shown below:
The resolve function goes through a list of nodes and fetches the blockchain of each node. If the blockchain is larger than the current blockchain then it replaces the blockchain with the larger one, otherwise it returns the current blockchain which is also the larger one.
In order to test it out let’s start two servers on separate port and add two transactions on port 8080 and three on 8090. You can start a Vapor server using terminal by issuing the following command.
vapor run serve -— port=8090
We added three transactions on port 8080 node as shown below:
After that we added two transactions on port 8090 node as shown below:
Make sure to register the node with the 8090 address as shown below:
Finally, it is time to test our resolve conflict end point. Invoke the “resolve” end point by visiting it in your Postman as shown below:
As you can see the resolve end point returns the larger blockchain and also updates the blockchain for the other nodes. This completes our conflict resolution scenario.
This post is based on an amazing post by Daniel Van Flymen “Learn Blockchains by Building One”.
I hope you like the post. I am currently in the process of making a Udemy course on “Blockchain Programming in iOS”. You can subscribe here to get notified when the course is released.
If you want to support my writing and donate then please visit my courses page and buy my amazing courses on Udemy.
Thanks and happy programming!