Develop your own blockchain basic functions

 

Ready to work:

  1. Install the go development environment
  2. Build web services with go
  3. go language basics

 

 

Install the go development environment

Go to https://golang.org/dl/ to download the corresponding installation package, available for mac, windows, and linux (requires scientific Internet access). Take mac as an example, after the download is successful, double-click to install the next step, which is very simple. After the installation is successful, run go version to check the version (if not, restart the terminal)

 

 

Build web services with go

Here we are using the Gorilla/mux package. step:

  1. Create NewRouter
  2. set port number
  3. Set http parameter dictionary
  4. Call the ListenAndServe method to start the service

 

 

 

go language basics

  1. Guide package: multiple packages are enclosed in parentheses
    1. import (

"sync"

"time"

)

  1. Use the dot to call the method:
    1. time.Now()
  2. Declare the variable:
    1. var coin int is separated by spaces, the type is written at the back, the variable name is written in the middle, and the first is a var
    2. coin := 10 You can also omit var and use := to assign value, but you must ensure that coin has not been declared, otherwise an error will be reported
    3. coin1, coin2 := 10, 20 The variable declaration is like this
  3. Conditional control:
    1. if a<b {

return 10

}else{

return 20

}

  1. Loop Control:
    1. for a := 0; a < 10; a++ {

fmt.Printf("a: %d\n", a)

}

  1. Function definition, passing parameters:
    1. /* The function returns the maximum of the two numbers */
    2. func max(num1, num2 int) int {

}

    1. num1, num2 int represent two integer parameters, which are optional or can be left blank.
    2. The int at the end is the type of the return value
    3. Call the function in this way: n := max(a, b)
  • Structure definition, assignment, call:
    1. 定义:type Article struct { title string id int }
    2. Assignment: var a1 Article

a1.title = "Write Code"

    1. Call: fmt.Printf( "title : %s\n", a1.title)

 

Knowing this, you can understand the code today. Of course, there are many knowledge points to learn in the go language. You can come here to learn http://www.runoob.com/go/go-tutorial.html

 

 

 

Organize ideas:

Based on the blockchain principles we have learned before, let's sort out what methods need to be implemented:

  1. What information does a block need to contain:
    1. Index : The index of this block in the entire chain
    2. Timestamp : the timestamp when the block was generated
    3. Hash: The hash value of the block generated by the SHA256 algorithm
    4. PrevHash : SHA256 hash of the previous block
    5. content : the content to be recorded
  2. function to calculate hash value
  3. A function to generate a new block
  4. According to immutability, we also need a function that verifies whether the block has been tampered with
  5. The function that starts the web service

 

 

 

Create the block structure:

type Block struct {

Index int

Timestamp string

Content string

Hash string

PrevHash string

}

 

 

Calculate the hash value: (Put together the information in the block structure, and then calculate the hash value)

func calculateHash(block Block) string {

record := strconv.Itoa(block.Index) + block.Timestamp + block.Content + block.PrevHash

h := sha256.New()

h.Write([]byte(record))

hashed := h.Sum(nil)

return hex.EncodeToString(hashed)

}

 

 

Generate a new block: (The index of the previous block is incremented by 1, the Hash of the previous block is assigned to the PrevHash of the current block, and the Hash of the current block is generated by the calculateHash function)

func generateBlock(oldBlock Block, Content string) Block {

 

was newBlock Block

 

t := time.Now()

 

newBlock.Index = oldBlock.Index + 1

newBlock.Timestamp = t.String()

newBlock.Content = Content

newBlock.PrevHash = oldBlock.Hash

newBlock.Hash = calculateHash(newBlock)

 

return newBlock

}

 

 

Verify block: (judging by the index and hash value, the old index plus 1 should be equal to the new index, the new PrevHash should be equal to the old hash, and finally recalculate the hash of a new block to see if it is the same as the one passed)

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

}

 

 

Start the web service:

//Set the parameters required by http and start the service

func run() error {

mux := makeMuxRouter()

httpAddr := "8080"

s := &http.Server{

Addr: ":" + httpAddr,

Handler: mux,

ReadTimeout: 10 * time.Second,

WriteTimeout: 10 * time.Second,

MaxHeaderBytes: 1 << 20,

}

 

if err := s.ListenAndServe(); err != nil {

return err

}

 

return nil

}

 

//Generate NewRouter object

func makeMuxRouter() http.Handler {

muxRouter := mux.NewRouter()

muxRouter.HandleFunc("/", handleGetBlockchain).Methods("GET")

muxRouter.HandleFunc("/", handleWriteBlock).Methods("POST")

return muxRouter

}

 

Ok, the required functions have been listed, assemble them below, put them in a main.go file, start the terminal, go to the main.go folder and enter the go run main.go command.

Open the http://localhost:8080/ address and you will see a genesis block. If you want to add a new block, you need to use postman to pass a content parameter, as shown in the figure:

 

Then refresh the browser, it will return the new block information, as shown in the figure:

 

Okay, here we go, next time we'll add the consensus algorithm.

 

Summarize:

Today, the basic functions of generating new blocks, hash calculation, and block verification have been implemented. The code is at: https://github.com/sunqichao/createblockchain

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324940666&siteId=291194637
Recommended