Use go to build a block chain----Part 1: Basic prototype _ block chain

Source: Internet
Author: User
Tags prev

The translation of the series of articles I have put on the GitHub: blockchain-tutorial, follow-up updates will be on the GitHub, may not be synchronized here. If you want to run the code directly, you can also clone GitHub on the Tutorial warehouse and go to the SRC directory to execute make. Introduction

Block chain is one of the most revolutionary technologies in the 21st century, it is still in the growing stage, and there are many potential has not yet emerged. In essence, the block chain is just a distributed database. What makes it unique, however, is that the chunk chain is an open database, not a private database, that is, each person who uses it has a full or partial copy. New records can be added to the database only with the consent of the other database administrator. Moreover, it is because of the block chain that makes the cryptographic currency and the smart contract a reality.

In this series of articles, we will implement a simplified version of the Block chain, based on which to build a simplified version of the encrypted currency. Block

Let's start with "chunks" in the "Block chain". In a block chain, a chunk is a block that stores valid information. For example, the useful information stored in bitcoin blocks is Bitcoin trading, and transaction information is the essence of all cryptographic currencies. In addition, the blocks also contain technical information, such as the version, the current timestamp, and the hash of the previous block.

In this article, we do not implement a block chain as described in the Bitcoin specification, but instead implement a simplified version of the Block chain, which contains only a few key information. It looks like this:

Type block struct {
    Timestamp     int64
    Data          []byte
    prevblockhash []byte
    Hash          []byte
}
Timestamp is the current timestamp, which is the time the block was created. Data is the actual and effective information that is stored in the block. Prevblockhash stores the hash of the previous block. Hashing is the hash of the current block.

In the Bitcoin specification, Timestamp, Prevblockhash, Hash is the chunk header (block header), and the chunk header is a separate data structure. And the transaction, which is here, is another separate data structure. For the sake of simplicity, I mixed the two together.

So how do we compute the hash? How to compute the hash is a very important part of the block chain. It is this feature that makes the chain of blocks safe. Calculating a hash is a very difficult operation to compute. Even on high-speed computers, it takes time (which is why people buy GPU to dig bitcoin). This is an intentional architectural design that makes it very difficult to add new blocks, so it is hard to make changes once the blocks are added. In the next few articles in this series, we will discuss and implement this mechanism.

Currently, we take only a few fields of the block structure (Timestamp, Data, and Prevblockhash), connect them to each other, and then compute a SHA-256 hash on the result of the connection. Let's complete this task in the Sethash method:

Func (b *block) Sethash () {
    timestamp: = []byte (StrConv. Formatint (B.timestamp))
    headers: = bytes. Join ([][]byte{b.prevblockhash, B.data, timestamp}, []byte{})
    Hash: = sha256. Sum256 (headers)

    B.hash = hash[:]
}

Next, according to Golang's convention, we implement a function that simplifies the creation of a block:

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

That's the whole story of the chunk. Block chain

Now let's implement a block chain. In essence, a block chain is only a database with a specific structure, and is a list of ordered, back links. This means that the blocks are stored in the order in which they are inserted, and each block is connected to the previous block. Such a structure allows us to quickly get the latest block on the chain and efficiently retrieve a block via hash.

In Golang, this structure can be implemented by an array and a map: array stores ordered hashes (Golang array is ordered), map storage hask-> block pair (Golang, map is unordered). But in the basic prototype phase, we only use array, because we do not need to get the block by hash now.

Type blockchain struct {
    blocks []*block
}

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

Now, let's add a block 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)
}

Complete. But is that really the case?

In order to add a new block, we have to have an existing block, but now our chain is empty, not one block. So, in any block chain, there must be at least one block. Such a block, which is the first block in the chain, is usually called the Genesis block (Genesis blocks). Let's implement a way to create a Genesis block:

Func Newgenesisblock () *block {return
    newblock (' Genesis block ', []byte{}]
}

Now we can implement a function to create a block chain with a Genesis block:

Func Newblockchain () *blockchain {return
    &blockchain{[]*block{newgenesisblock ()}}
}

To check whether our block chain is working as scheduled:

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 block
hash:aff955a50dc6cd2abfe81b8849eab15f99ed1dc333d38487024223b5fe0f1168

Prev. hash:aff955a50dc6cd2abfe81b8849eab15f99ed1dc333d38487024223b5fe0f1168
Data:send 1 BTC to Ivan
hash:d75ce22a840abb9b4e8fc3b60767c4ba3f46a0432d3ea15b71aef9fde6a314e1

Prev. Hash: D75ce22a840abb9b4e8fc3b60767c4ba3f46a0432d3ea15b71aef9fde6a314e1
data:send 2 BTC to Ivan
Hash: 561237522bb7fcfbccbc6fe0e98bbbde7427ffe01c6fb223f7562288ca2295d1

Summarize

We created a very simple block-chain prototype: It's just a series of blocks of an array, each of which is associated with the previous block. The real block chain is much more complex than this. In our block chain, adding new blocks is very simple and quick, but in a real block chain, adding a new block requires a lot of work: you have to go through a very heavy calculation (a mechanism called work proof) to get the power to add a new block. Moreover, the block chain is a distributed database without a single decision maker. Therefore, a new block must be recognized and agreed by other participants in the network (this mechanism is called consensus (consensus)). There's also a bit of our block chain that hasn't been traded yet.

We will cover these features in the next article.

The source code involved in this article: part_1

Chunk Hash Algorithm: Https://en.bitcoin.it/wiki/Block_hashing_algorithm

Original:

Building blockchain in go. Part 1:basic 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.