Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use go language Block chain to realize simple Block and Block chain

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "how to use go language block chain to achieve simple block and block chain". In the operation of actual cases, many people will encounter such a dilemma, and then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

The actual combat byte field of the block chain indicates the version number of the block in version 4, indicating that the verification rule 32 the parent block header hash value of the previous block is the hash value of the Merkle tree root of the previous block. The SHA256 is also used to calculate the hash value of the Merkle tree root traded in the block, and the SHA256 is also used to calculate the approximate time produced by the 4 timestamp of the block. The UNIX timestamp accurate to seconds must be strictly greater than the median time of the previous 11 blocks. At the same time, the whole node will also reject the block 4 difficulty target with a timestamp of more than two hours. the block workload proves the difficulty target of the algorithm, and has used a specific algorithm to code 4Nonce to find the random number set to meet the difficulty goal in the future. in order to solve the problem that 32 random numbers are not enough in the case of skyrocketing computing power, it is stipulated that the timestamp and coinbase transaction information are changed, so as to expand the number of nonce digits.

Note: the hash value is not stored in the block, and the node accepts the block and calculates it independently and stores it locally.

Version 1 Block related:

1. Define the structure of a block Block

a. Block head: 6 field

b. Blocks: strings represent data

two。 Provides a method for creating chunks

NewBlock (parameter)

Block chain correlation

Define a block chain structure BlockChain

Block array

Provides a method for creating BlockChain ()

NewBlockChain ()

Provide a way to add blocks

AddBlock (parameter)

Block.go file

Package mainimport ("bytes"crypto/sha256"time") / * 1. Define the structure of a block Blocka. Block head: 6 fields b. Block: the string represents the data*/// block type Block struct {Version int64 / / version PerBlockHash [] byte / / the hash value of the previous block Hash [] byte / / the hash value of the current block To simplify the code MerKelRoot [] byte / / Meckergen TimeStamp int64 / / time extract Bits int64 / / difficulty value Nonce int64 / / Random value / / Block Data [] byte / / transaction information} / * provide a method to create a block NewBlock (parameter) * / func NewBlock (data string) PrevBlockHash [] byte) * Block {var block Block block = Block {Version: 1, PerBlockHash: prevBlockHash, / / Hash: [] byte {}, / / blocks do not store hash values After accepting the block, the node is calculated independently and stored locally. MerKelRoot: [] byte {}, TimeStamp: time.Now () .Unix (), Bits: 1, Nonce: 1, Data: [] byte (data) } block.SetHash () / / fill in Hash return & block} func (block * Block) SetHash () {/ / inside the source code is the two-dimensional slice func Join (s [] [] byte, sep [] byte) [] byte tmp: = [] [] byte {IntToByte (block.Version), block.PerBlockHash, block.MerKelRoot IntToByte (block.TimeStamp), IntToByte (block.Bits), IntToByte (block.Nonce),} data:=bytes.Join (tmp) [] byte {}) / / then calculate hash hash: = sha256.Sum256 (data) block.Hash = hash [:] / / variable slice} / / original block func NewGensisBlock () * Block {return NewBlock ("Genesis Block!", [] byte {})}

BlockChain.go file

Package main/*1. Define a blockchain structure BlockChain Block array * / type BlockChain struct {blocks [] * Block} / * 2. Provide a method to create BlockChain () NewBlockChain () * / func NewBlockChain () * BlockChain {block: = NewGensisBlock () return & BlockChain {blocks: [] * Block {block}} / / create a chunk chain with only one element, initialize} / * 3. Provide a method to add blocks AddBlock (parameter) * / func (bc * BlockChain) AddBlock (data string) {PerBlockHash: = bc.blocks [len (bc.blocks)-1] .Hash / / the hash of this block is the hash value of the previous block block: = NewBlock (data,PerBlockHash) bc.blocks = append (bc.blocks,block)}

Utils.go file

Package mainimport ("bytes"encoding/binary"fmt"os") func IntToByte (num int64) [] byte {/ / func Write (w io.Writer, order ByteOrder, data interface {}) error {var buffer bytes.Buffer err: = binary.Write (& buffer, binary.BigEndian, num) CheckErr ("IntToByte", err) return buffer.Bytes ()} func CheckErr (position string,err error) {if err! = nil {fmt.Println ("error, pos:" Position,err) os.Exit (1)}}

Main.go file

Package mainimport "fmt" func main () {bc: = NewBlockChain () bc.AddBlock ("A send B 1BTC") bc.AddBlock ("B send C 1BTC") for _, block: = range bc.blocks {fmt.Printf ("Version:% d\ n", block.Version) fmt.Printf ("PerBlockHash:% x\ n", block.PerBlockHash) fmt.Printf ("Hash:% x\ n" Block.Hash) fmt.Printf ("MerKelRoot:% x\ n", block.MerKelRoot) fmt.Printf ("TimeStamp:% d\ n", block.TimeStamp) fmt.Printf ("Bits:% d\ n", block.Bits) fmt.Printf ("Nonce:% d\ n", block.Nonce) fmt.Printf ("Data:% s\ n", block.Data)}}

Execution result

This is the end of the content of "how to use go language block chain to achieve simple block and block chain". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development