【go共識演算法】-POW

jincheng828發表於2019-02-16

pow介紹

工作量證明(PoW,Proof of Work)。
通過計算一個數值(nonce ),使得拼揍上交易資料後內容的 Hash 值滿足規定的上限。在節點成功找到滿足的Hash值之後,會馬上對全網進行廣播打包區塊,網路的節點收到廣播打包區塊,會立刻對其進行驗證。

如果驗證通過,則表明已經有節點成功解迷,自己就不再競爭當前區塊打包,而是選擇接受這個區塊,記錄到自己的賬本中,然後進行下一個區塊的競爭猜謎。 網路中只有最快解謎的區塊,才會新增的賬本中,其他的節點進行復制,這樣就保證了整個賬本的唯一性。

假如節點有任何的作弊行為,都會導致網路的節點驗證不通過,直接丟棄其打包的區塊,這個區塊就無法記錄到總賬本中,作弊的節點耗費的成本就白費了,因此在巨大的挖礦成本下,也使得礦工自覺自願的遵守比特幣系統的共識協議,也就確保了整個系統的安全。
參考黎躍春的翻譯

pow優缺點

  • 優點:完全去中心化,節點自由進出;
  • 缺點:目前bitcoin已經吸引全球大部分的算力,其它再用Pow共識機制的區塊鏈應用很難獲得相同的算力來保障自身的安全;挖礦造成大量的資源浪費;共識達成的週期較長,不適合商業應用

go實現pow共識演算法

程式碼出處

依賴軟體

  • spew 在控制檯中格式化輸出相應的結果。
    $ go get github.com/davecgh/go-spew/spew
  • gorilla/mux 是編寫web處理程式的流行軟體包。
    $ go get github.com/gorilla/mux
  • godotenv 可以從我們專案的根目錄的 .env 檔案中讀取資料。
    $ go get github.com/joho/godotenv

.env

ADDR=8080

main.go

package main

import (
        "crypto/sha256"
        "encoding/hex"
        "encoding/json"
        "fmt"
        "io"
        "log"
        "net/http"
        "os"
        "strconv"
        "strings"
        "sync"
        "time"

        "github.com/davecgh/go-spew/spew"
        "github.com/gorilla/mux"
        "github.com/joho/godotenv"
)

const difficulty = 1

type Block struct {
        Index      int
        Timestamp  string
        BPM        int
        Hash       string
        PrevHash   string
        Difficulty int
        Nonce      string
}

var Blockchain []Block

type Message struct {
        BPM int
}

var mutex = &sync.Mutex{}

func generateBlock(oldBlock Block, BPM int) Block {
    var newBlock Block

    t := time.Now()

    newBlock.Index = oldBlock.Index + 1
    newBlock.Timestamp = t.String()
    newBlock.BPM = BPM
    newBlock.PrevHash = oldBlock.Hash
    newBlock.Difficulty = difficulty

    for i := 0; ; i++ {
            hex := fmt.Sprintf("%x", i)
            newBlock.Nonce = hex
            if !isHashValid(calculateHash(newBlock), newBlock.Difficulty) {
                    fmt.Println(calculateHash(newBlock), " do more work!")
                    time.Sleep(time.Second)
                    continue
            } else {
                    fmt.Println(calculateHash(newBlock), " work done!")
                    newBlock.Hash = calculateHash(newBlock)
                    break
            }

    }
    return newBlock
}

func isHashValid(hash string, difficulty int) bool {
    //複製 difficulty 個0,並返回新字串,當 difficulty 為2 ,則 prefix 為 00
    prefix := strings.Repeat("0", difficulty)
    // HasPrefix判斷字串 hash 是否包含字首 prefix
    return strings.HasPrefix(hash, prefix)
}

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

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
}


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 << 20,
    }

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

    return nil
}

func makeMuxRouter() http.Handler {
    muxRouter := mux.NewRouter()
    muxRouter.HandleFunc("/", handleGetBlockchain).Methods("GET")
    muxRouter.HandleFunc("/", handleWriteBlock).Methods("POST")
    return muxRouter
}

func handleGetBlockchain(w http.ResponseWriter, r *http.Request) {
    bytes, err := json.MarshalIndent(Blockchain, "", "  ")
    if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
    }
    io.WriteString(w, string(bytes))
}

func handleWriteBlock(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var m Message

    decoder := json.NewDecoder(r.Body)
    if err := decoder.Decode(&m); err != nil {
            respondWithJSON(w, r, http.StatusBadRequest, r.Body)
            return
    }   
    defer r.Body.Close()

    //ensure atomicity when creating new block
    mutex.Lock()
    newBlock := generateBlock(Blockchain[len(Blockchain)-1], m.BPM)
    mutex.Unlock()

    if isBlockValid(newBlock, Blockchain[len(Blockchain)-1]) {
            Blockchain = append(Blockchain, newBlock)
            spew.Dump(Blockchain)
    }   

    respondWithJSON(w, r, http.StatusCreated, newBlock)

}

func respondWithJSON(w http.ResponseWriter, r *http.Request, code int, payload interface{}) {
    w.Header().Set("Content-Type", "application/json")
    response, err := json.MarshalIndent(payload, "", "  ")
    if err != nil {
            w.WriteHeader(http.StatusInternalServerError)
            w.Write([]byte("HTTP 500: Internal Server Error"))
            return
    }
    w.WriteHeader(code)
    w.Write(response)
}

func main() {
    err := godotenv.Load()
    if err != nil {
            log.Fatal(err)
    }   

    go func() {
            t := time.Now()
            genesisBlock := Block{}
            genesisBlock = Block{0, t.String(), 0, calculateHash(genesisBlock), "", difficulty, ""} 
            spew.Dump(genesisBlock)

            mutex.Lock()
            Blockchain = append(Blockchain, genesisBlock)
            mutex.Unlock()
    }() 
    log.Fatal(run())

}

相關文章