準備工作:
-
安裝go開發環境
用go搭建web服務
go語言基礎
安裝go開發環境
到https://golang.org/dl/這個地址下載對應的安裝包,mac ,windows,linux都有(需要科學上網)。以mac為例,下載成功後雙擊安裝下一步即可,很簡單。安裝成功後運行go version查看版本(如果沒有的話,就重啟一下終端)
用go搭建web服務
在這裡咱們用的是Gorilla/mux包。步驟:
創建NewRouter
設置端口號
設置http的參數字典
調用ListenAndServe方法,啟動服務
go語言基礎
導包:多個包用小括號括起來
import (
"sync"
"time"
)
使用點調用方法:
time.Now()
var coin int 用空格隔開,類型寫到後面,變量名寫中間,最後是個var
-
條件控制:
if a
return 10
}else{
return 20
}
循環控制:
for a := 0; a < 10; a++ {
fmt.Printf("a: %d\n", a)
}
函數定義,傳參:
/* 函數返回兩個數的最大值 */
func max(num1, num2 int) int {
}
num1, num2 int表示兩個整形參數,是可選的,也可以不填,
最後的int是返回值的類型
調用函數通過這樣方式:n := max(a, b)
結構體定義,賦值,調用:
定義:type Article struct { title string id int}
賦值:var a1 Article
a1.title = "寫代碼"
調用:fmt.Printf( "title : %s\n", a1.title)
瞭解這些,今天的代碼就能看懂了,當然go語言還有很多要學習的知識點,可以到這裡來http://www.runoob.com/go/go-tutorial.html學習
整理思路:
根據之前瞭解的區塊鏈原理和共識算法,我們整理一下需要實現哪些方法:
一個區塊需要包含哪些信息:
Index :這個區塊在整個鏈中的索引
Timestamp : 區塊生成時的時間戳
Hash : 區塊通過 SHA256 算法生成的哈希值
PrevHash : 前一個區塊的 SHA256 哈希值
content : 需要記錄的內容
計算哈希值的函數
-
生成新區塊的函數
根據不可篡改性,我們還需要一個驗證區塊是否被篡改的函數
啟動web服務的函數
創建區塊結構體:
type Block struct {
Index int
Timestamp string
Content string
Hash string
PrevHash string
}
計算哈希值:(把區塊結構體中的信息都拼在一起,然後Hash算出來)
func calculateHash(block Block) string {
record := strconv.Itoa(block.Index) + block.Timestamp + strconv.Itoa(block.Content) + block.PrevHash
h := sha256.New()
h.Write([]byte(record))
hashed := h.Sum(nil)
return hex.EncodeToString(hashed)
}
生成新區塊:(上一個區塊的索引加1,上一個區塊的Hash賦值給當前區塊的PrevHash,當前區塊的Hash由calculateHash函數生成)
func generateBlock(oldBlock Block, Content string) Block {
var 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
}
驗證區塊:(根據索引和Hash值判斷,老索引加1應該等於新索引,新的PrevHash應該等於老的Hash,最後還要重新計算一個新區塊的Hash,看是否和傳過來的一樣)
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
}
啟動web服務:
//設置http需要的參數,並開啟服務
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
}
//生成NewRouter對象
func makeMuxRouter() http.Handler {
muxRouter := mux.NewRouter()
muxRouter.HandleFunc("/", handleGetBlockchain).Methods("GET")
muxRouter.HandleFunc("/", handleWriteBlock).Methods("POST")
return muxRouter
}
好的,需要的函數都已經列好,下面把它們組裝起來即可,然後放到一個main.go的文件中,啟動終端,進入到main.go文件夾並輸入go run main.go命令。
打開http://localhost:8080/地址,會看到一個創世區塊,如果想添加一個新區塊則需要使用postman 傳一個content參數過去,如圖:
然後再刷新瀏覽器,會返回新的區塊信息,如圖:
好的,先到這裡,下一次我們把共識算法加進去。
總結:
今天實現了生成新區塊、哈希計算、區塊校驗這些基本功能。代碼在:https://github.com/sunqichao/createblockchain
閱讀更多 5分鐘機器學習 的文章