How to Design a Blockchain Network in Swift / by Wayne Bishop

Bitcoin. The name invokes reactions of interest, speculation and curiosity. As someone interested in iOS development and computer science, it has been hard to resist exploring the technology and how it works. It is fascinating that even though crypto-currencies like Bitcoin are seen as new solutions, their design is based on a few concepts based in computer science. For this introductory article on Bitcoin, we'll review its core technology - known as a Blockchain, in Swift. 

 

PRIVATE LEDGERS

These days, the idea of sending or receiving money online is anything but new. On the contrary, much of the world economy is now conducted through the Internet, with some countries openly discussing the elimination of paper currencies altogether. Even though consumers, banks and institutions have designed a system that works, opportunities still exist for improvement. To see how ideas like Bitcoin differ from traditional banking consider the following:

ledger-private.png

Traditional banking model. 

In traditional commerce, Banks act as the coordinator and trusted authority for financial transactions. As a result, if person A wants to send or receive funds with person B, the exchange must be authorized by the Bank before any action takes place. Assuming the exchange is authorized, the Bank will facilitate the exchange and record the transaction in its books - otherwise called a private ledger. One reason for the Bank's success is accountability. Meaning, if any dispute over a transaction occurs, either person A or B can contact the Bank for more information. Another item to note is privacy. Even though persons A and B conduct business with the same Bank, neither party are permitted to view any transactions beyond their own. 

 

PUBLIC LEDGERS 

Crypto-currencies like Bitcoin operate differently. Their model is based on popular Internet-based strategies like wisdom of crowds to avoid disputes, detect fraud and increase security. Consider the following:

bitcoin-graph.png

A "Bitcoin" decentralized network.

This model doesn't show how entities relate to a Bank, as no central Bank (e.g. a single coordinating entity) exists. In its place, a decentralized network operates more like an undirected graph. Instead of a single Bank working to check the integrity of transactions, this effort is spread throughout the network with the assistance of additional entities called Miners. An important feature is that all peers can track the transactions completed by any other peer. This public ledger of events is known as the Blockchain:

ledger-public.png

A Blockchain.

This representation provides an illustration of transactions that have occurred in our network. For each occurrence, a special data structure known as a Block is created and added to the list. Similar to a Linked List, Blockchains are initiated with a nil record often called the Genesis Block.

 

BUILDING BLOCKS

Now that we understand the fundamentals of a Blockchain, let's explore how this model can be expressed in Swift. For educational purposes, our peer-to-peer network can be visualized as a Graph. However, to satisfy our currency/transaction requirements, we'll apply Swift Inheritance and design our model as a Graph subclass. As a result, we can represent a Peer as a unique Graph Vertex:

/* an object that participates in a graph network */

public class Vertex {
    
    var key: String?
    var neighbors = Array<Edge>()
    var lastModified = Date()
    
    init() {
    }
    
    init(with name: String) {
        self.key = name
    }
}

/* note: a Peer acts as Vertex subclass */

public class Peer: Vertex {
    
    var chain = Array<Block>()
    var intentions = Array<Exchange>()
    
    
    override init(with name: String) {
        super.init()
        super.key = name.identifierWithDate(date: lastModified)
    }
    
    
    //publish intended transaction
    func intent(with to: Peer, for amount: Double) {
        
        //create exchange
        let newExchange = Exchange(from: self.key,
                                   to: to.key,
                                   amount: amount)
        
        intentions.append(newExchange)
    }
}

Many features of crypto-currency networks are supported by our Peer class. Access to the public ledger is made possible with the chain array variable. Managed as a public property, this will be updated when new transactions get processed. When a Peer intends to exchange funds with others, the event is published (to the network) for Miners to fulfill.

 

PUBLIC LEDGER

Another feature of Blockchain networks is traceability. Typically, information on senders and receivers is included in the public ledger. Production-level systems like Bitcoin use advanced Rijndael/AES encryption to allow Peers to digitaly sign transactions with a public key. However, to keep our model straightforward, our class implements a custom initialization sequence that transforms its key to a one-way hash:

extension String {

    //unique identifer based on date
    func identifierWithDate(date: Date) -> String {
        
        let cleartext = self + String(describing: date)
        return String(cleartext.hashValue)
    }
}

Written as a String extension, identifierWithDate combines our Peer key with the current date to create a "public key". As an iOS developer, note how the cleartext String variable conforms to the popular Hashable protocol. This technique provides a quick way to encrypt information without integrating third-party frameworks. For example:

var PeerA = Peer(with: "Steve Wosniak")
print(PeerA.key) //prints "5356917553324395268"
 
var PeerB = Peer(with: "Steve Jobs")
print(PeerB.key) //prints "6319305020597144651"

While it would be technically possible to encrypt just the Peer name, the algorithm also includes Date to reduce the likelihood of hash collisions. 


Learning iOS for your next project or technical interview? Most successful apps combine language features, tools and various techniques to solve a specific problem. Based on the implementation of my own projects, use this free worksheet to plan your learning path.