开发自己的区块链基础功能篇
準(zhǔn)備工作:
安裝go開發(fā)環(huán)境
到https://golang.org/dl/這個地址下載對應(yīng)的安裝包,mac ,windows,linux都有(需要科學(xué)上網(wǎng))。以mac為例,下載成功后雙擊安裝下一步即可,很簡單。安裝成功后運行g(shù)o version查看版本(如果沒有的話,就重啟一下終端)
用go搭建web服務(wù)
在這里咱們用的是Gorilla/mux包。步驟:
go語言基礎(chǔ)
fmt.Printf("a: %d\n", a) }
了解這些,今天的代碼就能看懂了,當(dāng)然go語言還有很多要學(xué)習(xí)的知識點,可以到這里來http://www.runoob.com/go/go-tutorial.html學(xué)習(xí)
整理思路:
根據(jù)之前了解的區(qū)塊鏈原理,我們整理一下需要實現(xiàn)哪些方法:
創(chuàng)建區(qū)塊結(jié)構(gòu)體:
type Block struct {Index intTimestamp stringContent stringHash stringPrevHash string } 復(fù)制代碼計算哈希值:(把區(qū)塊結(jié)構(gòu)體中的信息都拼在一起,然后Hash算出來)
func calculateHash(block Block) string {record := strconv.Itoa(block.Index) + block.Timestamp + block.Content + block.PrevHashh := sha256.New()h.Write([]byte(record))hashed := h.Sum(nil)return hex.EncodeToString(hashed) } 復(fù)制代碼生成新區(qū)塊:(上一個區(qū)塊的索引加1,上一個區(qū)塊的Hash賦值給當(dāng)前區(qū)塊的PrevHash,當(dāng)前區(qū)塊的Hash由calculateHash函數(shù)生成)
func generateBlock(oldBlock Block, Content string) Block {var newBlock Blockt := time.Now()newBlock.Index = oldBlock.Index + 1newBlock.Timestamp = t.String()newBlock.Content = ContentnewBlock.PrevHash = oldBlock.HashnewBlock.Hash = calculateHash(newBlock)return newBlock } 復(fù)制代碼驗證區(qū)塊:(根據(jù)索引和Hash值判斷,老索引加1應(yīng)該等于新索引,新的PrevHash應(yīng)該等于老的Hash,最后還要重新計算一個新區(qū)塊的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 } 復(fù)制代碼啟動web服務(wù):
//設(shè)置http需要的參數(shù),并開啟服務(wù) 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 }//生成NewRouter對象 func makeMuxRouter() http.Handler {muxRouter := mux.NewRouter()muxRouter.HandleFunc("/", handleGetBlockchain).Methods("GET")muxRouter.HandleFunc("/", handleWriteBlock).Methods("POST")return muxRouter } 復(fù)制代碼好的,需要的函數(shù)都已經(jīng)列好,下面把它們組裝起來即可,然后放到一個main.go的文件中,啟動終端,進入到main.go文件夾并輸入go run main.go命令。 打開http://localhost:8080/地址,會看到一個創(chuàng)世區(qū)塊,如果想添加一個新區(qū)塊則需要使用postman 傳一個content參數(shù)過去,如圖:
然后再刷新瀏覽器,會返回新的區(qū)塊信息,如圖:
好的,先到這里,下一次我們把共識算法加進去。
總結(jié):
今天實現(xiàn)了生成新區(qū)塊、哈希計算、區(qū)塊校驗這些基本功能。代碼在:https://github.com/sunqichao/createblockchain
參考https://medium.com/@mycoralhealth/code-your-own-blockchain-in-less-than-200-lines-of-go-e296282bcffc
轉(zhuǎn)載于:https://juejin.im/post/5aabab10f265da237b21d94a
總結(jié)
以上是生活随笔為你收集整理的开发自己的区块链基础功能篇的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我不曾忘记的初心-冒险努力正是你缺少的!
- 下一篇: 查看SQL SERVER数据库的连接数