Simple Bitcoin System in Go Language (2): Consensus Algorithm

1. Issues in the previous version

  • Random number and difficulty value fill in casually
  • The hash value of the block is irregular

2. New content in this version

  • Add POW consensus algorithm

3. POW

3.1 Introduction to POW

  • Proof Of Work (POW), that is, proof of work, is a consensus algorithm. It is an agreement that ensures the security of digital transactions without relying on a third party.

3.2 Essence of POW

  • In essence, the work in the proof of work is a problem that everyone must solve together. The data generated by POW is very difficult and costly, but it is easy to verify once it is produced.

3.3 POW in Bitcoin

  • The problem of POW in Bitcoin is to verify and confirm the block, so that the transactions in the block can be realized. Specifically, the POW algorithm is mainly to find a random number so that the hash value of the block header is less than the specified target value.
  • The following is a simple block verification process, taking the second block of Bitcoin as an example.
    Insert picture description here
//1.计算哈希值

//计算区块头的哈希需要以下六个参数,然后不断的修改nonce值,
//    并对区块头进行sha256
version:	    000000001 --小端结尾--> 01000000
pre_hash(小端结尾后):6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000
merkle_root(小端结尾后): 982051fd1e4ba744bbbe680e1fee14677ba1a3c3540bf7b1cdb606e857233e0e
timestamp:4966BC61--小端结尾-->61BC5549
bits:1D00FFFF ----> FFFF001D
nonce:9962E301 ----> 01E36299  //这个nonce值已经符合要求

header_hash=version+pre_hash+merkle_root+timestamp+bits+nonce

//对区块头进行两次sha256等运算并小端结尾得到:
header_hash=00000000839a8e6886ab5951d76f411475428afc90947ee320161bbf18eb6048

//2. 比较
//把计算得到的区块头哈希与目标值进行比较,
//    如果得到的哈希值比目标值小,那么代表就解出了这道数学题

//但是,我不会算目标值。计算目标值的公式为:目标值=系数*2^(8*(指数-3))次方
//还望路过的大佬指点指点


4. Realize POW

4.1 Define POW structure

type ProofOfWork struct {
    
    
	//a. 要挖矿的区块
	block *Block
	//b. 目标值
	target *big.Int
}

4.2 Create POW function

func NewProofOfWork(block *Block) *ProofOfWork{
    
    
	pow := ProofOfWork{
    
    
		block:  block,
	}
	//目标值
	targetStr := "0000f00000000000000000000000000000000000000000000000000000000000"

	//引入辅助变量,将targetStr转换为big.int
	//因为字符串无法比较大小
	tmpInt := big.Int{
    
    }
	//把targetStr赋值给tmpInt, 格式为16进制
	tmpInt.SetString(targetStr, 16)

	pow.target = &tmpInt
	return &pow
}

4.3 Mining method

func (pow *ProofOfWork) Run () ([]byte, uint64) {
    
    
	//随机数
	var nonce uint64
	//要挖矿的区块
	block := pow.block
	var hash [32]byte
	
	//不断循环,增加nonce,得到比目标值小的数
	for{
    
    
		//拼装数据
		tmp := [][]byte{
    
    
			Uint64ToByte(block.Version),
			block.PrevHash,
			block.MerkelRoot,
			Uint64ToByte(block.TimeStamp),
			Uint64ToByte(block.Difficulty),
			Uint64ToByte(nonce),
			block.Data,
		}
		blockInfo := bytes.Join(tmp, []byte{
    
    })
		//做hash运算
		hash = sha256.Sum256(blockInfo)
		tmpInt := big.Int{
    
    }
		tmpInt.SetBytes(hash[:])
		
		//与目标值比较
		//Cmp比较返回值的含义
		//   -1 if x <  y
		//    0 if x == y
		//   +1 if x >  y
		if tmpInt.Cmp(pow.target) == -1{
    
    
			//找到了
			fmt.Printf("挖矿成功! hash: %x, nonce: %d\n", hash, nonce)
			return hash[:], nonce
		}else {
    
    
			//没到到 nonce加1
			nonce ++
		}

	}
}

4.4 Set nonce and block hash

//添加区块函数
func NewBlock (data string, prevBlockHash []byte) *Block{
    
    
	block := Block{
    
    
		Version:    00,
		PrevHash:   prevBlockHash,
		MerkelRoot: []byte{
    
    },
		TimeStamp:  uint64(time.Now().Unix()),
		Difficulty: 0,
		Nonce:      0,
		Hash:       []byte{
    
    },
		Data:       []byte(data),
	}

	//block.SetHash()
	//创建一个pow对象
	pow := NewProofOfWork(&block)
	hash, nonce := pow.Run()
	//根据挖矿结果对区块进行更新
	block.Hash= hash
	block.Nonce = nonce

	return &block
}

Source code: https://gitee.com/xiaoshengdada/go_bitcoin/tree/master/v2

Since then, the POW algorithm has been added and the function is relatively simple. The POW consensus algorithm will continue to be improved in the future. Next blog, to achieve block persistence.

If you have any questions, you can come to the WeChat group to communicate and learn and make progress together.
Insert picture description hereFinally, recommend the official account of a big brother: the blockchain technology stack .

Guess you like

Origin blog.csdn.net/qq_31639829/article/details/115295812