zoukankan      html  css  js  c++  java
  • 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
      ", 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在计算时耗费的时间越长

  • 相关阅读:
    首位相连数组求最大子数组的和
    第四周学习进度报告
    求二维数组中子数组的最大值
    第三周学习进度总结
    数组从文件读取判断子数组的最大值
    CI项目设计Redis队列
    list
    zset
    NodeJS框架一览
    nginx虚拟主机配置
  • 原文地址:https://www.cnblogs.com/failymao/p/9292643.html
Copyright © 2011-2022 走看看