为广大币圈朋友提供币圈基础入门专业知识!
当前位置首页 > 区块链知识> 正文

区块链共识验证机,区块链证书查询

发布时间:2023-12-06-08:49:00 来源:网络 区块链知识 区块   共识

区块链共识验证机,区块链证书查询


请查看相关英文文档

㈠ Consensus mechanism of blockchain

1. The goal of blockchain consensus mechanism

What is blockchain? Simply put, blockchain is a decentralized database, or it can be called a distributed ledger. Traditionally, all databases are centralized. For example, a bank's ledger is stored in the bank's central server. The disadvantage of a centralized database is that the security and accuracy of the data depend entirely on the database operator (i.e., the bank), because anyone who has access to the centralized database (such as bank employees or hackers) can destroy or modify the data in it.


Blockchain technology allows databases to be stored on thousands of computers around the world. Everyone’s ledger is synchronized through a peer-to-peer network, and anyone in the network can Once a user adds a transaction, the transaction information will be notified to other users through the network for verification and recorded in their respective ledgers. Blockchain gets its name because it is a data structure composed of blocks containing transaction information linked in an orderly manner from back to front.


Many people’s question about blockchain is that if each user has an independent ledger, does it mean that they can add to their own ledger? Arbitrary transaction information, and how can thousands of ledgers ensure the consistency of accounting? Solving the problem of accounting consistency is the goal of the blockchain consensus mechanism. The blockchain consensus mechanism aims to ensure that the data in all nodes in the distributed system are exactly the same and can reach agreement on a certain proposal (for example, a transaction record). However, due to the introduction of multiple nodes in a distributed system, various very complex situations will occur in the system; as the number of nodes increases, node failure or failure, network communication between nodes is interfered or even blocked, etc. In addition to common problems, solving various boundary conditions and unexpected situations in distributed systems also increases the difficulty of solving distributed consistency problems.


Blockchain can be divided into three types:


Public chain: full Anyone in the world can enter the system at any time to read data, send confirmed transactions, and compete for accounting in the blockchain. Public blockchains are generally considered "completely decentralized" because no one or institution can control or tamper with the reading and writing of data. Public chains generally encourage participants to compete for accounting through a token mechanism to ensure data security.


Alliance chain: Alliance chain refers to a blockchain in which several institutions jointly participate in management. Each institution runs one or more nodes, and the data in it only allows different institutions within the system to read, write and send transactions, and jointly record transaction data. This type of blockchain is recognizedIt is "partially decentralized".


Private chain: refers to a blockchain whose write permission is controlled by an organization or institution. The qualifications of participating nodes will be strictly restricted. Since the participating nodes are limited and controllable, private chains can often have extremely fast transaction speeds, better privacy protection, lower transaction costs, and are not prone to malicious attacks. , and can meet the necessary requirements of the financial industry such as identity authentication. Compared with centralized databases, private chains can prevent single nodes within an organization from deliberately concealing or tampering with data. Even if an error occurs, the source can be quickly discovered, so many large financial institutions are currently more inclined to use private chain technology.

2. Classification of blockchain consensus mechanisms

The difficulty of solving distributed consistency problems has given rise to several consensus mechanisms, each of which has its own advantages and disadvantages, and is also suitable for different environment and issues. The consensus mechanisms that are common knowledge include:


l PoW (Proof of Work) workload proof mechanism

l PoS (Proof of Stake) ) Equity/Equity Proof Mechanism

l DPoS (Delegated Proof of Stake) Share Authorization Proof Mechanism

l PBFT (Practical Byzantine Fault Tolerance) Practical Byzantine Fault Tolerance Algorithm

l DBFT (Delegated Byzantine Fault Tolerance) Authorized Byzantine Fault Tolerance Algorithm

l SCP (Stellar Consensus Protocol) Stellar Consensus Protocol

l RPCA (Ripple Protocol Consensus Algorithm) Ripple Consensus Algorithm

p>

l Pool verification pool consensus mechanism


(1) PoW (Proof of Work) workload proof mechanism

< br />

1. Basic introduction


In this mechanism, every node on the network is using the SHA256 hash function (hash function) Calculate the hash value (hash sum) of a changing block header. Consensus requires that the calculated value must be equal to or less than a given value. In a distributed network, all participants need to continuously calculate the hash value using different random numbers until the goal is reached. When a nodeTo calculate the exact value, all other nodes must confirm with each other that the value is correct. Transactions in new blocks will then be verified to prevent fraud.


In Bitcoin, the above nodes that calculate hash values ​​are called "miners", and the PoW process is called "mining". Mining is a time-consuming process, so incentives have been proposed (such as granting miners a small share of Bitcoin). The advantage of PoW is complete decentralization, but its disadvantage is the waste of resources caused by consuming a lot of computing power, the cycle of reaching consensus is also relatively long, and the consensus efficiency is low, so it is not very suitable for commercial use.



2. Application examples of cryptocurrency


Bitcoin and Litecoin. The first three phases of Ethereum (Frontier, Homestead, and Metropolis) all adopt the PoW mechanism, and its fourth phase (Serenity) will adopt the proof-of-stake mechanism. PoW is suitable for public chains.


Although the PoW mechanism has successfully proved its long-term stability and relative fairness, under the existing framework, using the "mining" form of PoW will consume A lot of energy. The energy it consumes is just to continuously perform SHA256 calculations to ensure fair workload, and has no other meaning of existence. The current transaction efficiency that BTC can achieve is about 5TPS (5 transactions/second). Ethereum is currently subject to the upper limit of the total amount of GAS in a single block, and the transaction frequency that can be achieved is about 25TPS, which is the same as the average thousand times per second and peak performance. There is a huge difference between VISA and MASTERCARD, which can achieve processing efficiency of 10,000 times per second.


3. Simple diagram understanding mode



(ps: The process of calculating hash values ​​by A, B, C, and D is "mining". In order to reward the time cost, the mechanism will use a certain number of Bitcoins as incentives.)


(Ps: In PoS mode, your "mining" income is proportional to the age of your currency (number of coins * number of days), and has nothing to do with the computing performance of the computer. We can think that the accumulation of any probabilistic events is proof of work, such as gold mining. Assuming that the gold content of ore is p% mass, when you get a certain amount of gold, we can think that you must have dug 1/p mass of ore. And The more gold you get, the more reliable the proof is.)


(2) PoS (Proof of Stake) Equity/Proof of Equity Mechanism


1. Basic introduction


PoS requires people to prove ownership of the currency amount, and it is believed that people with a large amount of currency are less likely to attack the network. Selection based on account balance is very unfair, as the single richest person is bound to dominate the network, so many solutions have been proposed.


In the proof-of-stake mechanism, whenever a block is created, miners need to create a transaction called "coin rights", which will be determined according to a certain Proportionately sends some coins to miners in advance. Then the equity proof mechanism reduces the mining difficulty of nodes in equal proportions based on the proportion and time of tokens held by each node (coin age) according to the algorithm, so as to speed up the node's search for random numbers and shorten the time required to reach consensus.


Compared with PoW, PoS can save more energy and be more efficient. But since the mining cost is close to 0, it may be vulnerable to attacks. And PoS still essentially requires nodes in the network to perform mining operations, so it is also difficult to apply in the commercial field.



2. Application examples of digital currency


The more mature digital currencies under the PoS mechanism are Peercoin and NXT. Compared with PoW, the PoS mechanism saves energy and introduces the concept of "coin days" to participate in random operations. The PoS mechanism allows more currency holders to participate in the accounting work without the need to purchase additional equipment (mining machines, graphics cards, etc.). The computing power of each unit token is positively related to the length of time it is held. That is, the more tokens a holder holds and the longer the time, the greater the probability that the holder can sign and produce the next block. Once it signs the next block, the currency days held by the currency holder will be cleared and a new cycle will be re-entered.


PoS is suitable for public chains.


3. How to generate block signers


Under the PoS mechanism, Because the signers of blocks are randomly generated, some currency holders will hold tokens for a long time and in large amounts to obtain a greater probability of generating blocks, and to clear as many of their "coin days" as possible. Therefore, the number of circulating tokens in the entire network will decrease, which is not conducive to the circulation of tokens on the chain, and prices will be more susceptible to fluctuations. becauseThere may be a situation where a small number of large investors hold most of the tokens in the entire network, and the entire network may become more and more centralized as the running time increases. Compared with PoW, the cost of doing evil under the PoS mechanism is very low, so for forking or double-spending attacks, more mechanisms are needed to ensure consensus. Under stable conditions, approximately 12 transactions can be generated per second, but due to network delays and consensus issues, it takes about 60 seconds to fully broadcast the consensus block. In the long run, the speed of generating blocks (that is, clearing "coin days") is much lower than the speed of network propagation and broadcasting. Therefore, under the PoS mechanism, it is necessary to "limit the speed" of generated blocks to ensure the stability of the main network. run.


4. Simple diagram understanding mode




(PS: The more “shares” you own, the easier it is for you to obtain account rights. It refers to how much currency you get, which depends on the workload you contribute to mining and the performance of your computer. The better, the more mines will be allocated to you.)


(In a pure POS system, such as NXT, there is no mining process, and the initial equity The distribution has been fixed, and then only the equity is transferred among traders, very similar to stocks in the real world.)


(3) DPoS (Delegated Proof of Stake) ) Share authorization certification mechanism


1. Basic introduction


Due to various disadvantages of PoS , thus the DPoS (Delegated Proof of Stake), the first equity representation mechanism pioneered by BitShares, came into being. The core element of the DPoS mechanism is election. Holders of each system's native tokens can participate in elections in the blockchain, and the balance of the tokens they hold is the voting weight. Through voting, shareholders can elect board members and express their attitudes on issues related to the development direction of the platform, all of which form the basis of community autonomy. In addition to voting in elections themselves, shareholders can also vote on their behalf by authorizing their election votes to other accounts they trust.


Specifically, DPoS was invented by the Bitshares project team. Stakeholders elect their representatives to generate and verify blocks. DPoS is similar to a modern corporate board of directors system. The BitShares system calls token holders shareholders, and shareholders vote to elect 101 representatives. These representatives are then responsible for generating and verifying blocks. If a currency holder wants to be called a representative, he must first use hisRegister your public key on the blockchain and obtain a unique identity identifier with a length of 32 bits. Shareholders can vote on this identifier in the form of transactions, and the top 101 votes will be selected as representatives.

Representatives take turns to generate blocks, and the profits (transaction fees) are equally divided. The advantage of DPoS is that it greatly reduces the number of nodes participating in block verification and accounting, thereby shortening the time required for consensus verification and greatly improving transaction efficiency. From a certain perspective, DPoS can be understood as a polycentric system, which has the advantages of both decentralization and centralization. Advantages: It greatly reduces the number of nodes participating in verification and accounting, and can achieve second-level consensus verification. Disadvantages: Voting enthusiasm is not high, and most token holders do not participate in voting; in addition, the entire consensus mechanism still relies on tokens, and many commercial applications do not require the existence of tokens.


The DPoS mechanism requires that before generating the next block, it must be verified that the previous block has been signed by a trusted node. Compared with PoS's "National Mining", DPoS uses a system similar to the "Congress" to directly select trusted nodes, and these trusted nodes (i.e. witnesses) exercise power on behalf of other currency holders. Witnesses Nodes are required to be online for a long time, thus solving a series of problems such as delays in block production that may be caused by PoS block signers not always being online. The DPoS mechanism can usually reach a transaction speed of 10,000 transactions per second, and can reach the level of 100,000 seconds when the network delay is low, which is very suitable for enterprise-level applications. Because Gongxinbao Data Exchange has high requirements for data transaction frequency and long-term stability, DPoS is a very good choice.



2. Institutions and systems under the share authorization certification mechanism


The board of directors is the authority of the blockchain network. The candidates for the board of directors are elected by system shareholders (i.e. currency holders). Board members have the right to initiate motions and vote on motions.


One of the important responsibilities of the Board of Directors is to adjust the variable parameters of the system as needed. These parameters include:


l Fee related: rates for various transaction types.

l Authorization related: parameters related to charges and subsidies for third-party platforms that access the network.

l Block production related: block production interval, block reward.

l Identity review related: review and verify the information of abnormal institutional accounts.

l At the same time, matters related to the interests of the Board of Directors will not be set by the Board of Directors.


inIn the Finchain system, witnesses are responsible for collecting various transactions broadcast when the network is running and packaging them into blocks. Their work is similar to miners in the Bitcoin network. In the Bitcoin network using PoW (proof of work), A lottery method in which the probability of winning depends on hash power determines which miner node produces the next block. In a financial chain network that adopts the DPoS mechanism, the number of witnesses is determined by voting by the board of directors, and the candidates for the witnesses are determined by voting by currency holders. The selected active witnesses package transactions and produce blocks in order. After each round of block production, the witnesses will randomly shuffle the cards to determine the new order before entering the next round of block production.


3. Application examples of DPoS


Bitshares uses DPoS. DPoS is mainly suitable for alliance chains.


4. Simple diagram understanding mode





(4) PBFT (Practical Byzantine Fault Tolerance) Practical Byzantine Fault Tolerance Algorithm


1. Basic introduction


PBFT is an algorithm based on strict mathematical proof, which requires three stages of information interaction and local consensus to achieve the final unanimous output. The three stages are pre-prepare, prepare, and commit. The PBFT algorithm proves that as long as there are more than 2/3 normal nodes in the system, it can ensure that a consistent consensus result can be output in the end. In other words, in a system using the PBFT algorithm, it can tolerate no more than 1/3 of the total number of nodes in the system (including nodes that intentionally mislead, intentionally damage the system, time out, repeatedly send messages, forge signatures, etc., also known as " Byzantium" node).



2. Application examples of PBFT


The famous alliance chain Hyperledger Fabric v0.6 uses PBFT, and v1.0 launched an improved version of PBFT, SBFT. PBFT is mainly suitable for private chains and consortium chains.


3. Simple diagram understanding mode




The above figure shows a simplified PBFT protocol Communication mode, where C is the client, 0 – 3 represents the service node, where 0 is the master node and 3 is the fault node. The basic process of the entire protocol is as follows:


(1) The client sends a request to activate the service operation of the master node;

(2) When the master node receives the request, it starts a three-phase protocol to broadcast the request to each slave node;

(a) Sequence number allocation phase, the master node assigns a sequence number n to the request, broadcasts the sequence number allocation message and the client's request message m, and will construct a pre-prepare message to each slave node;

(b) In the interaction phase, the slave node receives the pre-prepare message and broadcasts the prepare message to other service nodes;

(c) In the sequence number confirmation phase, after each node verifies the request and sequence in the view, it broadcasts the commit message, executes the received client request and responds to the client.

(3) The client waits for responses from different nodes. If m+1 responses are the same, the response is the result of the operation;



p>


(5) DBFT (Delegated Byzantine Fault Tolerance) authorized Byzantine fault tolerance algorithm


1. Basic introduction


DBFT is based on PBFT. In this mechanism, there are two types of participants, one is the "super node" who specializes in accounting , one is an ordinary user in the system who does not participate in accounting. Ordinary users vote for super nodes based on the proportion of their equity holdings. When a consensus (accounting) needs to be passed, a spokesperson is randomly selected among these super nodes to formulate a plan, and then other super nodes use Byzantine fault tolerance to algorithm (see above), that is, the principle of majority submission. If more than 2/3 of the super nodes agree with the speaker plan, a consensus is reached. This proposal becomes the final published block, and the block is irreversible, and all transactions in it are 100% confirmed. If a consensus proposal has not been reached within a certain period of time, or if illegal transactions are discovered, other super nodes can reinitiate the proposal and repeat the voting process until a consensus is reached.



2. DBFTApplication examples


NEO, a domestic cryptocurrency and blockchain platform, is the developer and adopter of the DBFT algorithm.


3. Simple diagram understanding mode




Assume that there are only four super nodes in the system voted by ordinary users. When a consensus needs to be passed, the system will randomly select one of the representatives to speak. People make plans. The spokesperson will hand over the prepared plan to each representative. Each representative will first determine whether the speaker's calculation results are consistent with their own records, and then discuss with other representatives to verify whether the calculation results are correct. If 2/3 of the representatives unanimously agree that the calculation results of the speaker's plan are correct, then the plan is passed.


If less than 2/3 of the representatives reach a consensus, a new speaker will be randomly selected and the above process will be repeated. This system is designed to protect the system from leaders who are unable to function.


The above figure assumes that all nodes are honest and reach 100% consensus, and plan A (block) will be verified.



Given that the spokesperson is a randomly selected representative, he may be dishonest or malfunctioning . The above figure assumes that the spokesperson sends malicious messages to 2 of the 3 representatives (scenario B), and at the same time sends a correct message to 1 representative (scenario A).


In this case, the malicious information (Option B) cannot pass. The calculation results of the representatives in the middle and on the right were inconsistent with those sent by the spokesperson, so they could not verify the plan drawn up by the spokesperson, causing the two people to reject the plan. The representative on the left received correct information that was consistent with his own calculation results, so he was able to confirm the plan and successfully completed a verification. However, this plan still failed to pass because less than 2/3 of the representatives reached a consensus. A new spokesperson will then be randomly selected and the consensus process will begin again.




The above picture assumes that the speaker is honest, but One of the representatives experienced an anomaly; the representative on the right sent incorrect information to the other representatives (B).


In this case, the correct information (A) formulated by the speaker can still be verified, because both the honest representatives on the left and the middle can verify that the correct information (A) formulated by the spokesperson Prepared by the spokespersonplan and reached a 2/3 consensus. The representative can also determine whether the speaker is lying to the node on the right or the node on the right is being dishonest.


(6) SCP (Stellar Consensus Protocol) Stellar Consensus Protocol


1. Basic introduction


SCP is a consensus algorithm developed and used by Stellar (a decentralized global payment protocol based on the Internet). It is based on the Federated Byzantine Agreement ( Federated Byzantine Agreement). Although traditional non-federated Byzantine protocols (such as PBFT and DBFT above) ensure that consensus can be reached through distributed methods and achieve Byzantine fault tolerance (can tolerate at most failed nodes that do not exceed 1/3 of the total number of nodes in the system), it is a Centralized system - The number and identity of nodes in the network must be known and verified in advance. The difference of the Federated Byzantine Agreement is that it can be decentralized and Byzantine fault-tolerant at the same time.


[…]


(7) RPCA (Ripple Protocol Consensus Algorithm) Ripple Consensus algorithm


1. Basic introduction


RPCA is Ripple (an Internet-based Open source payment protocol, which can realize decentralized currency exchange, payment and settlement functions) consensus algorithm developed and used. In Ripple's network, transactions are initiated by the client (application) and broadcast to the entire network through the tracking node or validating node. The main function of the tracking node is to distribute transaction information and respond to client ledger requests. In addition to all the functions of the tracking node, the verification node can also add new ledger instance data to the ledger through the consensus protocol.


Ripple's consensus occurs between verification nodes. Each verification node is pre-configured with a list of trusted nodes, called UNL (Unique Node). List). Nodes on the list can vote on the transaction. The consensus process is as follows:


(1) Each verification node will continuously receive transactions sent from the network, and communicate with the local accountAfter this data is verified, illegal transactions will be discarded directly, and legal transactions will be summarized into a transaction candidate set. The transaction candidate set also includes transactions left over from the previous consensus process that could not be confirmed.

(2) Each verification node sends its own transaction candidate set as a proposal to other verification nodes.

(3) After the verification node receives a proposal from other nodes, if it is not from a node on UNL, it will ignore the proposal; if it is from a node on UNL, it will compare it with the proposal. Transaction and local transaction candidate set, if there is the same transaction, the transaction gets one vote. Within a certain period of time, when a transaction receives more than 50% of the votes, the transaction enters the next round. Transactions that do not exceed 50% will be left for the next consensus process to be confirmed.

(4) The verification node sends transactions with more than 50% of the votes as proposals to other nodes, and at the same time increases the threshold of the required votes to 60%, repeating steps (3) and (4) until the threshold Reach 80%.

(5) The verification node formally writes the transactions confirmed by 80% UNL nodes into the local ledger data, which is called the last closed ledger, which is the last (latest) status of the ledger.


In Ripple's consensus algorithm, the identities of participating voting nodes are known in advance. Therefore, the algorithm is more efficient than anonymous consensus algorithms such as PoW. Transactions The confirmation time only takes a few seconds. This also determines that the consensus algorithm is only suitable for alliance chains or private chains. The Byzantine Fault Tolerance (BFT) capability of the Ripple consensus algorithm is (n-1)/5, which means it can tolerate Byzantine errors in 20% of the nodes in the entire network without affecting the correct consensus.



2. Simple diagram understanding mode


Schematic diagram of node interaction in the consensus process:



Consensus algorithm process:

< br />


(8) POOL verification pool consensus mechanism


Pool verification pool The consensus mechanism is a mechanism developed based on traditional distributed consensus algorithms (Paxos and Raft). The Paxos algorithm is a consensus algorithm based on message passing and highly fault-tolerant proposed in 1990. In the past, Paxos has been the standard for distributed protocols, but Paxos is difficult to understand and even harder to implement.now. Raft is a consensus algorithm released in 2013 that is simpler than Paxos and can realize the problems solved by Paxos. The process of reaching consensus in Paxos and Raft is like an election. Candidates need to convince the majority of voters (servers) to vote for them and follow their actions once selected. The difference between Paxos and Raft lies in the specific process of election. The Pool verification pool consensus mechanism is based on these two mature distributed consensus algorithms, supplemented by a data verification mechanism.






㈡ Blockchain consensus algorithm - (4) PoA consensus (Proof of Activity)

PoA consensus (Proof of Activity) is also called proof of activity. It combines the characteristics of PoW workload proof and PoS equity proof and expands accordingly. PoA consensus has more complex accounting node selection and a fairer reward mechanism.

PoA activities prove that the main advantage is to use fair incentives to ensure that nodes remain online and mobilize node enthusiasm. Online miners have a certain probability of earning profits even if they are not mining. Greatly improved the quality of network-wide maintenance.

step1: Each miner first uses its own computing power to pass the workload proof mechanism to obtain the nonce and generate an empty block header. This block header has no transaction information data and other data is consistent with the normal block. .

step2: The node that first generates the empty block broadcasts to the entire network nodes. After receiving the message, the entire network nodes splice the hash value of this block with the hash value of the previous block, and then Add n fixed suffix values ​​for hashing, and finally get n values ​​as input, enter the follow-the-satoshi program, and then output n random equity holders.

step3: The first n-1 random equity holders sign the empty block. The nth random equity holder is the node that has obtained the accounting right. He will be in the empty area. Add transaction data and signatures on a block basis.

step4: The nth random equity holder will broadcast the packaged block to the entire network. After receiving the block, all network nodes will verify it and upload it to the chain after successful verification.

step5: The miner who generated the empty block shares the transaction fee reward with the nth random equity holder and the first n-1 signed random equity holders.

㈢ Three common consensus mechanisms in blockchain

Blockchain is built on a P2P network and is participated by nodes.The biggest feature of the distributed ledger system is "decentralization". That is to say, in the blockchain system, there is no need to establish trust between users, between users and institutions, and between institutions. Transactions can be realized by relying only on the blockchain protocol system.

But how to ensure the accuracy, authority, and reliability of the ledger? Why do nodes on the blockchain network participate in accounting? What should I do if the node is fake? How to prevent the ledger from being tampered with? How to ensure data consistency between nodes? …These are the problems that blockchain needs to solve when establishing “decentralized” transactions, resulting in the consensus mechanism.

The so-called "consensus mechanism" is to complete the verification and confirmation of transactions in a very short time through the voting of special nodes; when there is a disagreement, without central control, several Nodes participate in decision-making to reach consensus, that is, how to establish a trust relationship between individuals who have no basis for trust in each other.

Blockchain technology uses a set of consensus-based mathematical algorithms to establish a "trust" network between machines, thereby creating new credit through technical endorsement rather than centralized credit institutions.

Different blockchain types require different consensus algorithms to ensure that the last block on the blockchain can reflect the status of the entire network at any time.

So far, the blockchain consensus mechanisms mainly include the following: POW workload proof, POS equity proof, DPOS authorized equity proof, Paxos, PBFT (Practical Byzantine Fault Tolerance Algorithm), dBFT, DAG ( Directed acyclic graph)

Next, we will mainly talk about the principles and application scenarios of common POW, POS, and DPOS consensus mechanisms

Concept:

Proof of work was originally an economic term, referring to the measurement method set up by the system to achieve a certain goal. A simple understanding is a certificate to confirm that you have done a certain amount of work, and to prove that the corresponding amount of work has been completed by certifying the results of the work.

The proof-of-work mechanism has the advantage of complete decentralization. In a blockchain with a proof-of-work mechanism as the consensus, nodes can enter and exit freely and calculate the numerical solution of the random hash. The ability to compete for accounting rights and obtain correct numerical solutions to generate blocks is a concrete manifestation of node computing power.

Applications:

The most famous application of POW is Bitcoin. In the Bitcoin network, during the Block generation process, miners need to solve complex cryptographic mathematical problems to find a Block Hash that meets the requirements, consisting of N leading zeros. The number of zeros depends on the difficulty value of the network.During this period, a lot of trial calculations (workload) are required, and the calculation time depends on the hashing speed of the machine.

Finding a reasonable hash is a probabilistic event. When a node has n% of the computing power of the entire network, the node has an n/100 probability of finding the Block Hash. After the node successfully finds a satisfactory Hash value, it will immediately broadcast the packaged block to the entire network. The nodes in the network will verify it immediately after receiving the broadcast packaged block.

If the verification passes, it means that a node has successfully solved the puzzle, and it will no longer compete for the current block, but choose to accept the block, record it in its own ledger, and then proceed to the next block. Competitive guessing game of blocks. Only the fastest puzzle-solving block in the network will be added to the ledger, and other nodes will copy it, thus ensuring the uniqueness of the entire ledger.

If a node engages in any cheating behavior, it will cause the network node verification to fail and directly discard its packaged block. This block will not be recorded in the general ledger, and the cost of the cheating node will be It is all in vain. Therefore, under the huge mining cost, miners voluntarily comply with the consensus protocol of the Bitcoin system, thus ensuring the security of the entire system.

Advantages and Disadvantages

Advantages: The results can be verified quickly, the system bears a large number of nodes, and the cost of evil is high to ensure the conscious compliance of miners.

Disadvantages: It requires a large amount of algorithm consumption, and it takes a long time to reach consensus

Concept:

Proof of Stake mechanism (Proof of Stake), requirements A certifier provides ownership of a certain amount of cryptocurrency.

The way the proof-of-stake mechanism works is that when a new block is created, the miner needs to create a "coin rights" transaction, which will send some coins to the miners themselves according to a preset ratio. The proof-of-stake mechanism reduces the mining difficulty of nodes in equal proportions based on the proportion and time of tokens owned by each node based on the algorithm, thus speeding up the search for random numbers.

Application:

In 2012, a netizen with the pseudonym Sunny King launched Peercoin, which was the first application of the proof-of-stake mechanism in encrypted electronic currency. The biggest innovation of PPC is that its mining method mixes POW and POS methods, uses a proof-of-work mechanism to issue new coins, and uses a proof-of-stake mechanism to maintain network security.

In order to implement POS, Sunny King learned from Satoshi Nakamoto’s Coinbase and designed a special type of transaction called Coinstake.

The picture above shows the working principle of Coinstake.The currency age refers to the holding period of the currency. If you own 10 coins and hold them for 10 days, then you have collected 100 days of currency age. If you use these 10 coins, the coin age is consumed (destroyed).

Advantages and Disadvantages:

Advantages: Shortens the time required to reach consensus and is more energy-saving than proof of work.

Disadvantages: Essentially, nodes in the network are still required to perform mining operations, and the authenticity of transfers is difficult to guarantee

Concept:

Authorized equity certificate Mechanism (Delegated Proof of Stake) is similar to board voting. This mechanism has a built-in real-time shareholder voting system, just like the system is convening a never-ending shareholders' meeting at any time, where all shareholders vote to decide company decisions.

While trying to solve the problems of traditional PoW and PoS mechanisms, authorized proof of equity can also offset the negative effects of centralization by implementing technological democracy. The decentralization of the blockchain established based on the DPoS mechanism relies on a certain number of representatives rather than all users. In such a blockchain, all nodes vote to elect a certain number of node representatives, who act on behalf of all nodes to confirm blocks and maintain the orderly operation of the system.

At the same time, all nodes in the blockchain have the power to remove and appoint representatives at any time. If necessary, all nodes can vote to disqualify the current node representatives and re-elect new representatives to achieve real-time democracy.

Application:

Bitshare is a type of cryptocurrency that uses the DPOS mechanism. By introducing the concept of witnesses, witnesses can generate blocks, and everyone who holds BitShares can vote for witnesses. Candidates who get the top N (N is usually defined as 101) candidates in the total number of consent votes can be elected as witnesses. The number of elected witnesses (N) must meet: at least half of the participating voters believe that N has been fully decentralized. .

The candidate list of witnesses is updated every maintenance cycle (1 day). The witnesses are then randomly arranged, and each witness has 2 seconds of permission time to generate a block in order. If the witness cannot generate a block in a given time slice, the block generation permission is given to the witness corresponding to the next time slice. . This design of DPoS makes the generation of blocks faster and more energy-saving.

DPOS makes full use of the votes of shareholders to reach consensus in a fair and democratic way. The N witnesses they voted for can be regarded as N mining pools, and these N mining pools Each other's rights are completely equal. Shareholders can change these witnesses (mining pools) by voting at any time, as long as they provideThe computing power is unstable, the computer is down, or they try to use the power in their hands to do evil.

Advantages and Disadvantages:

Advantages: Reduce the number of nodes participating in verification and accounting, thereby achieving second-level consensus verification

Disadvantages: Centrality Weaker, the security is weaker than POW, and the node agents are artificially selected, and the fairness is lower than POS. At the same time, the entire consensus mechanism still relies on the additional issuance of tokens to maintain the stability of the agent nodes.

㈣ An introduction to the principles and applications of blockchain technology

1. Blockchain is a series of data blocks generated using cryptographic methods. Each data block contains The information of all Bitcoin network transactions in the past ten minutes is used to verify the validity of its information (anti-counterfeiting) and generate the next block. It is the underlying technology of Bitcoin, like a database ledger that records all transaction records.

2. Broad definition: Use encrypted chain structure to verify and store data, use distributed node consensus algorithm to generate and update data, use automated script code (smart contract) to convert and operate data A new decentralized infrastructure and distributed computing paradigm.

3. Narrow definition: A decentralized shared account that combines data blocks into a specific data structure in a chain in chronological order, and is cryptographically guaranteed to be non-tamperable and non-forgeable.

4. Characteristics of blockchain: Decentralization: The verification, accounting, storage, maintenance and transmission of blockchain data are all based on distributed system institutions, using pure Mathematical methods rather than central structures are used to establish trust relationships between distributed nodes, thereby forming a decentralized and trustworthy distributed system.

5. Time series data: Blockchain uses a chain block structure with timestamps to store data, thereby adding a time dimension to the data and having strong verifiability and traceability.

6. Collective maintenance: The blockchain system uses a specific economic incentive mechanism to ensure that all nodes in the distributed system can participate in the verification process of data blocks, and select specific nodes through a consensus algorithm Add new blocks to the blockchain.

7. Programmable: Blockchain technology provides a flexible script code system to support users in creating advanced smart contracts, currencies or other decentralized applications.

8. Safe and trustworthy: Blockchain technology uses asymmetric cryptography principles to encrypt data, and at the same time uses the powerful computing power formed by consensus algorithms such as workload proof of each node of the distributed system. To resist external attacks and ensure that blockchain data cannot be tampered with or forged, it has high security.

9. Blockchain application scenarios: digital currency: represented by Bitcoin Damin Coin, which is essentiallyThe issuance process of digital currency generated by a distributed network system does not rely on a specific centralized institution.

㈤ Consensus mechanism of blockchain

1. How to confirm and reach consensus on transaction information on the network?

Although the consensus mechanism is often mentioned, the meaning and understanding of the consensus mechanism are not clear. Therefore, it is necessary to understand the relevant concepts, principles and implementation methods of the consensus mechanism.

The transaction information of the blockchain is transmitted to each node in the network through network broadcast. How to confirm the broadcast information and reach a consensus among the entire network nodes and finally write it into the block? If there is no corresponding reliable and secure implementation mechanism, it will be difficult to realize its basic functions. Therefore, the consensus mechanism is a key to the operation of the entire network.

The consensus mechanism solves the problem of how the blockchain can achieve consistency in a distributed scenario. The blockchain can reach a relatively balanced state among many nodes because of the consensus mechanism. So how does the consensus mechanism solve the problem of mutual trust between nodes based on the idea of ​​decentralization?

When the idea of ​​distribution was proposed, people began to design consensus algorithms based on the FLP theorem and the CAP theorem. Standardly speaking, the consistency of an ideal distributed system should meet the following three points:

1. Termination: The consistency result can be completed within a limited time.

2. Consensus: The final decision-making results of different nodes should be the same.

3. Validity: The result of the decision must be a proposal put forward by other processes.

However, in actual computer clusters, the following problems may exist:

1. Nodes have different transaction processing capabilities, and the data throughput of network nodes is different

2. The communication channel between nodes may be unsafe

3. There may be malicious nodes

4. When asynchronous processing capabilities reach a high degree of consistency, The scalability of the system will become worse (cannot tolerate the addition of new nodes).

Scientists believe that it is impossible to achieve complete consistency in a distributed scenario. However, engineers can sacrifice part of the cost in exchange for the consistency of distributed scenarios. The above two major theorems also have this idea. Therefore, various formula mechanisms based on blockchain design can be regarded as sacrificing part of the cost in exchange for more adaptability. The consistency ofDepending on the consistency of the scene at that time, a flexible blockchain system can be realized, which is a pluggable blockchain system. Today I will introduce my views and analysis on various consensus mechanisms. Distributed systems with or without malicious nodes are divided into Byzantine fault-tolerant and non-Byzantine fault-tolerant mechanisms.

The FLP theorem is the impossibility of FLP. It proves that in a distributed scenario, no matter any algorithm, even if only one process hangs up, there is an inability to reach consensus for other non-failed processes. possible.

FLP is based on the following assumptions:

Can only be modified once: Each process initially records a value (0 or 1). The process can receive messages, change the value, and send messages. When the process enters the decide state, the value will no longer change. The protocol ends successfully when all non-failed processes enter the decided state. This is relaxed to the extent that some processes enter the decided state, even if the agreement is successful.

Asynchronous communication: The biggest difference from synchronous communication is that there is no clock, no time synchronization, no timeout, no detection failure, messages can be delayed arbitrarily, and messages can be out of order.

Communication is robust: As long as the process does not fail, the message will be delayed indefinitely, but will eventually be delivered; and the message will only be delivered once (no duplication).

Fail-Stop model: A process failure is like a downtime and no more messages are processed.

Number of failed processes: At most one process fails.

CAP is the most discussed theory in distributed systems, especially in the field of distributed storage. CAP was proposed by Eric Brewer at the PODC meeting in 2000. It was a result of Eric Brewer's research on data consistency (consistency), service availability (availability), and partition fault tolerance (partition- tolerance) conjecture:

Data consistency (consistency): If the system returns success for a write operation, then subsequent read requests must read the new data; if the system returns failure, then all read operations No one can read this data. For the caller, the data has strong consistency (also called atomic and linearizable consistency) [5]

Service availability (availability) : All read and write requests are received within a certain period of timeWhen a response is received, it can be terminated and will not wait forever

Partition-tolerance: In the case of network partition, the separated nodes can still provide normal external services

If AP is satisfied at a certain moment, the separated nodes can serve externally at the same time but cannot communicate with each other, which will lead to inconsistent status, that is, C cannot be satisfied; if CP is satisfied, C cannot be achieved in the case of network partition, and the request can only wait forever, that is, it cannot be satisfied. A is satisfied; if CA is to be satisfied, the node status must be consistent within a certain period of time, and network partitioning must not occur, then P cannot be satisfied.

C, A, and P can only satisfy at most two of them. Like the FLP theorem, the CAP theorem also indicates an unreachable result (impossibility result).

㈥ Blockchain --- Consensus Algorithm

The PoW algorithm is a mechanism to prevent the abuse of distributed service resources and denial of service attacks. It requires nodes to perform complex operations that consume a moderate amount of time and resources, and the operation results can be quickly verified by other nodes, using time and energy as a guarantee to ensure that services and resources are used according to real needs.

The most basic technical principle in the PoW algorithm is the use of hashing algorithms. Assume that the hash value Hash(r) is found. If the original data is r (raw), the operation result is R (Result).

R = Hash(r)

The characteristic of the hash function Hash() is that for any input value r, the result R is obtained, and r cannot be deduced from R. When the input original data r changes by 1 bit, the resulting R value changes completely. In the Bitcoin PoW algorithm, the algorithm difficulty d and the random value n are introduced, and the following formula is obtained:

Rd = Hash(r+n)

This formula requires filling in the random In the case of value n, the first d bytes of the calculation result Rd must be 0. Due to the unknown nature of the hash function results, each miner has to do a lot of calculations to get the correct result. After the calculation result is broadcast to the entire network, other nodes only need to perform a hash operation to verify it. The PoW algorithm uses this method to make calculations consume resources, and verification only needs to be done once.

The PoS algorithm requires node verifiers to pledge a certain amount of funds to be eligible for mining and packaging, and the regional chain system uses a random method when selecting packaging nodes. When the node pledges The more funds there are, the greater the probability of being selected to package the block.

In POS mode, each coin generates 1 coin age every day. For example, if you hold 100 coins for a total of 30 days, thenWell, your coin age will be 3000 at this time. At this time, if you verify a POS block, your currency age will be cleared to 0, and the corresponding digital currency interest will be obtained from the block.

The process of a node producing blocks through the PoS algorithm is as follows: To become a block producing node, an ordinary node must first pledge its assets. When it is its turn to produce a block, it packages the block and then broadcasts it to the entire network. , other verification nodes will verify the legitimacy of the block.

The DPoS algorithm is similar to the PoS algorithm and also uses shares and equity pledges.

But the difference is that the DPoS algorithm uses a delegated pledge method, which is similar to the method of universal election of representatives to select N super nodes to record and produce blocks.

Voters cast their votes for a certain node. If a certain node is elected as an accounting node, then the accounting node can often use any method to reward its voters after obtaining the block reward.

These N accounting nodes will take turns to produce blocks, and the nodes will supervise each other. If they do evil, the pledge deposit will be deducted.

By trusting a small number of honest nodes, unnecessary steps in the block signing process can be removed, increasing the speed of transactions.

Byzantine problem:

Byzantium was the capital of the ancient Eastern Roman Empire. For defense, an army led by a single general was stationed in each fiefdom. Between the generals The message could only be delivered by messenger. In a war, all generals must reach a consensus and decide whether to go to war together.

However, there may be traitors within the army who will influence the generals to reach a consensus. The Byzantine Generals Problem refers to the problem of how the remaining generals can reach a unanimous decision when one of the generals is known to be a traitor.

BFT:

BFT is Byzantine fault tolerance. Byzantine fault tolerance technology is a type of fault tolerance technology in the field of distributed computing. The Byzantine hypothesis is a modeling of the real world, where computers and networks may behave unpredictably due to hardware errors, network congestion or outages, and malicious attacks. Byzantine fault tolerance techniques are designed to handle these abnormal behaviors and meet the specification requirements of the problem to be solved.

Byzantine fault-tolerant system:

The failed node is called a Byzantine node, and the normal node is a non-Byzantine node.

Assuming that the distributed system has n nodes, and assuming that the entire system has no more than m Byzantine nodes (n ≥ 3m + 1), the Byzantine fault-tolerant system requiresThe following two conditions are met:

In addition, the Byzantine fault-tolerant system needs to achieve the following two indicators:

PBFT is a practical Byzantine fault-tolerant algorithm, which solves the problem of inefficiency of the original Byzantine fault-tolerant algorithm. , the time complexity of the algorithm is O(n^2), so that the Byzantine fault tolerance problem can be solved in actual system applications

PBFT is a state machine copy replication algorithm, all copies are in During the operation of a view (view) rotation, the main node is determined by the view number and the number of nodes, that is: the main node p = v mod |R|. v: view number, |R| number of nodes, p: primary node number.

The consensus process of the PBFT algorithm is as follows: the client (Client) initiates a message request (request) and broadcasts it to each replica node (Replica), and one of the master nodes (Leader) initiates a proposal message pre -prepare and broadcast. Other nodes obtain the original message and send prepare messages after the verification is completed. Each node receives 2f+1 prepare messages, that is, it is considered ready and sends a commit message. When the node receives 2f+1 commit messages and the client receives f+1 identical reply messages, it means that the request initiated by the client has reached a network-wide consensus.

The specific process is as follows:

Client c sends a request to master node p. o: the specific operation of the request, t: the timestamp appended by the client during the request, c: client identifier. REQUEST: Contains message content m, and message digest d(m). The client signs the request.

When the master node receives the client's request, it needs to conduct the following verifications:

a. Whether the signature of the client's request message is correct.

Illegal requests are discarded. For a correct request, a number n is assigned. The number n is mainly used to sort the client's requests. Then broadcast a <, m> message to other replica nodes. v: view number, d client message summary, m message content. performs master node signature. n is [h, H] to be within a certain range. For specific reasons, please refer to the Garbage Collection chapter.

When replica node i receives the PRE-PREPARE message from the master node, the following verification is required:

a. Whether the signature of the master node's PRE-PREPARE message is correct.

b. Whether the current replica node has received aPRE-PREPARE information under the same v and also numbered n, but with different signatures.

c. Whether the abstracts of d and m are consistent.

d. Whether n is within the interval [h, H].

Illegal requests are discarded. Correct request, replica node i sends a message to other nodes including the master node, v, n, d, m is the same as the content of the above PRE-PREPARE message, i is the current replica node number. Sign the replica node i. Record PRE-PREPARE and PREPARE messages to the log, which are used to restore unfinished request operations during the View Change process.

When the master node and replica node receive the PREPARE message, they need to conduct the following verifications:

a. Whether the signature of the replica node's PREPARE message is correct.

b. Whether the current replica node has received n under the same view v.

c. Whether n is within the interval [h, H].

d. Whether d is the same as d in the currently received PRE-PPREPARE

Illegal request is discarded. If replica node i receives 2f+1 verified PREPARE messages, it sends a message to other nodes including the master node, where v, n, d, i is the same as the content of the above PREPARE message. same. performs the signature of replica node i. Record the COMMIT message to the log, which is used to restore the unfinished request operation during the View Change process. Record PREPARE messages sent by other replica nodes to the log.

When the master node and replica node receive the COMMIT message, they need to conduct the following verifications:

a. Whether the signature of the COMMIT message of the replica node is correct.

b. Whether the current replica node has received n under the same view v.

c. Whether the abstracts of d and m are consistent.

d. Whether n is within the interval [h, H].

Illegal requests are discarded. If replica node i receives 2f+1 verified COMMIT messages, it means that most nodes in the current network have reached a consensus, run the client's request operation o, and return To the client, r: is the result of the request operation. If the client receives f+1 identical REPLY messages, it indicates that the request was initiated by the client.A network-wide consensus has been reached, otherwise the client needs to determine whether to resend the request to the master node. Record COMMIT messages sent by other replica nodes to the log.

If the master node does evil, it may assign the same sequence number to different requests, or not allocate sequence numbers, or make adjacent sequence numbers discontinuous. The backup node should have the responsibility to actively check the validity of these sequence numbers.

If the master node goes offline or does something evil and does not broadcast the client's request, the client sets a timeout mechanism. If the timeout occurs, the request message is broadcast to all replica nodes. The replica node detects that the master node has done something evil or is offline, and initiates the View Change protocol.

View Change protocol:

The replica node broadcasts ​​messages to other nodes. n is the number of the latest stable checkpoint, C is the 2f+1 verified CheckPoint message set, and P is the PRE-PREPARE and PREPARE message set of outstanding requests by the current replica node.

When the master node p = v + 1 mod |R| receives 2f valid VIEW-CHANGE messages, it broadcasts messages to other nodes. V is a valid set of VIEW-CHANGE messages. O is the set of uncompleted PRE-PREPARE messages reinitiated by the master node. Selection rules for the PRE-PREPARE message set:

The replica node receives the NEW-VIEW message from the master node, verifies the validity, and if valid, enters the v+1 state and starts the PRE-PREPARE message in O processing flow.

In the above algorithm process, in order to ensure that the previous request can be restored during the View Change process, each replica node records some messages to the local log. When the request is executed The replica node needs to clear the record messages of the previous request.

The simplest way is to execute the consensus synchronization of the current state again after the Reply message. This is relatively expensive, so it can be executed after executing multiple requests K (for example: 100). A status synchronization. This status synchronization message is the CheckPoint message.

Replica node i sends to other nodes. n is the last view request number retained by the current node, d is a summary of the current status, and the CheckPointThe message is recorded in the log. If replica node i receives 2f+1 verified CheckPoint messages, the messages in the previous log are cleared and n is used as the current stable checkpoint.

This is an ideal situation. In fact, when the replica node i sends a CheckPoint message to other nodes, the other nodes have not completed K requests, so they will not respond to i's request immediately. It will also follow its own rhythm, moving forward, but the CheckPoint issued at this time does not form stable.

In order to prevent i from processing requests too quickly, set a high and low water level interval [h, H] mentioned above to solve this problem. The low water level h is equal to the number of the previous stable checkpoint, and the high water level H = h + L, where L is the value we specify, which is equal to an integer multiple of the number of requests processed in the checkpoint cycle K, and can be set to L = 2K. When the request processed by replica node i exceeds the high water mark H, it will stop and wait for the stable checkpoint to change before continuing.

In blockchain scenarios, it is generally suitable for private chain and alliance chain scenarios that require strong consistency. For example, in the IBM-led blockchain Hyperledger project, PBFT is an optional consensus protocol. In Hyperledger's Fabric project, the consensus module is designed as a pluggable module and supports consensus algorithms such as PBFT and Raft.

Raft is based on a leader-driven consensus model, in which an outstanding leader (Leader) will be elected, and the Leader will be fully responsible for managing the cluster. Responsible for managing replication logs between all nodes in the Raft cluster.

In the figure below, the Leader (S1) of the cluster will be selected during the startup process and serve all commands/requests from clients. All nodes in a Raft cluster maintain a distributed log (replicated log) to store and submit commands (log entries) issued by clients. The Leader accepts log entries from clients and replicates them among all followers (S2, S3, S4, S5) in the Raft cluster.

In a Raft cluster, a minimum number of nodes is required to provide the expected level of consensus guarantee, which is also called a quorum. The minimum number of votes required to perform an operation in a Raft cluster is (N / 2 +1), where N is the total number of members in the group, that is, at least more than half of the votes, which is why cluster nodes usually have an odd number of nodes. Therefore, in the above indicationIn this example, we need at least 3 nodes to have consensus guarantee.

If the legal quorum node is unavailable for any reason, that is, the votes do not exceed half, the negotiation will not reach an agreement and new logs cannot be submitted.

Data storage: Tidb/TiKV

Log: Alibaba's DLedger

Service discovery: Consul& etcd

< p> Cluster scheduling: HashiCorp Nomad

Can only accommodate faulty nodes (CFT), not evil nodes

Sequential voting, only serial apply, so high concurrency Poor performance in scenarios

Raft solves the distributed consensus problem by solving the three main sub-problems surrounding Leader election and managing the security functions of distributed logs and algorithms.

When we start a new Raft cluster or a leader is unavailable, a new leader will be elected through negotiation among all member nodes in the cluster. Therefore, in a given instance, a node of a Raft cluster can be in any of the following states: Follower, Candidate, or Leader.

When the system first starts, all nodes are followers. If they do not receive the heartbeat signal from the leader within a period of time, the follower will be converted into a candidate;

If a node If a Candidate node receives votes from the majority of nodes, the Candidate can be converted into a Leader, and the remaining Candidate nodes will return to the Follower state;

Once a Leader discovers that there is a Leader node in the system that is older than itself. If the term is higher, it will be converted to Follower.

Raft uses a heartbeat-based RPC mechanism to detect when a new election starts. During normal times, the Leader will regularly send heartbeat messages to all available Followers (in practice, the log and heartbeat may be sent together). Therefore, the other node starts in the Follower state and remains in the Follower state as long as it receives periodic heartbeats from the current Leader.

When a Follower reaches its timeout, it will start the election process by:

Based on the responses Candidate receives from other nodes in the cluster, three outcomes of the election can be derived.

The implementation of consensus algorithms is generally based on replicated state machines. What is a replicated state machine:

In simple terms: the same initial recognition state + the same input = Same end state. Different nodes should use the same and deterministic function to process input, rather than introducing uncertain values, such as local time, etc. It is a good idea to use replicated log. Log has the characteristics of persistence and order preservation, and is the cornerstone of most distributed systems.

With the Leader, all concurrent requests from the client can form an orderly log (status) sequence on the Leader's side to represent the order in which these requests are processed. The Leader then sends its log sequence to the Followers to maintain the global consistency of the entire system. Note that this is not strong consistency, but eventual consistency.

The log consists of log entries with a sequential number (log index). Each log entry consists of the term when it was created, and the data contained in the log, which can be of any type, from simple types to blocks of the blockchain. Each log entry can be represented by a [term, index, data] sequence pair, where term represents the term, index represents the index number, and data represents the log data.

The Leader attempts to execute replication commands on a majority of the nodes in the cluster. If the replication is successful, the command is submitted to the cluster and the response is sent back to the client. Similar to two-phase commit (2PC), but the difference from 2PC is that the leader only needs the consent of more than half of the nodes (in a working state).

Both leader and follower may crash, so the log maintained by the follower may have the following situations compared with the leader

When the leader and follower are inconsistent, the leader forces the follower to copy its own log, the Leader will try from back to front. Each time AppendEntries fails, it will try the previous log entry (decrementing the nextIndex value) until it successfully finds the consistent position point of each Follower's log (based on the two guarantees mentioned above), and then moves backward one by one. Cover FollowersThe entry following this position. So missing or extra entries may persist for multiple terms.

Requires the candidate's log to be at least as up-to-date as other nodes. If not, the follower node will not vote for the candidate.

Means that each submitted entry must exist in at least one of these servers. If a candidate's log is at least as up-to-date as the other logs in the majority, it will save all committed entries, avoiding a log rollback event.

That is, at most one leader can be elected in any term. This is very important, there can only be one leader in a replica set at any time. There is more than one leader in the system at the same time, which is called brain split. This is a very serious problem and will cause data coverage loss. In raft, two points guarantee this property:

Therefore, there must be only one leader in a certain term.

When the status of nodes in the cluster changes (the cluster configuration changes), the system is vulnerable to system failure. So, to prevent this, Raft uses something called a two-phase approach to changing cluster membership. Therefore, in this approach, the cluster first changes to an intermediate state (called federated consensus) before implementing a new membership configuration. Federated consensus enables the system to be used to respond to client requests even when transitioning between configurations, and its main purpose is to improve the availability of distributed systems.

㈦ Consensus mechanism of blockchain

The so-called "consensus mechanism" is to complete the verification and confirmation of transactions in a very short time through the voting of special nodes; For a transaction, if several nodes with unrelated interests can reach a consensus, we can think that the entire network can also reach a consensus on it. Beijing Muqi Mobile Technology Co., Ltd., a professional blockchain outsourcing development company, welcomes discussions for cooperation. Below we will look at several consensus mechanisms of blockchain, hoping to help everyone understand the basic technology of blockchain.

Due to the development of blockchain technology, everyone is no longer unfamiliar with the term consensus mechanism. With the development of technology, various innovative consensus mechanisms are also developing.

POW proof of work

Bitcoin uses the PoW proof of work mechanism, and later Ethereum used the PoW consensus mechanism. Pow is equivalent to calculating a difficult mathematical problem, which is to calculate the hash value of a new block, and the difficulty of the calculation will be adjusted every period of time. Although PoW is a consensus mechanism that is relatively recognized by everyone, calculations will consume a lot of energy and may pollute the environment.

POS Proof of Stake

The probability of obtaining accounting rights is determined by the number and duration of holding Tokens. Compared with POW, POS avoids a large amount of resource waste caused by mining and shortens the time for each node to reach consensus. If the network environment is good, it can be achieved in milliseconds and has low requirements on node performance.

However, the shortcomings of POS are also obvious. Nodes holding more Tokens have a greater chance of obtaining accounting rights. This will lead to the "Matthew Effect", where the rich will get richer, destroying the decentralization of the blockchain. Centralization.

DPOS Proof of Equity

The principle of DPOS Delegated Proof of Equity is the same as that of POS. The main difference is that DPOS Token holders can vote to elect agents as super nodes, responsible for Produce blocks and maintain consensus rules on the network. If these nodes fail to perform their duties, new nodes will be voted in. The same disadvantage also tends to be centralized.

POA Proof of Authority

POA nodes can reach consensus without communication, so it is extremely efficient. And it can also resist computing power attacks very well and has high security. But POA requires a centralized authoritative node to verify identity, which means it will harm the decentralization of the blockchain, which is also a compromise between decentralization and improved efficiency.

㈧ What consensus mechanisms are currently used in the blockchain and what are their respective advantages, disadvantages and scope of application

There are currently four main types of consensus mechanisms: Pow, Pos, DPos, and Pool
1. Pow workload proof is the familiar mining. Through AND or operation, a random number that meets the rules is calculated, that is, the accounting right is obtained, and the data that needs to be recorded in this round is sent to the entire network. Other nodes verify and store them together;
Advantages: Complete decentralization, nodes can enter and exit freely;
Disadvantages: At present, Bitcoin has attracted most of the world's computing power, and other blockchain applications use the Pow consensus mechanism. It is difficult to obtain the same computing power to ensure one's own security; mining causes a lot of waste of resources; the period for reaching consensus is long and is not suitable for commercial applications

2. PoS equity proof, a type of POW Upgrade the consensus mechanism; according to the proportion and time of tokens held by each node, the mining difficulty is reduced in an equal proportion, thereby speeding up the speed of finding random numbers.
Advantages: It shortens the time to reach consensus to a certain extent
Disadvantages: It still requires mining, which essentially does not solve the pain points of commercial applications

3. DPos share authorization certification mechanism , similar to board voting, currency holders vote for a certain number of nodes to perform verification and accounting on their behalf.
Advantages: Significantly reduces the number of nodes participating in verification and accounting, and can achieve second-level consensus verification
Disadvantages: The entire consensus mechanism still relies on tokens, and many commercial applications do not require tokensExisting

4. Pool verification pool, based on traditional distributed consistency technology, plus data verification mechanism; it is the consensus mechanism currently used in a wide range of industry chains
Advantages: Not required Tokens can also work, achieving second-level consensus verification based on mature distributed consensus algorithms (Pasox, Raft);
Disadvantages: The degree of decentralization is not as good as bictoin; more suitable for multi-center business models with multi-party participation

It is a huge advantage when using the consensus mechanism to ensure data consistency (the consensus mechanism was first proposed by Ripple, a network transaction synchronization mechanism that prioritizes data correctness. In the consensus network, no matter how the software code is Changes, if you cannot achieve consensus, you will not be able to enter the network, let alone a fork).
————————————————
PS: A little self-deprecating, although the consensus mechanism can definitely ensure that no hard fork will occur at any time. However, the disadvantage of this mechanism is also obvious, that is, it takes much longer to achieve consensus with other nodes than the current Bitcoin network. In extreme cases, the consequences of being disconnected in the Ripple consensus mechanism network are also terrifying.

It is possible that your home has a power outage for one day, and the entire system will no longer be able to achieve consensus with other Rippled nodes the next day (the consensus mechanism actually requires more than 80% of the nodes to recognize your data, your Submission will be accepted by other nodes, otherwise the connection will be exclusively refused), and you can even only clear all more than 500 GB of your data and resynchronize before you can connect to other Ripple nodes.

So currently, the existing Rippled end is not suitable for civilian use (for commercial use, the impact is relatively small. For example, RL's own Rippled node is hosted in the Amazon cloud data center. If it does not respond for a long time, it can be very high. The amount of compensation is claimed, and that kind of place is almost uninterrupted except for major disasters). This is also one of the aspects that RL has always wanted to improve.

博客主人唯心底涂
男,单身,无聊上班族,闲着没事喜欢研究股票,无时无刻分享股票入门基础知识,资深技术宅。
  • 37052 文章总数
  • 3637265访问次数
  • 3078建站天数