Use go to build blockchain--1. Basic prototypes

Source: Internet
Author: User

This article began to enter the "Go to build Blockchain" series, mainly for the original translation. This article corresponds to the following text:

Building Blockchain in Go. Part 1:basic Prototype

Words do not say much, began to enter the text.

1. Introduction

Blockchain is one of the most revolutionary technologies of the 21st century, it is still evolving, and its potential is not fully understood. Essentially, a blockchain is just a distributed database. However, it is unique in that it is not a private database, but rather a public one, where each person who uses it has all or part of its copy. New records can be added only if they are approved by other database administrators. Because of this blockchain, crypto currency and smart contracts are made possible.

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

2. Block

We start with the chunks section of the blockchain. In a blockchain, it stores valuable information. For example, the Bitcoin block stores transaction information, which is the essence of all crypto currencies. In addition, chunks contain technical information such as the version number, the current timestamp, and the hash of the previous chunk.

In this article, we will not implement the chunks described in the blockchain, nor the chunks in the Bitcoin specification, but rather use a simplified version that contains only important information. This is what it looks like:

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

Timestampis the current timestamp (when the chunk is created), Data is the actual valuable information contained in the chunk, and Hash is the hash of the current chunk. In the Bitcoin specification, and the Timestamp PrevBlockHash Hash chunk header, they form a separate data structure, and the trade (in our case, the data) is a separate data structure. We're all mixed up here for the sake of simplicity.

So, how do we calculate the hash? Hashing is a very important feature in the blockchain, which makes the blockchain more secure. The problem is that calculating a hash is a difficult operation to calculate, and it can take a lot of time even on a very fast computer (that's why people buy a powerful GPU to dig bitcoins). This is an architecturally intentional design, which makes it difficult to add new chunks, preventing post-addition modifications. We will discuss and implement this mechanism in the next article.

Now we've only taken the chunk fields and stitched them together and computed the SHA-256 hash on the concatenated combination. Let's SetHash do these things in the method:

func (b *Block) SetHash() {    timestamp := []byte(strconv.FormatInt(b.Timestamp, 10))    headers := bytes.Join([][]byte{b.PrevBlockHash, b.Data, timestamp}, []byte{})    hash := sha256.Sum256(headers)    b.Hash = hash[:]}

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

func NewBlock(data string, prevBlockHash []byte) *Block {    block := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}}    block.SetHash()    return block}

All right, this is the chunk!

3. Block chain

Now let's implement a blockchain. Its essential blockchain is simply a database with a specific structure: it is an orderly, tail-linked list. This means that chunks are stored in the order in which they are inserted, and each chunk is linked to the previous block. The structure allows fast access to the latest block in the chain and obtains chunks through its hash (valid).

In Golang, this structure can be implemented by using arrays and maps: An array stores an ordered hash (in Golang, an array is ordered), and the map structure can hold hash -> block matching information. But in our blockchain prototype, we only use an array, because we don't need the hash to get the chunk information for the time being.

type Blockchain struct {  blocks []*Block}

This is our first block chain! I never thought it would be so easy

Now, let's add a chunk to it:

func (bc *Blockchain) AddBlock(data string) {    prevBlock := bc.blocks[len(bc.blocks)-1]    newBlock := NewBlock(data, prevBlock.Hash)    bc.blocks = append(bc.blocks, newBlock)}

That's it! Still is?

To add a new chunk, we need an existing chunk, but we don't have a chunk on our blockchain! Therefore, there must be at least one chunk in any blockchain, and this chunk is the first chunk in the chain, called the Genesis Block. Let's implement a function to create a Genesis block:

func NewGenesisBlock() *Block {    return NewBlock("Genesis Block", []byte{})}

Now, we can implement a function that creates a blockchain that contains the Genesis block:

func NewBlockchain() *Blockchain {    return &Blockchain{[]*Block{NewGenesisBlock()}}}

Now, let's check to see if the Blockchain works:

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()    }}

Output:

Prev. hash:Data: Genesis BlockHash: aff955a50dc6cd2abfe81b8849eab15f99ed1dc333d38487024223b5fe0f1168Prev. hash: aff955a50dc6cd2abfe81b8849eab15f99ed1dc333d38487024223b5fe0f1168Data: Send 1 BTC to IvanHash: d75ce22a840abb9b4e8fc3b60767c4ba3f46a0432d3ea15b71aef9fde6a314e1Prev. hash: d75ce22a840abb9b4e8fc3b60767c4ba3f46a0432d3ea15b71aef9fde6a314e1Data: Send 2 more BTC to IvanHash: 561237522bb7fcfbccbc6fe0e98bbbde7427ffe01c6fb223f7562288ca2295d1

Yes, that's it!

4. Summary

We've built a very simple blockchain prototype: It's just an array of chunks, each of which is connected to the previous one. The real blockchain is much more complicated than this. Adding new chunks in our blockchain is very simple and good, but adding blocks to the real blockchain requires a lot of work: one is to do some complex calculations before adding chunks to get permission to add chunks (this process is called 工作量证明 ). In addition, blockchain is a distributed database, it does not have a single decision-maker. Therefore, a new chunk must be recognized and agreed upon by other participants in the network (this mechanism is known as consensus). Moreover, our blockchain has not been traded!

In a future article, we'll cover these features.

Link:
1. Access Source: https://github.com/Jeiwan/blockchain_go/tree/part_1
2. Chunk Hashing algorithm: Https://en.bitcoin.it/wiki/Block_hashing_algorithm

Because the level is limited, the translation quality is not very good, welcome everybody to shoot the brick.

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.