In this blog, we are going to learn how you can create a blockchain in the Golang programming language from scratch. Before we get started, it is imperative that you are aware of the fundamental concepts in Golang. I hope you have been going through the blog posts posted on Golang.Company. In this tutorial, we will also cover the Go module system.
Let’s Get Started with the Program
In order to get started, we will create a new directory. Let’s name this directory ‘blockchain’. For this, we will have to code in the Command Prompt (or if you are using macOS or Linux, then you have to use the Terminal). So we type:
cd go-workspace
mkdir blockchain
cd blockchain
code .
With the last statement, the VS Code launches (my preference of text editor). You can use any other IDE or text editor.
Next, the application that I will write on Command Prompt will be recognized by the compiler
go mod init github.com/golang-company/blockchain
I am hereby specifying the name of the module that I have created. Upon execution of the command, you will notice that you will have a new file inside of the folder ‘blockchain’. And this file is the go.mod file.
We will now go ahead and write the application inside main.go. We will also bring in third-party libraries. In order to show how this works with the Go module system, I will create an instance first.
package main
import (
“fmt”
“rsc.io/quote”
)
func main() {
fmt.Println(quote.Hello())
}
The rsc.io/quote library that we have imported enables us to get hold of various strings and then print them out. (Note: If you do not have the rsc.io/quote installed, you have to get it. For this, you have to type on the Terminal: go get rsc.io/quote
and it will get downloaded.)
Now, let’s run this program on the Terminal, we will get the following output:
You will notice that there is another file created under the ‘blockchain’ directory named ‘go.sum’. It consists of all the dependencies for the third-party library that we have incorporated into our application.
Now that you have got insight into the basic concept required for this tutorial, let us proceed to the main topic of blockchain in Golang.
A blockchain can be stated as a public database that is distributed and decentralized across a number of different peers. With blockchain, even if the node is generating incorrect data, the database has the ability to fix itself. That is what makes blockchain different than other distributed solutions. The database does not have to “trust” the nodes, which is why it enables you to implement an application of cryptocurrency, smart contracts, etc.
The blockchain consists of a number of different blocks. Every block consists of the data that we wish to transmit inside the database, and hash that is associated with the block. It also consists of the cryptographic hash of the previous block. Thus, in order to represent this, we will have to create a struct.
We will get started with the programming in go blockchain. We will be erasing the previous program and starting afresh in ‘main.go’.
package main
import (
“bytes”
“crypto/sha256”
“fmt”
)
type Cryptoblock struct {
Hash [] byte
Data [] byte
PrevHash [] byte
}
func (c *Cryptoblock) BuildHash() {
details := bytes.Join([][] byte{c.Data, c.PrevHash}, []byte{})
hash := sha256.Sum256(details)
c.Hash = hash[ : ]
}
(Note: The sha256 algorithm is extremely simple in comparison to the actual way to estimate the hash for a blockchain. We will demonstrate how the hash changes with the change in data)func BuildBlock (data string, prevHash [] byte) *Cryptoblock {
block := &Cryptoblock{[]byte{}, []byte(data), prevHash}
block.BuildHash()
return block
}
type BlockChain struct {
blocks []*Cryptoblock
}
func (chain *BlockChain) AddBlock(data string) {
prevBlock := chain.blocks[len(chain.blocks)-1]
new := BuildBlock(data, prevBlock.Hash)
chain.blocks = append(chain.blocks, new)
}
func Inception() *Cryptoblock {
return BuildBlock("Inception", []byte{})
}
func main() {
chain := InitBlockChain()
chain.AddBlock("First Block after Inception”)
chain.AddBlock("Second Block after Inception")
chain.AddBlock("Third Block after Inception")
for _, block := range chain.blocks {
fmt.Printf("Previous Hash: %x\n", block.PrevHash)
fmt.Printf("Data in Block: %s\n", block.Data)
fmt.Printf("Hash: %x\n", block.Hash)
}
}
fmt.Printf("Previous Hash: %x\n", block.PrevHash)
fmt.Printf("Data in Block: %s\n", block.Data)
fmt.Printf("Hash: %x\n", block.Hash)
Let us check out the Output:
As you can see, the program has run successfully. We are able to see the Data in the Block and the Hash for Inception. Since Inception has no previous block block, there is no previous hash. For the following results, we get to see the previous hash, the data and the hash of that particular block.
All of the code that has been explained in this tutorial will be available on Github at https://github.com/GolangCompany/blockchain/blob/main/main.go
Hopefully, you were able to understand the program and the concept of blockchain in Golang. It is imperative that you try it out by yourself in "Go development." Only then will you be able to grasp the concept. Happy coding!