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 create a blockchain in go language

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article introduces how to create a block chain in go language, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Development environment

Let's assume that you already have some development experience in the Go language. After installing and configuring the Go development environment, we will also acquire some of the following dependencies:

~ $go get github.com/davecgh/go-spew/spew

Spew can help us view the struct and slice data structures directly in the terminal.

~ $go get github.com/gorilla/mux

Gorilla's mux package is so popular that we use it to write web handler.

~ $go get github.com/joho/godotenv

Godotenv can help us read the. env configuration file in the root directory of the project so that you don't have to hard-code configurations such as http ports into your code. Like this:

ADDR=8080

Next, we create a main.go file. After that, most of the work revolves around this file, so start writing code!

Import dependency packages

We import all dependent packages declaratively:

Package mainimport ("crypto/sha256", "encoding/hex", "encoding/json", "io", "log", "net/http", "os", "time", "github.com/davecgh/go-spew/spew", "github.com/gorilla/mux"github.com/joho/godotenv") data model

Then let's define a structure that represents the data model of each block that makes up the block chain:

Type Block struct {Index int Timestamp string BPM int Hash string PrevHash string}

Index is the position of this block in the entire chain

Timestamp is obviously the timestamp when the block is generated

Hash is the hash value generated by the SHA256 algorithm for this block.

PrevHash represents the SHA256 hash value of the previous block

BPM heartbeats per minute, that is, heart rate

Next, we define a structure to represent the entire chain, and the simplest representation is a slice of Block:

Var Blockchain [] Block

We use the hash algorithm (SHA256) to determine and maintain the correct order of blocks and blocks in the chain, ensuring that the PrevHash value of each block is equal to the Hash value of the previous block, so that the chain is built in the correct block order:

Hashing and generating new blocks

Why do we need hashes? There are two main reasons:

Uniquely identify data on the premise of saving space. The hash is calculated using the data of the entire block. In our example, the data of the entire block is calculated into a fixed-length unforgeable string through SHA256.

Maintain the integrity of the chain. By storing the hash value of the previous block, we can ensure that each block is in the correct order in the chain. Any tampering with the data will change the hash value and break the chain. Take the field of health care we are engaged in as an example, for example, if a malicious third party modifies the unhealthy BPM value in one or more blocks in order to adjust the price of "life insurance", then the whole chain becomes unreliable.

Let's go on to write a function to calculate the SHA256 hash value of the given data:

Func calculateHash (block Block) string {record: = string (block.Index) + block.Timestamp + string (block.BPM) + block.PrevHash h: = sha256.New () h.Write ([] byte (record)) hashed: = h.Sum (nil) return hex.EncodeToString (hashed)}

This calculateHash function takes a block and calculates the SHA256 hash value from the Index,Timestamp,BPM in the block, as well as the PrevHash value. Then we can write a function that generates the block:

Func generateBlock (oldBlock Block, BPM int) (Block, error) {var newBlock Block t: = time.Now () newBlock.Index = oldBlock.Index + 1 newBlock.Timestamp = t.String () newBlock.BPM = BPM newBlock.PrevHash = oldBlock.Hash newBlock.Hash = calculateHash (newBlock) return newBlock, nil}

Where Index is incremented from the Index of the previous block given, the timestamp is obtained directly through the time.Now () function, the Hash value is calculated by the previous calculateHash function, and PrevHash is the Hash value of the given previous block.

Check block

After completing the block generation, we need a function to help us determine whether a block has been tampered with. Check Index to see if this block is incremented correctly, check that PrevHash is consistent with the Hash of the previous block, and then check that the Hash value of the current block is correct through calculateHash. Through these steps, we can write a check function:

Func isBlockValid (newBlock, oldBlock Block) bool {if oldBlock.Index+1! = newBlock.Index {return false} if oldBlock.Hash! = newBlock.PrevHash {return false} if calculateHash (newBlock)! = newBlock.Hash {return false} return true}

In addition to checking blocks, we also encounter a problem: both nodes generate blocks and add them to their respective chains, so who should prevail? Let's save the details here for the next article, and let's remember one principle: always choose the longest chain:

In general, a longer chain means that its data (state) is up-to-date, so we need a function to help us switch the local expired chain to the latest one:

Func replaceChain (newBlocks [] Block) {if len (newBlocks) > len (Blockchain) {Blockchain = newBlocks}}

At this point, we have basically completed all the important functions. Next, we need a convenient and intuitive way to view our chain, including data and status. Viewing the web page through a browser is probably the most appropriate way!

Web service

I guess you must be very familiar with traditional web services and development, so you will definitely take a look at this part.

With the Gorilla/mux package, let's first write a function to initialize our web service:

Func run () error {mux: = makeMuxRouter () httpAddr: = os.Getenv ("ADDR") log.Println ("Listening on", os.Getenv ("ADDR")) s: = & http.Server {Addr: ":" + httpAddr, Handler: mux, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1

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

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report