"Blockchain go language Implementation" Part I: Basic blockchain prototype

Source: Internet
Author: User

0x00 Introduction

Blockchain (Blockchain) is one of the most revolutionary technologies of the 21st century, and it is still in its maturing stage, and its development potential has not been fully realized. Essentially, a blockchain is just a distributed database of records. But it's unique because it's not a private database, it's a public database, which means that every person who uses it has a full or partial copy of the data. Also, new records can be added to the blockchain only if the other holders of the database agree. In addition, it is the blockchain that makes cryptocurrency and smart contracts possible.

In this series of articles, we will build a simple crypto currency based on the blockchain.

0x01 Chunks

First, we start with the "chunks" section of "Blockchain". In a blockchain, chunks are blocks that store valuable information. For example, Bitcoin chunks are used to store transactions, which is the essence of any kind of cryptocurrency. In addition, chunks contain technical information, such as its version, the current timestamp, and the hash value of the previous chunk (the hashes).

In this article, we are not going to implement the chunk described in the blockchain or Bitcoin specification, but rather use its simplified version, that is, the chunk structure we are going to implement contains only important information. The following code is for our block structure:

type Block struct {    Timestamp     int64    Data          []byte    Prevblockhash [] byte     Hash          []byte}

Timestamp (timestamp) is the timestamp of the block creation time, data is the actual valuable information contained in the chunk, prevblockhas the hash value of the previous chunk, and the hash is the hash value of the current chunk. In the Bitcoin specification, Timestamp, Prevblockhash, and hash are chunk headers, which form a separate data structure, and the transaction (in our case, data) is a separate data structure. For the sake of simplicity, we'll mix them here.

So how do you calculate the hash value? The hash value is computed as a very important feature of the blockchain, which makes the blockchain secure. Calculating the hash value of a chunk is a computationally difficult operation, even if it takes some time on a fast computer (that's why people buy a powerful GPU to dig bitcoins). This is an intentional architectural design that makes it difficult to add new chunks, thus preventing tampering with existing chunks. We will discuss and implement this mechanism in a future article.

Now, we'll just use the chunk fields, connect them, and compute a SHA-256 hash value on the concatenated combination. Below, we use the Sethash method to do this:

Func (b *Block) Sethash () {    timestamp:= []byte)    headers:= bytes. Join ([]byte{b.prevblockhash, b.data, timestamp}, []byte{})    hash:= sha256. Sum256 (headers)    = hash[:]}

Next, in accordance with the Golang Convention, we will implement a function to simplify the creation of chunks:

string, Prevblockhash []byte) *block {    block:= &block{time. Now (). Unix (), []byte(data), Prevblockhash, []byte{}}    block. Sethash ()    return block}

In this way, we are ready to work on the block!

0x02 block Chain

Now, let's implement a blockchain. Essentially, a blockchain is just a database that contains certain structures: It's an ordered list of backlinks. This means that chunks are stored in the order in which they are inserted, and each chunk is linked to the previous chunk. This structure ensures fast access to the latest chunks in a blockchain, and is able to obtain the chunk efficiently through the chunk hash value.

In Golang, you can use an array and a map to implement this structure: arrays are used to hold ordered hashes (arrays in Go are ordered), and map is used to hold hash-and chunk pairs (map is unordered). However, for our blockchain prototypes, we only use an array, because now we do not need to get the corresponding chunk through the hash column of the chunk.

type Blockchain struct {    blocks []*Block}

This is our first blockchain and I never thought it would be so easy.

Now we implement the ability to add chunks:

string {    prevblock:= Bc.blocks[len (bc.blocks)-1]    newblock:= newblock (data, Prevblock.hash)    = append (bc.blocks, Newblock)}

Is that it? No!

To add a new chunk to the blockchain, we need to make sure that a chunk exists, but there is no chunk in our blockchain at the moment. Therefore, in any blockchain, there must be at least one chunk, and the first chunk in the blockchain is called the creation block. Below, we implement a method to create a Genesis block:

Func newgenesisblock () *block {    return Newblock ("Genesis block", [] byte {})}

Now, we can implement a function to create a blockchain using the Genesis block:

Func newblockchain () *Blockchain {    &blockchain{[]*block{newgenesisblock () }}}

Let's check to see if our blockchain is working properly:

Func Main () {BC:=newblockchain () BC. Addblock ("Send 1 BTC to Ivan") BC. Addblock ("Send 2 more BTC to Ivan")     for_, Block: =Range Bc.blocks {FMT. Printf ("Prev. Hash:%x\n", block. Prevblockhash)FMT. Printf ("Data:%s\n", block. Data)FMT. Printf ("Hash:%x\n", block. Hash)FMT. Println ()}}

The output results are as follows:

12 more BTC to Ivanhash: 561237522bb7fcfbccbc6fe0e98bbbde7427ffe01c6fb223f7562288ca2295d1

With the above results, we can make sure that the blockchain is working properly.

0x03 Conclusion

In this article, we created a very simple blockchain prototype: It's just a chunk array, where each chunk has a link to the previous chunk, but the actual blockchain is much more complex. In our blockchain, adding new chunks is simple and fast, but adding blocks to the actual blockchain requires some work: before gaining permission to add chunks, the chunk add-on (or node) must perform some heavy computations (this mechanism is known as proof of work, PROOF-OF-WORK,POW). In addition, blockchain is a distributed database, so there is no single decision maker. Therefore, a new chunk must be confirmed and approved by other participants in the network (this mechanism is known as the consensus mechanism). Finally, there are no deals in our blockchain yet!

In the following articles we will discuss these functions and features gradually.

English Link: https://jeiwan.cc/posts/building-blockchain-in-go-part-1/

"Blockchain go language Implementation" Part I: Basic blockchain prototype

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.