Brother even blockchain getting started tutorial sharing blockchain POW Proof code implementation demo

Source: Internet
Author: User
Tags pow

Here we emphasize the protocol layering of the blockchain
? Application Layer
? contract Layer
? Incentive mechanism
? Consensus layer
? Network layer
? data layer
On a main implementation of the Blockchain data layer, the main use of data layer technology is to check the data, to seek hash.
Here is a description of the workload proof POW, which is part of the consensus mechanism.
The POW mechanism performs the allocation of money and the determination of the right to account according to the miners ' workload. The winner of the calculated competition will receive the corresponding block billing rights and Bitcoin rewards. Therefore, the higher the calculation power of the chip, the longer the mining time, the more digital currency can be obtained.
Advantages:
The algorithm is simple and easy to implement; there is no need to exchange additional information between nodes to reach a consensus; destroying the system costs a great deal of effort.
Disadvantages:
waste of energy; block confirmation time is difficult to shorten; new blockchain must find a different hashing algorithm, otherwise it will face Bitcoin's calculation force * * *, prone to fork, need to wait for multiple confirmations, never final, need checkpoint mechanism to compensate for the final sex.
At present, there are many digital currencies based on the POW consensus mechanism, and most of the initial digital currencies, such as Bitcoin, Wright coins, dog coins, Qantas coins and Monroe coins, are the POW consensus mechanism.
Other consensus mechanisms are also
PoS (Proof of Stake)
DPOS (Delegated Proof-of-stake)
DAG (Directed acyclic graph)
PBFT (Practical Byzantine Fault tolerance)
Pool Validation Pools
DBFT (Delegated BFT)
PoA (proof-of-authority)
RPCA (Ripple Protocol consensus algorithm)
Hcash--pow+pos consensus mechanism
These consensus mechanisms, which will be supplemented by time, are today mainly about POW
POW is very simple, the principle is the use of computational power, in the selection of a nonce value combined with chunks of data to calculate the hash, so that the number of bits in front of the hash is 0.
A nonce is a number used to find a hash value that satisfies a condition, and the nonce value is iterated until the hash value is valid. In our case, a valid hash value is a minimum of 4 leading 0. The process of finding the hash value to meet the appropriate conditions is called mining.
The following code is given:
Version Golang

Package Mainimport ("bytes" "crypto/sha256" "FMT" "Math" "math/big")//Preamble 0, difficulty const TARGETBITS = 8type Pro ofofwork struct {block *block targetbit *big. Int}func newproofofwork (Block *block) *proofofwork {//Set 64-bit full 1 var inttarget = big. Newint (1)//00000000000000000000000000001//10000000000000000000000000000//00000000000100000000000000000//00 00001//Right shift targetbits bit inttarget.lsh (inttarget, UINT (256-targetbits)) return &proofofwork{block:block, tar        Getbit: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)//This is used to determine the hash value (int) calculated as long as the maximum inttarget small is correct. If hashint.cmp (pow.targetbit) = =-1 {fmt. Printf ("Found Hash:%x\n", hash) break} else {nonce++}} return nonce, hash[: ]}//data check func for block (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

Brother even blockchain getting started tutorial sharing blockchain POW Proof code implementation demo

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.