Active Members Fi8sVrs Posted January 2, 2018 Active Members Report Posted January 2, 2018 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. Implementing Models 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. class Block : Codable { var index :Int = 0 var dateCreated :String var previousHash :String! var hash :String! var nonce :Int var message :String = "" private (set) var transactions :[Transaction] = [Transaction]() var key :String { get { let transactionsData = try! JSONEncoder().encode(self.transactions) let transactionsJSONString = String(data: transactionsData, encoding: .utf8) return String(self.index) + self.dateCreated + self.previousHash + transactionsJSONString! + String(self.nonce) } } func addTransaction(transaction :Transaction) { self.transactions.append(transaction) } init() { self.dateCreated = Date().toString() self.nonce = 0 self.message = "Mined a New Block" } init(transaction :Transaction) { self.dateCreated = Date().toString() self.nonce = 0 self.addTransaction(transaction: transaction) } } 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: class Transaction :Codable { var from :String var to :String var amount :Double init(from :String, to :String, amount :Double) { self.from = from self.to = to self.amount = amount } init?(request :Request) { guard let from = request.data["from"]?.string, let to = request.data["to"]?.string, let amount = request.data["amount"]?.double else { return nil } self.from = from self.to = to self.amount = amount } } 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. class Blockchain : Codable { var blocks :[Block] = [Block]() init() { } init(_ genesisBlock :Block) { self.addBlock(genesisBlock) } func addBlock(_ block :Block) { if self.blocks.isEmpty { // add the genesis block // no previous has was found for the first block block.previousHash = "0" } else { let previousBlock = getPreviousBlock() block.previousHash = previousBlock.hash block.index = self.blocks.count } block.hash = generateHash(for: block) self.blocks.append(block) block.message = "Block added to the Blockchain" } private func getPreviousBlock() -> Block { return self.blocks[self.blocks.count - 1] } private func displayBlock(_ block :Block) { print("------ Block \(block.index) ---------") print("Date Created : \(block.dateCreated) ") //print("Data : \(block.data) ") print("Nonce : \(block.nonce) ") print("Previous Hash : \(block.previousHash!) ") print("Hash : \(block.hash!) ") } private func generateHash(for block: Block) -> String { var hash = block.key.sha256()! // setting the proof of work. // In "00" is good to start since "0000" will take forever and Playground will eventually crash :) while(!hash.hasPrefix(DIFFICULTY)) { block.nonce += 1 hash = block.key.sha256()! print(hash) } return hash } } 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: class BlockchainController { private (set) var drop :Droplet private (set) var blockchainService :BlockchainService! init(drop :Droplet) { self.drop = drop self.blockchainService = BlockchainService() // setup the routes for the controller setupRoutes() } private func setupRoutes() { self.drop.get("mine") { request in let block = Block() self.blockchainService.addBlock(block) return try JSONEncoder().encode(block) } // adding a new transaction self.drop.post("transaction") { request in if let transaction = Transaction(request: request) { // add the transaction to the block // get the last mined block let block = self.blockchainService.getLastBlock() block.addTransaction(transaction: transaction) //let block = Block(transaction: transaction) //self.blockchainService.addBlock(block) return try JSONEncoder().encode(block) } return try JSONEncoder().encode(["message":"Something bad happend!"]) } // get the chain self.drop.get("blockchain") { request in if let blockchain = self.blockchainService.getBlockchain() { return try JSONEncoder().encode(blockchain) } return try! JSONEncoder().encode(["message":"Blockchain is not initialized. Please mine a block"]) } } } 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: // // BlockchainService.swift // Run // // Created by Mohammad Azam on 12/25/17. // import Foundation import Vapor class BlockchainService { typealias JSONDictionary = [String:String] private var blockchain :Blockchain = Blockchain() init() { } func addBlock(_ block :Block) { self.blockchain.addBlock(block) } func registerNode(_ blockchainNode :BlockchainNode) { self.blockchain.addNode(blockchainNode) } func getLastBlock() -> Block { return self.blockchain.blocks.last! } func getBlockchain() -> Blockchain? { return self.blockchain } } Let’s go ahead and check out out Web API end points. Start the Vapor server and send a request to “mine” end point. Mining a New Block 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. New Transaction The final step is to check out our blockchain with the newly added block. Visit the endpoint “blockchain” to view the complete chain. Blockchain 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: class BlockchainNode :Codable { var address :String init(address :String) { self.address = address } init?(request :Request) { guard let address = request.data["address"]?.string else { return nil } self.address = address } } 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: self.drop.post("nodes/register") { request in guard let blockchainNode = BlockchainNode(request :request) else { return try JSONEncoder().encode(["message":"Error registering node"]) } self.blockchainService.registerNode(blockchainNode) return try JSONEncoder().encode(blockchainNode) } The BlockchainService also gets updated to accommodate registering of the new nodes. func getNodes() -> [BlockchainNode] { return self.blockchain.nodes } func registerNode(_ blockchainNode :BlockchainNode) { self.blockchain.addNode(blockchainNode) } Let’s go ahead and test it out. Start the new Vapor server and try to register new nodes. Register a New Node Once, the node(s) has been registered, you can fetch it using the nodes end point as shown below: Fetching All Nodes 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. self.drop.get("nodes/resolve") { request in return try Response.async { portal in self.blockchainService.resolve { blockchain in let blockchain = try! JSONEncoder().encode(blockchain) portal.close(with: blockchain.makeResponse()) } } } 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: func resolve(completion :@escaping (Blockchain) -> ()) { // get the nodes let nodes = self.blockchain.nodes for node in nodes { let url = URL(string :"http://\(node.address)/blockchain")! URLSession.shared.dataTask(with: url) { data, _, _ in if let data = data { let blockchain = try! JSONDecoder().decode(Blockchain.self, from: data) if self.blockchain.blocks.count > blockchain.blocks.count { completion(self.blockchain) } else { self.blockchain.blocks = blockchain.blocks completion(blockchain) } } }.resume() } } 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: Blockchain on Port 8080 After that we added two transactions on port 8090 node as shown below: Blockchain on Port 8090 Make sure to register the node with the 8090 address as shown below: Registering a Node 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: Resolve End Point Returning Larger Blockchain 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. [Github] 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! Source: https://hackernoon.com/building-blockchain-web-api-using-swift-and-vapor-2daf599c8449 4 Quote