Blockchain in Swift

Simple blockchain implementation in #Swift

Harsh Vishwakarma
4 min readJan 8, 2019

The source code is available here.

Before we start, we should have a fair understanding of Swift programming language, know how HTTP requests work and an HTTP Client, like Postman or cURL.

What is a blockchain?

A blockchain is a distributed and decentralized way of storing data such as transactions, and that is publicly shared across multiple nodes. As the name suggests Block-Chain, in a blockchain, multiple such blocks of transactions are chained together using hashes. The hash of the one a block is dependent on the hash of the previous block in the chain.

The Setup

I will be using Swift Package Manager to manage the dependencies in this project. You can skip this step if you are using Cocoapods or some other dependency manager. All you need is to include the following three libraries.
Kitura, SwiftyRequest for HTTP requests and CryptoSwift for hashing.

// Create a new directory and follow these steps.$ mkdir Swift-Blockchain && cd Swift-Blockchain
$ swift package init --type=executable

# Open the Pacakge.swift and make the changes so your file looks similar to the one below.

Package.swift
// Fetch the dependencies we mentioned in the 'Package.swift' file.
$ swift package resolve
// Generate Xcode Project.
$ swift package generate-xcodeproj
// Build the project.
$ swift build

Building the Blockchain

The Blockchainclass will store the chain and the transactions as well. We will be implementing methods toadd transactions, mine a block, find proof of work, hash and a few others as well. Below is the structure of our Blockchain class.

Each Block in a blockchain has an index, a timestamp, a list of transactions, a proof, and the hash of the previous Block. Here’s how a block looks like.

Mining in Bitcoin

Mining, in the context of blockchain technology, is the process of adding transactions. Our newTransaction(:sender, :recipient, :amount), method creates a new transaction and appends it to the list of existing transactions.

Adding new Transaction to a Blockchain

Calculating “proof of work (PoW)” and “Hashing”

A proof of work is a piece of data which is difficult (costly, time-consuming) to produce but easy for others to verify. In Blockchain, this algorithm is used to confirm transactions and produce new blocks to the chain. With PoW, miners compete against each other to complete transactions on the network and get rewarded.

The first block (Genesis Block) of a blockchain is created in the initializer of our Blockchain class. And our newBlock(:previous_hash, :proof) method takes care of creating a new block.

Adding a new Block to the chain

# Find a number p that when hashed with the previous block’s solution a hash with 4 leading 0s is produced.

Calculating “Proof of Work” (PoW)

Bitcoin uses the Hashcash proof of work system.

REST API

Our blockchain implementation is complete. Now it’s time to deploy it over a network. We’ll be using external libraries, Kitura for creating REST API and SwiftyRequests for sending HTTP requests.

Modify our Blockchain class to include the methods to create a distributed architecture by allowing multiple nodes on the network. We will be adding an HTTP server after this to deploy our blockchain over the network.

Interacting with the Network

API Endpoints

# Creating new transactions………..………….…/transactions/new
# Mining new blocks..….…………………………/mine
# Fetching the blockchain.….….….….….….….../chain
# Registering new nodes in the network….…..…/nodes/register
# Verifying the valid chain….….….….….….….../nodes/resolve

HTTP Server

At this point, our server is running on http://localhost:5000

Fetching the blockchain

{
"chain": [
{
"timestamp": 568658289.66846001,
"proof": 100,
"transactions": [],
"previous_hash": "1",
"index": 1
}
],
"length": 1
}

Adding a new Transaction

{
"message": "Transaction will be added to Block 2"
}

Mining a new Block

{
"message": "New Block Foreged",
"proof": 33575,
"previous_hash": "0201d60f8d9227e99b52465254dceaf3487d5f829e9a4c72633b327684aaa308",
"transactions": [
{
"amount": 5,
"recipient": "4as226eee1514743e92c6cd394edd974f",
"sender": "d4ee26eee15148ee92c6cd394edd974e"
},
{
"amount": 1,
"recipient": "792DC096423E4D289CE73510A66751872631800001087BEA56B12",
"sender": "0"
}
],
"index": 2
}

Registering a new Node in the Network

{
"message": "New nodes have been added",
"total_nodes": [
"127.0.0.104"
]
}

Verifying the Blockchain

{
"message": "Our chain is authoritative",
"chain": [
{
"timestamp": 568658419.15293097,
"proof": 100,
"transactions": [],
"previous_hash": "1",
"index": 1
}
]
}
{
"message": "Our chain was replaced",
"new_chain": [
{
"timestamp": 568658449.77230096,
"proof": 100,
"transactions": [],
"previous_hash": "1",
"index": 1
}
]
}

If you use Postman, you can download the postman collection here.

If you missed, the source code for “Siwft-Blockchain” is available here.

This article is a swift port to “Learn Blockchains by Building One”

Many thanks to Daniel van Flymen for writing Learning blockchain By Building One”, it is such an awesome article to read. I hope you have enjoyed this post as much as I’ve enjoyed writing it. As always, your suggestions are most welcome.

--

--