Blockchain is a Disruptive technology, which has gained increasing attention in recent years. Why is that? Because blockchain is the founding technology of many Cryptocurrencies such as Bitcoin, Ethereum, and Litecoin. So how does blockchain work? In this teaching, I will talk about all the knowledge of blockchain technology and how to use Swift to make my own “blockchain”. So, let’s get started!
How blockchain works
As the name suggests, a blockchain is a “chain” of different blocks, each containing three pieces of information: Data, a Hash, and a Hash of the previous block.
- Data — The data stored in the block will vary depending on the type of blockchain, depending on the context of use. In the Bitcoin blockchain, for example, stored data is information about a transaction, the amount of money transferred, and information about the two people involved in the transaction.
- Hash values — You can think of hash as a digital fingerprint that identifies a block and its data. The most important thing about hash is that it is a unique Alphanumeric code, usually made up of 64 characters. When a block is created, hash values are also generated. When a block is changed, the hash value is also changed. In this way, hash values are important when you want to see any changes on the block.
- Hash of the previous block — each block is linked together by storing hash of the previous block to form a blockchain! That’s what makes blockchain so secure. Take a look at this image:
As you can see, each block is made up of data (not shown), hash values, and hash values from the previous block. For example, the yellow block contains its own hash value, H7S6, and the red block’s hash value, 8SD9. In this way, they form a chain and are joined together. Now, suppose a hacker breaks in and tries to change the red block. Remember, every time a block is changed in any way, the block’s hash is changed too! Thus, when the next block performs validation and sees that the hash values of the previous block do not match, it effectively separates itself from the chain without being read by a hacker.
This is why block drills are so secure, it’s almost impossible to go back and change anything. Hash values provide good confidentiality and privacy, but there are also two security mechanisms that make blockchains more secure: proof-of-work and Smart contracts. I won’t go into details, but you can learn more here. The last way to secure blockchain is based on its location. Unlike most data stored on servers or in databases, blockchains use peer-to-peer (P2P) networks, a type of network that allows anyone To join and distribute data on the network To each recipient. Every time someone joins the network, they get a full copy of the blockchain; Every time someone creates a new block, it is transmitted to everyone in the network. Nodes are then programmed to verify that a block has been tampered with before it is added to the blockchain. In this way, anyone, anywhere, can access the information. If you’re a big fan of HBO’s Silicon Valley, this might sound familiar, since the show’s main character uses similar technology to build a new network.
Because each person or node has a copy of the blockchain, they can have consensus and confirm which blocks are legitimate. Therefore, if you want to hack a block, you have to hack more than 50% of the block on the network to get your information through. That’s why blockchain is probably one of the most secure technologies of the last decade.
About sample applications
Now that you understand how blockchain works, let’s start building our sample App! Please download the initial project first. (https://raw.githubusercontent.com/appcoda/BlockchainDemo/master/BlockchainStarter.zip)
As you can see, we have two Bitcoin wallets. The first Account, Account 1065, has 500 BTC, while the second Account, 0217, has nothing. We use the send button to send Bitcoins to other accounts. To earn BTC, we press the Mine button and get 50 BTC as a reward. Basically, what we do is we use the console to watch transactions between two Bitcoin accounts as the App executes.
You’ll notice that there are two important categories in the sidebar: Block and Blockchain. If you open these files, you’ll see that the files are empty, and that’s because I’m going to guide you through the logic of these categories. Let’s get started!
Define a Block in Swift
Go to block. swift and add code to define a Block. First, let’s look at what a block is. We previously defined a block to consist of three parts: hash values, the actual data recorded, and hash values from the previous block. When we want to build our own blockchain, we must know the order of the blocks, which can be easily defined in Swift. Add the following code to the category:
var hash: String!
var data: String!
var previousHash: String!
var index: Int!
Copy the code
Now, we need to add one last important piece of code. I mentioned earlier that every time a block is changed, the hash changes; That’s one of the things that makes blockchain so secure. So we have to set up a function to generate a random alphanumeric hash. This function requires only a few strokes of code:
func generateHash(a) -> String {
return NSUUID().uuidString.replacingOccurrences(of: "-", with: "")}Copy the code
NSUUID is an object that represents a universal unique value for bridging UUID. It is built into Swift and is ideal for generating 32-character strings. This generates a UUID, removes all hyphens (-), and returns a String, a hash of the block. Block.swift should now look like this:
Now that we’ve defined the Block category, let’s define the Blockchain category. Switch to blockchain.swift.
Define Blockchain in Swift
As mentioned above, let’s try to understand blockchain from the fundamentals. In basic terms, a blockchain is just a chain of blocks strung together; In other words, it’s a list of all the items. Sound familiar? Because that’s the definition of an array, and an array is made up of blocks! Let’s add the following code:
var chain = [Block] ()Copy the code
Tip: This applies to just about anything in the computer science world. If you have a big problem, try to break it down into small pieces and solve the problem in your own way. Just like we figured out how to add blocks and blockchains to Swift!
You’ll notice that the array contains the previously defined Block classes, which are all the variables we need in the blockchain. Add two functions to the class, and we’re done. Try to answer this question with what I taught you earlier:
What are the two main functions in a blockchain?
Hope you can answer this question! The main functions that these two blockchains have are to create the initial block and to add new blocks later. Of course, I’m not going to drop the chain and add the smart contract right now, but these are the basic functions! Add the following code to blockchain.swift:
func createGenesisBlock(data:String) {
let genesisBlock = Block()
genesisBlock.hash = genesisBlock.generateHash()
genesisBlock.data = data
genesisBlock.previousHash = "0000"
genesisBlock.index = 0
chain.append(genesisBlock)
}
func createBlock(data:String) {
let newBlock = Block()
newBlock.hash = newBlock.generateHash()
newBlock.data = data
newBlock.previousHash = chain[chain.count-1].hash
newBlock.index = chain.count
chain.append(newBlock)
}
Copy the code
- The first function we add is to set up the initial block. To do this, we create a function that takes the block’s data as Input. We then define a variable named genesisBlock and set it to Block type. Since it is of Block type, it has all the variables and functions we defined earlier in block. swift. We set generateHash() to hash and Input Data to data. Since this is the first block, we set the hash of the previous block to 000 to let us know that this is the initial block. We set its index to 0 and put it into the blockchain chain.
- The next function we create will apply to all blocks after genesisBlock, and it will create all the remaining blocks. You will notice that it is very similar to the previous function, except that we set previousHash to the hash of the previous block and index to the position at which the block is run. Done! We have successfully defined our own Blockchain! Your code should look like this!
Next, let’s connect all the parts to the viewController.swift file and see the results!
Wallet Backend
Switching to ViewController.swift, we can see that all the UI components are connected. All we need to do is process the transaction and print it to the console. Before we begin, however, we should talk a little bit about the Bitcoin blockchain. Bitcoins come from a master account, let’s say the account number is 000. When you mine a bitcoin, you solve a math problem and receive a certain amount of bitcoin as a reward. It’s a clever way to create currency, and it creates an incentive for more people to tap it. In our App, we offer 100 BTC as a reward. First, let’s add the required variables to the ViewController:
let firstAccount = 1065
let secondAccount = 0217
let bitcoinChain = Blockchain(a)let reward = 100
var accounts: [String: Int] = ["0000": 10000000]
let invalidAlert = UIAlertController(title: "Invalid Transaction", message: "Please check the details of your transaction as we were unable to process this.", preferredStyle: .alert)
Copy the code
We define two accounts: one numbered 1065 and the other numbered 0217. We also added a bitcoinChain variable as our blockchain and set the reward to 100. We need a master account as the source of bitcoin: here’s our initial account, 0000, which holds 10 million bitcoins. You can use this account as a bank, and for every reward, 100 bitcoins will be withdrawn and transferred to a legitimate account. We also define a warning to display each time a transaction cannot be completed.
Now, let’s write some generic functions that will be executed. Can you guess what these functions are?
- The first function is used to process transactions. We need to make sure that the amount received or deducted from the sender’s and recipient’s accounts is correct and that this information is recorded on our blockchain.
- The next function is to print the complete record in the console, showing each block and the data within each block.
- The last function is used to verify that the blockchain is legitimate by verifying that the hash of the previous block matches the information of the next block. Since we will not demonstrate any hacking methods, the chain in this example will always be legal.
The Transaction function
The following is our generic transaction function. Enter the following code under the definition variable:
func transaction(from: String, to: String, amount: Int, type: String) {
/ / 1
if accounts[from] == nil {
self.present(invalidAlert, animated: true, completion: nil)
return
} else ifaccounts[from]! -amount <0 {
self.present(invalidAlert, animated: true, completion: nil)
return
} else{ accounts.updateValue(accounts[from]! -amount, forKey: from) }/ / 2
if accounts[to] == nil {
accounts.updateValue(amount, forKey: to)
} else{ accounts.updateValue(accounts[to]! +amount, forKey: to) }/ / 3
if type == "genesis" {
bitcoinChain.createGenesisBlock(data: "From: \(from); To: \(to); Amount: \(amount)BTC")}else if type == "normal" {
bitcoinChain.createBlock(data: "From: \(from); To: \(to); Amount: \(amount)BTC")}}Copy the code
It may seem like a lot of code, but the core of it is to define some rules for each transaction. At the beginning, we have four arguments: to, from, amount, and type. To, From, and Amount are obvious, and Type is basically the Type that defines the transaction. There are two types: Normal and Genesis. A Normal transaction type would be between account 1065 and 0217, whereas a Genesis transaction type would involve account 0000.
- The first if-else condition is about the source account. If the source account does not exist or the amount is insufficient, we display an invalid transaction warning and close the function. And if it passes, we update it.
-
The second if-else condition is about the receiving account. If the receiving account does not exist, we go with it and close the function. Otherwise, we send the correct number of Bitcoins to the account.Copy the code
- The third if-else conditional handles the type of transaction. If a transaction involves an initial block, we create a new initial block; Instead we create a new block to store the data.
Printing function
At the end of each transaction, we want to see a list of all transactions to make sure we know everything that happened. Here is the code we entered under the Transaction function:
func chainState(a) {
for i in 0. bitcoinChain.chain.count-1 {
print("\tBlock: \(bitcoinChain.chain[i].index!)\n\tHash: \(bitcoinChain.chain[i].hash!)\n\tPreviousHash: \(bitcoinChain.chain[i].previousHash!)\n\tData: \(bitcoinChain.chain[i].data!)")
}
redLabel.text = "Balance: \(accounts[String(describing: firstAccount)]!) BTC"
blueLabel.text = "Balance: \(accounts[String(describing: secondAccount)]!) BTC"
print(accounts)
print(chainValidity())
}
Copy the code
This is a simple for loop that contains each block of bitcoinChain. We print out the block numbers, hash values, hash of previous blocks, and stored data, and then update the UILabel to show the correct number of BTCS in each account. Finally, print out a list of each account (there should be three) and verify that the chain is valid. Now, you should have an error in the last line of the function. This is because we haven’t defined the chainValidity() function yet, so let’s start!
The gnosis.xml.validity function
Remember, if the hash value of the previous block matches what the current block describes, then the chain is legal. We can easily validate each block repeatedly with another for loop.
func chainValidity(a) -> String {
var isChainValid = true
for i in 1. bitcoinChain.chain.count-1 {
ifbitcoinChain.chain[i].previousHash ! = bitcoinChain.chain[i-1].hash {
isChainValid = false}}return "Chain is valid: \(isChainValid)\n"
}
Copy the code
Somewhat like before, we repeatedly validate each block in bitcoinChain to verify that the hash value of the previous block matches what the current block describes. And you’re done! We have defined functions and will use them every time! Your viewController.swift should now look like this:
Now all we need to do is attach the button to the function, and let’s begin the final chapter!
To connect everything together
When our App starts up for the first time, we want the initial account 0000 to send 50 BTC to our first account. We will then have the first account transfer 10 BTC to the second account. This step can be accomplished with only three stroke codes. Change your viewDidLoad function like this:
override func viewDidLoad(a) {
super.viewDidLoad()
transaction(from: "0000", to: "\(firstAccount)", amount: 50, type: "genesis")
transaction(from: "\(firstAccount)", to: "\(secondAccount)", amount: 10, type: "normal")
chainState()
self.invalidAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))}Copy the code
We use the previously defined function and call chainState() at the end. Also, we added an OK button to the warning of invalid transactions. Now let’s see what goes into the remaining four functions: redMine(), blueMine(), redSend(), and blueSend().
Mining function
Mining function is very simple, just three stroke code on the line. This is the code we want to add:
@IBAction func redMine(_ sender: Any) {
transaction(from: "0000", to: "\(firstAccount)", amount: 100, type: "normal")
print("New block mined by: \(firstAccount)")
chainState()
}
@IBAction func blueMine(_ sender: Any) {
transaction(from: "0000", to: "\(secondAccount)", amount: 100, type: "normal")
print("New block mined by: \(secondAccount)")
chainState()
}
Copy the code
In the first mining function, we use the Transaction function to transfer 100 BTC from the initial account to the first account, printing a block to be mined, and then printing the chainState. Similarly, we pass 100 BTC to the second account in the blueMine function.
Transfer function
The transport function is also slightly similar to the previous function.
@IBAction func redSend(_ sender: Any) {
if redAmount.text == "" {
present(invalidAlert, animated: true, completion: nil)}else {
transaction(from: "\(firstAccount)", to: "\(secondAccount)", amount: Int(redAmount.text!) ! , type:"normal")
print("\(redAmount.text!) BTC sent from \(firstAccount) to \(secondAccount)")
chainState()
redAmount.text = ""}}@IBAction func blueSend(_ sender: Any) {
if blueAmount.text == "" {
present(invalidAlert, animated: true, completion: nil)}else {
transaction(from: "\(secondAccount)", to: "\(firstAccount)", amount: Int(blueAmount.text!) ! , type:"normal")
print("\(blueAmount.text!) BTC sent from \(secondAccount) to \(firstAccount)")
chainState()
blueAmount.text = ""}}Copy the code
First, we verify that the text field in redAmount or blueAmount is null. If so, we display a warning that the transaction is invalid. If not, we can move on. We use the Transaction function to enter the amount and set the transaction to normal to transfer the amount from the first account to the second account (or vice versa). We print out the amount to be transferred and then call the chainState() function. Finally, empty the text field. And there we are! Make sure your code matches what is shown below.
Try executing the App! From the front end, it looks like a normal trading App, but you’ll see how it works in the background. Try using the App to trade BTC from one account to another, and try to trick the App!
conclusion
In this tutorial, you learned how to use Swift to set up a blockchain and set up your own Bitcoin transactions. Note that in the real cryptocurrency background, the implementation part is a completely different thing as it needs to be dispersed by smart contracts, but the demonstration above is for learning. In this example, we use Bitcoin as a cryptocurrency, but can you think of any other uses for blockchain? Feel free to share your thoughts in the comments below! Hope you learn something new here! You can download the full project on Github for reference.
Complete projects: https://github.com/appcoda/BlockchainDemo the original link: https://www.appcoda.com/blockchain-introduction/
Reprinted from AppCoda, a high quality teaching sharing platform focused on Swift.