POW proof code implementation demo[Blockchain]

Here we emphasize the protocol layering of the blockchain

  • application layer
  • contract layer
  • Incentives
  • consensus layer
  • Network layer
  • data layer

Here we introduce the workload proof POW, which belongs to the consensus mechanism.

In the PoW mechanism, the distribution of currency and the determination of bookkeeping rights are performed according to the workload of miners. The winner of the computing power competition will receive the corresponding block bookkeeping rights and bitcoin rewards. Therefore, the higher the computing power of the mining chip and the longer the mining time, the more digital currency can be obtained.

Advantages :

The algorithm is simple and easy to implement; nodes can reach a consensus without exchanging additional information; destroying the system requires a huge cost.

shortcoming:

Waste of energy; block confirmation time is difficult to shorten; the new blockchain must find a different hash algorithm, otherwise it will face Bitcoin's computing power attack; easy to fork, need to wait for multiple confirmations; never Finality requires a checkpoint mechanism to compensate for finality.

At present, there are many digital currencies based on the PoW consensus mechanism . Most of the initial digital currencies such as Bitcoin, Litecoin, Dogecoin, Dash, and Monero are based on the PoW consensus mechanism.

Other consensus mechanisms include

PoS(Proof of Stake)
DPOS(Delegated Proof-of-Stake)
DAG(Directed acyclic graph)
PBFT(Practical Byzantine Fault Tolerance)
Pool验证池
dBFT(delegated BFT)
PoA(Proof-of-Authority)
RPCA(Ripple Protocol consensus algorithm)
Hcash——PoW+PoS共识机制

These consensus mechanisms will be added later when there is time. Today I will mainly introduce POW

Pow is very simple. The principle is to use computing power to select a nonce value and combine the data of the block to calculate the hash, so that the number of digits in front of the hash is 0.

nonceis a number used to find hashthe value that satisfies the condition, noncethe values ​​are iterated until hashthe value is valid. A valid hash value in our case is at least 4one leading 0. The process of finding noncea value that satisfies suitable conditions hashis called mining.

For example: when writing the proof code, you need a picture to summarize " Proof Picture Template "

The code is given below:

golang version

package main

import (
    "bytes"
    "crypto/sha256"
    "fmt"
    "math"
    "math/big"
)

// 前导0,难度
const targetBits  = 8

type ProofOfWork struct {
    block *Block
    targetBit *big.Int

}

func NewProofOfWork(block *Block) *ProofOfWork  {
    // 设置64位全1
    var IntTarget = big.NewInt(1)
    //00000000000000000000000000001
    //10000000000000000000000000000
    //00000000000100000000000000000
    //0000001
    // 右移 targetBits位
    IntTarget.Lsh(IntTarget, uint(256 - targetBits))

    return &ProofOfWork{block:block, targetBit:IntTarget}
}

func (pow *ProofOfWork)PrepareRawData(nonce int64)[]byte  {

    block := pow.block
    tmp := [][]byte{
        Int2Byte(block.Version),
        block.PrevBlockHash,
        Int2Byte(block.TimeStamp),
        block.MerkeRoot,
        Int2Byte(nonce),
        Int2Byte(targetBits),
        block.Data}

    data := bytes.Join(tmp, []byte{})
    return data
}

func (pow *ProofOfWork)Run() (int64, []byte) {

    var nonce int64
    var hash [32]byte
    var HashInt big.Int
    fmt.Printf("target hash:", pow.targetBit.Bytes())
    for nonce < math.MaxInt64 {
        data := pow.PrepareRawData(nonce)
        hash = sha256.Sum256(data)

        HashInt.SetBytes(hash[:])
        //fmt.Println(nonce)
        // 这里用于 判断算出的hash值(int)只要比最大的IntTarget小就是正确的。
        if HashInt.Cmp(pow.targetBit) == -1 {
            fmt.Printf("Found Hash: %x\n", hash)
            break
        } else {
            nonce++
        }

    }
    return nonce, hash[:]
}

// 对block的数据校验
func (pow *ProofOfWork)IsVaild() bool {
    data := pow.PrepareRawData(pow.block.Nonce)
    hash := sha256.Sum256(data)
    var IntHash big.Int
    IntHash.SetBytes(hash[:])
    return IntHash.Cmp(pow.targetBit) == -1

}

python version

function isValidHashDifficulty(hash, difficulty) {
  for (var i = 0, b = hash.length; i < b; i ++) {
      if (hash[i] !== '0') {
          break;
      }
  }
  return i >= difficulty;
}

import hashlib

"""
工作量证明
"""


class ProofofWork():
    """
    pow
    """

    def __init__(self, block):
        self.block = block

    def mine(self):
        """
        挖矿函数
        :return:
        """
        i = 0
        prefix = '0000'

        while True:
            nonce = str(i)
            message = hashlib.sha256()
            message.update(str(self.block.data).encode('utf-8'))
            message.update(nonce.encode("utf-8"))
            digest = message.hexdigest()
            if digest.startswith(prefix):
                return nonce, digest
            i += 1

 

Guess you like

Origin blog.csdn.net/dageliuqing/article/details/128055629