Create a Blockchain with Swift Playground in 20 minutes

Li 👨🏻‍💻🤖🦾
Blockchain Journey
Published in
4 min readOct 8, 2017

Blockchain is an array of blocks linked together with the hash values from the previous blocks. In this article, I will show you how to create a total new blockchain from scratch, using Swift language in Playground. The code is based on Swift4 and Xcode9.

First, let’s create a blank Playground file in Xcode9. Delete the sample code and import Foundation library.

Create a block

A block normally consists of the transactions data, a hash pointer and a timestamp. For the sake of simplicity, the block we are going to create will have an array of strings and one hash pointer to the previous block.

  • previousBlockHashValue is the hashValue of the last block. It is readonly.
  • transactions is an array of strings, readonly.

So there you have it, a block for blockchain. But wait, there seems to be something missing, hmm… Of course, we will need a way to calculate the hash value of the block! In apps like Bitcoin, they use dedicated designs. But here, we will just calculate each transaction’s hash value(Int), add them together with the previous block’s hash value, then return the hash value of the result.

That’s it! The structure of our Block type. But this is not the end. We will need a blockchain to chain them together.

Create a Blockchain

The blockchain data type is quite like the Array type, except for that it has some conditions for appending new object. The new block to be added into the blockchain should have the hash pointer of the last block in the blockchain. That is how we chain them together. So that once added, the blockchain is immutable unless all of the has values of blocks to be recalculated.

Remember the conditions for appending new blocks, here it goes:

The new block’s hash pointer should be either 0(genesis) or the last block’s hash.

Let’s add some blocks

Every blockchain needs a genesis block, which is normally predefined and hard coded.

A new blockchain was created! The genesis block was created and added into the blockchain! Here is the debug console’s output:

Let’s create the second block

The genesis block’s hash vale was passed in to create the second block. Then the third one:

Here is the total output:

Those three blocks are linked together in the blockchain.

Let’s create a fake block

A new transaction was added to the third block. This fake block was trying to add itself into the blockchain, but got rejected because it’s hash pointer is not valid anymore.

Walaa! Now you have a fully working blockchain. It is not something to impress your friends with, but can give you a good idea of the basics of the blockchain.

I hope you enjoy reading this article. Please comment below if you spot any errors. The full source code of the Playground file is available here: https://github.com/proper/BlockchainInSwift

--

--