Introduction to Blockchain Programming

I guess very few of my readers haven’t heard about BitCoin or Ethereum. Just when BitCoin started, one of my acquaintances wanted me to buy into it. I am a sceptic—always been, will probably always be—it’s hard-printed into my DNA. Before I go too far off-topic, let me stop here. I may not be completely into BitCoin and all the other cryptocurrencies (or digital currencies, or virtual currencies) such as Ethereum, Dogecoin, BlackCoin, Nxt, LiteCoin, PeerCoin, and Dash, but I do love the technology behind it: the BlockChain.

What Is the BlockChain?

A blockchain is a continuously growing ledger of facts, replicated across a peer-to-peer network. Facts can range from monetary transactions to content signatures. A blockchain is a distributed and a decentralized digital ledger that can be used to record transactions across numerous computers. This means that the record cannot be retroactively altered without the alteration of all subsequent blocks and the collusion of the network.

Each block in the BlockChain contains a hash pointer as a link or reference to a previous block, transaction data, and a timestamp. Blockchains are resistant to modification of the data. A Blockchain serves as an open and distributed ledger that can record transactions between different two parties a verifiable and permanent way.

A Blockchain database consists of two kinds of records: blocks and transactions. Blocks hold batches of valid transactions that are hashed and encoded into a hash tree (a hash tree is a tree in which every leaf node is labeled with a data block, and every non-leaf node is labeled with the cryptographic hash of the labels of its child nodes). Each block includes the hash of the previous block in the Blockchain, linking the two.

Cryptocurrencies

A cryptocurrency is a digital medium of exchange that makes use of cryptography to secure transactions and to control creation of additional units of the currency. Miners help maintain the integrity, safety, and balance Cryptocurrency ledgers, by using their computers to help validate and timestamp transactions. Some of the most popular Cryptocurrencies are the following:

  • BitCoin
  • Ethereum
  • Dogecoin
  • BlackCoin
  • Nxt
  • LiteCoin
  • PeerCoin

BitCoin

BitCoin is the first decentralized digital currency. BitCoin is peer-to-peer, and transactions take place between users directly. These transactions are verified by network nodes and then recorded in a public-distributed ledger called a blockchain.

Ethereum

Ethereum is an open-source, blockchain-based distributed computing platform using smart contract scripting. Ethereum provides a decentralized Turing-complete virtual machine which can execute scripts using an international network of public nodes.

Dogecoin

Despite being introduced as a “joke currency” in 2013, Dogecoin quickly developed its own online community and reached a capitalization of $60 million in January 2014. In June 2017, it had a capitalization of $340 million.

BlackCoin

BlackCoin is also a peer-to-peer cryptocurrency. BlackCoin is open source and uses a proof-of-stake system. BlackCoin secures its network through a process called minting.

Nxt

Nxt is an open source cryptocurrency network. Nxt also uses a proof-of-stake system to reach consensus for transactions. Thus, it creates a static money supply and, unlike BitCoin, no mining is necessary.

LiteCoin

Litecoin has a lot of technical improvements over BitCoin, such as the adoption of the Lightning Network. Lightning Network uses an off-chain protocol and it features a P2P system for making micropayments of digital currencies such as BitCoin and LiteCoin through a scale-free network of bidirectional payment channels, without having to delegate custody of funds or trust to third parties.

PeerCoin

Peercoin is a peer-to-peer cryptocurrency utilizing both proof-of-stake and proof-of-work systems.

Creating a BlockChain in VB.NET

Be warned. This is not for the faint-hearted! Start Visual Studio and create a Visual Basic Class Library project. This project is loosely based on the Ethereum platform.

Add a class to your project and name it Node (or something similar). Add the following code to it:

Public Class Node

   Private btValue As Byte()
   Private btKey As Byte()

End Class

You might say that that this isn’t difficult; well, I didn’t want to scare you away with the very first code segment! Add the following class to encode Bytes to Hexadecimal and vice versa:

Imports System.IO

Public NotInheritable Class CompactEncoder

   Private Shared Delimiter As Byte = 16

   Public Shared Function CompactEncode(btHex As Byte()) As Byte()

      Dim btTerminate As Byte = 0

      If btHex(btHex.Length - 1) = Delimiter Then

         btTerminate = 1

         btHex = Encoder.RemoveLastBytes(btHex, 1)

      End If

      Dim intOddLength As Integer = btHex.Length Mod 2

      Dim intFlag As Integer = 2 * btTerminate + intOddLength

      If intOddLength <> 0 Then

         Dim btFlags As Byte() = New Byte() {CByte(intFlag)}

         btHex = Encoder.JoinByteArrays(btFlags, btHex)

      Else

         Dim btFlags As Byte() = New Byte() {CByte(intFlag), 0}

         btHex = Encoder.JoinByteArrays(btFlags, btHex)

      End If

      Dim msBuffer As New MemoryStream()

      For i As Integer = 0 To btHex.Length - 1 Step 2

         msBuffer.WriteByte(CByte(16 * btHex(i) + btHex(i + 1)))

      Next

      Return msBuffer.ToArray()

   End Function

   Public Shared Function CompactDecode(btString As Byte()) _
         As Byte()

      Dim btRes As Byte() = CompactHexDecode(btString)

      btRes = Encoder.RemoveLastBytes(btRes, 1)

      If btRes(0) >= 2 Then

         btRes = Encoder.AppendByteToArray(btRes, Delimiter)

      End If

      If btRes(0) Mod 2 = 1 Then

         btRes = Encoder.RemoveFirstBytes(btRes, 1)

      Else

         btRes = Encoder.RemoveFirstBytes(btRes, 2)

      End If

      Return btRes

   End Function

   Public Shared Function CompactHexDecode(btEncodedHexadecimal _
         As Byte()) As Byte()

      Dim chrCharacters As Char() = New Char() {"0"c, "1"c, "2"c, _
         "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c, "a"c, "b"c, _
         "c"c, "d"c, "e"c, "f"c}

      Dim btHex As Byte() = New Byte(-1) {}

      For Each btNumber As Byte In btEncodedHexadecimal

         Dim hexValue As String = btNumber.ConvertToHex()

         Dim chrHexValue As Char() = hexValue.ToCharArray()

         btHex = Encoder.AppendByteToArray(btHex, _
            CByte(Array.IndexOf(chrCharacters, chrHexValue(0))))

         btHex = Encoder.AppendByteToArray(btHex, _
            CByte(Array.IndexOf(chrCharacters, chrHexValue(1))))

      Next

      btHex = Encoder.AppendByteToArray(btHex, Delimiter)

      Return btHex

   End Function
End Class

Add the following extension module to be able to convert Bytes into Hexadecimal:

Imports System.Text


Public Module Converter

   Public Function ConvertByteArrayToUInt64(btInput As Byte()) _
         As UInt64

      If btInput.Length < 8 Then

         Dim tempArray As Byte() = New Byte(7) {}

         Array.Copy(btInput, 0, tempArray, (tempArray.Length - _
            btInput.Length), btInput.Length)

         Array.Reverse(tempArray)

         Return BitConverter.ToUInt64(tempArray, 0)

      End If

      Return BitConverter.ToUInt64(btInput, 0)

   End Function

   Private ReadOnly HexStringTable As String() = New String() _
      {"00", "01", "02", "03", "04", "05", "06", "07", "08", _
      "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", _
      "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", _
      "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", _
      "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", _
      "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", _
      "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", _
      "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", _
      "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", _
      "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", _
      "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", _
      "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", _
      "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", _
      "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", _
      "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", _
      "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", _
      "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", _
      "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", _
      "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", _
      "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", _
      "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", _
      "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", _
      "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", _
      "e5", "e6", "e7", "e8", "e9", "ea", "be", "ec", "ed", "ee", _
      "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", _
      "f9", "fa", "fb", "fc", "fd", "fe", "ff"}

   <System.Runtime.CompilerServices.Extension>

   Public Function ConvertToHex(btVal As Byte()) As String

      Dim sbString As New StringBuilder()

      If btVal IsNot Nothing Then

         For Each b As Byte In btVal

            sbString.Append(HexStringTable(b))

         Next

      End If

      Return sbString.ToString()

   End Function

End Module

Add the following code to encode and decode objects received from Byte Arrays, which will be converted to hex later:

Public Class Decode

   Private uPos As UInt64
   Private oDecoded As [Object]

   Public Sub New(Pos As UInt64, Decoded As [Object])

      Me.uPos = Pos
      Me.oDecoded = Decoded

   End Sub

   Public Function GetPos() As UInt64

      Return uPos

   End Function

   Public Function GetDecoded() As [Object]

      Return oDecoded

   End Function

End Class

Imports System.Text


Public NotInheritable Class Encoder

   Public Shared Function ToHex(oInput As [Object]) As Byte()

      Dim uInput As UInt64

      Dim blnNumber As Boolean = _
         UInt64.TryParse(oInput.ToString(), uInput)

      If blnNumber Then

         Return If((uInput = 0), New Byte(-1) {}, _
            ConvertUInt64ToByteArray(uInput))

      ElseIf TypeOf oInput() Is String Then

         Dim strInput As String = DirectCast(oInput(), String)

         Return Encoding.ASCII.GetBytes(strInput.ToCharArray())

      End If

   End Function

    Public Shared Function ConvertUInt64ToByteArray(uInput _
         As UInt64) As Byte()

      Dim btBytes As Byte() = BitConverter.GetBytes(uInput)

      Array.Reverse(btBytes)

      Dim i = 0

      While btBytes(i) = 0

         i += 1

      End While

      Dim btResult As Byte() = New Byte(btBytes.Length - i - 1) {}

      Array.Copy(btBytes, i, btResult, 0, btBytes.Length - i)

      Return btResult

   End Function

   Public Shared Function JoinByteArrays(btInputA As Byte(), _
         btInputB As Byte()) As Byte()

      Dim btResult As Byte() = New Byte(btInputA.Length + _
         (btInputB.Length - 1)) {}

      Array.Copy(btInputA, 0, btResult, 0, btInputA.Length)

      Array.Copy(btInputB, 0, btResult, btInputA.Length, _
         btInputB.Length)

      Return btResult

   End Function

   Public Shared Function AppendByteToArray(btInputArr As Byte(), _
         btInput As Byte) As Byte()

      Dim btResult As Byte() = New Byte(btInputArr.Length) {}

      Array.Copy(btInputArr, 0, btResult, 0, btInputArr.Length)

      btResult(btResult.Length - 1) = btInput

      Return btResult

   End Function

   Public Shared Function RemoveLastBytes(btInput As Byte(), _
         intAmount As Integer) As Byte()

      Dim btResult As Byte() = New Byte(btInput.Length - _
         intAmount - 1) {}

      Array.Copy(btInput, 0, btResult, 0, btInput.Length - _
         intAmount)

      Return btResult

   End Function

   Public Shared Function RemoveFirstBytes(btInput As Byte(), _
         intAmount As Integer) As Byte()

      Dim btResult As Byte() = New Byte(btInput.Length - _
         intAmount - 1) {}

      Array.Copy(btInput, intAmount, btResult, 0, _
         btInput.Length - intAmount)

      Return btResult

   End Function

End Class

This is by no means all, but I have decided to stop here. Reason being: There soon will be a Part 2, where I will explain how to put the preceding classes to proper use inside a test project and add some more features.

The previous code deals with the whole logic of the blockchain, but we still need to be able to mine properly—which will come a bit later, so please be on the lookout!

Solidity

Solidity is a contract-oriented, high-level language designed to target the Ethereum Virtual Machine. You can use and program Solidity Blockchain apps straight from Visual Studio Code.

Download the extension here.

It is quite easy to set up and get started. So, if you do not want to wait for Part 2 of this series, you are welcome to follow the steps properly outlined here to get started.

Source code is available on GitHub.

Conclusion

This project is by no means 100% done, but it should give you the proper foundation to start your own blockchains. This was not as easy and quick as I thought that it would be.

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read