Go实现Pow工作量证明

时间:2023-03-09 00:34:59
Go实现Pow工作量证明

之前使用python编写了一段代码实现了工作量证明机制,近期由于参与以太坊智能合约开发钱包的工作接触到golang语言,所以借此以go来实现Pow(Proof of work).

  • 实现代码如下:

    // pow 工作量证明
    package main
    import (
    "crypto/sha256"
    "fmt"
    "strconv"
    "time"
    ) func main() {
    c := PowProcess("Haxima")
    fmt.Println(c)
    } /* Pow working process
    设定条件:当hash后的值满足特定条件
    */ func PowProcess(x string) string {
    var i int
    t1 := time.Now().UnixNano()
    for i = 0; (HashString(x + strconv.Itoa(i)))[:4] != "0000"; i ++ {
    fmt.Println(i)
    } fmt.Println(i)
    fmt.Printf("Duration:%.3fs\n", float64((time.Now().UnixNano()-t1)/1e6)/1000)
    return HashString(x + strconv.Itoa(i))
    } /* hash函数
    params: available_str string ---> pre hash blockchain
    */
    func HashString(available_str string) string {
    h := sha256.New()
    h.Write([]byte(available_str))
    return fmt.Sprintf("%x", h.Sum(nil))
    } func main() {
    c := PowProcess("Haxima")
    fmt.Println(c)
    } /*运行结果
    i---> 1
    i---> 2
    i ...
    i---> 99110
    i---> 99111
    Duration:1.570s
    000063d6789a2f7d7f26157cdc38f82c67e52ddda8d6c4e1bf2a3bc4717737ae
    */

运行代码可知 :当PowProcess函数条件设置越苛刻(即0的个数越多),其工作量难度越大,CPU在计算时耗费的时间越长