A comprehensive and detailed explanation of 15 blockchain consensus algorithms

1. Abstract

This article tries to list all the major consensus algorithms and evaluate their respective advantages and disadvantages. The consensus algorithm is the core technology of the blockchain. This article will be continuously updated based on the author’s understanding. If readers find any omissions or errors, I hope they can point them out through comments.
2. Blockchain consensus algorithm
2.1 Proof of Work (PoW, Proof of Work)

Pros: Extensively tested since 2009 and still widely used.
Disadvantages: slow. It consumes a lot of energy and is not good for the environment. Vulnerable to "economies of scale".
Users: Bitcoin, Ethereum, LiteCoin, Dogecoin, etc.
Type: Competitive consensus.
Explanation: PoW is the first consensus algorithm. It was proposed by Satoshi Nakamoto in his paper to establish a distributed trustless consensus and identify the "double spend" problem. PoW is not a new idea, but Satoshi Nakamoto combined Pow with existing ideas such as cryptographic signatures, Merkle chains, and P2P networks to form a usable distributed consensus system. Cryptocurrency is the first basis and application of such a system and is therefore uniquely innovative.
In the way PoW works, blockchain participants (called "miners") must solve some kind of "complex but useless" computational problem in order to add a block of transactions to the blockchain.
As long as more than half of the work submitted by miners is trustworthy, Bitcoin is safe.
From a certain perspective, PoW is a bit like buying a lottery ticket, except that the probability is higher.
Technical principle:
The core technical principle of workload proof is the hash function (hash). In Bitcoin, PoW work is actually how to calculate the target hash value of a block, allowing users to perform a large number of exhaustive operations. At the same time, to obtain this hash value, some necessary conditions must be met. This condition is in the block The chain is actually a difficulty coefficient value. By whether the calculated hash value matches the first N bits which are all 0, the proof of work is finally achieved.
for example:
For example, given a fixed string "Hello, blockchain", the current calculation problem is to concatenate this string with a random number (Nonce), and calculate a fixed 256-bit length hash value through SHA256 hashing , if the first 5 digits of the calculation result are all 0, it is considered that the calculation conditions are met, and the random number (Nonce) value obtained is proved to be a valid random number to achieve proof of work.
2.2 Proof of Stake (PoS, Proof of Stake)

Advantages: energy saving, higher cost to attackers, less susceptible to "economies of scale".
Disadvantage: "Nothing at stake" attack problem.
Users: Ethereum (coming soon), Peercoin, Nxt.
Type: Competing consensus.
Explanation:
Similar to property being stored in a bank, this model will be based on your The amount and time you hold digital currency will allocate you corresponding interest.
Simply put, it is a system that pays you interest based on the amount and time you hold the currency. In the proof-of-stake POS model, there is a term It’s called coin age. Each coin generates 1 coin age every day. For example, if you hold 100 coins for a total of 30 days, then your coin age will be 3000. At this time, if you find a POS area block, your coin age will be cleared to 0. Every time you are cleared of 365 coin ages, you will get 0.05 coins of interest from the block (assuming that the interest can be understood as an annual interest rate of 5%), then in this case , interest = 3000 * 5% / 365 = 0.41 coins. This is very interesting. Holding coins has interest. Ethereum uses the POS consensus algorithm. From a certain point of view, PoS is a bit like a bank
deposit. You hold The longer the time, the larger the principal, the more interest you will get.
Technical principle:
Every absentee has the right to produce blocks (i.e., mine). As long as the block is produced successfully, there will be rewards given by the system. There is no need to go through complicated calculations to mine. The only question is who will produce the block. The greater the stake, the greater the probability of producing the block, and vice versa. There are many variations of POS, and the stake can be the number of coins held. Or the amount paid, etc.

Go demo code implementation:

package main

import (
    "time"
    "strconv"
    "crypto/sha256"
    "math/rand"
    "fmt"
    "encoding/hex"
)

//实现pos挖矿的原理

type Block struct {
    
    
    Index int
    Data string //
    PreHash string
    Hash string
    Timestamp string
    //记录挖矿节点
    Validator *Node

}

func genesisBlock() Block  {
    
    

    var genesBlock  = Block{
    
    0, "Genesis block","","",time.Now().String(),&Node{
    
    0, 0, "dd"}}
    genesBlock.Hash = hex.EncodeToString(BlockHash(&genesBlock))
    return genesBlock
}

func BlockHash(block *Block) []byte  {
    
    
    record := strconv.Itoa(block.Index) + block.Data + block.PreHash + block.Timestamp + block.Validator.Address
    h := sha256.New()
    h.Write([]byte(record))
    hashed := h.Sum(nil)

    return hashed
}

//创建全节点类型
type Node struct {
    
    
    Tokens int //持币数量
    Days int //持币时间
    Address string //地址
}


//创建5个节点
//算法的实现要满足 持币越多的节点越容易出块
var nodes = make([]Node, 5)
//存放节点的地址
var addr = make([]*Node, 15)


func InitNodes()  {
    
    

    nodes[0] = Node{
    
    1, 1, "0x12341"}
    nodes[1] = Node{
    
    2, 1, "0x12342"}
    nodes[2] = Node{
    
    3, 1, "0x12343"}
    nodes[3] = Node{
    
    4, 1, "0x12344"}
    nodes[4] = Node{
    
    5, 1, "0x12345"}

    cnt :=0
    for i:=0;i<5;i++ {
    
    
        for j:=0;j<nodes[i].Tokens * nodes[i].Days;j++{
    
    
            addr[cnt] = &nodes[i]
            cnt++
        }
    }

}

//采用Pos共识算法进行挖矿
func CreateNewBlock(lastBlock *Block, data string) Block{
    
    

    var newBlock Block
    newBlock.Index = lastBlock.Index + 1
    newBlock.Timestamp = time.Now().String()
    newBlock.PreHash = lastBlock.Hash
    newBlock.Data = data


    //通过pos计算由那个村民挖矿
    //设置随机种子
    rand.Seed(time.Now().Unix())
    //[0,15)产生0-15的随机值
    var rd =rand.Intn(15)

    //选出挖矿的旷工
    node := addr[rd]
    //设置当前区块挖矿地址为旷工
    newBlock.Validator = node
    //简单模拟 挖矿所得奖励
    node.Tokens += 1
    newBlock.Hash = hex.EncodeToString(BlockHash(&newBlock))
    return newBlock
}

func main()  {
    
    

    InitNodes()

    //创建创世区块
    var genesisBlock = genesisBlock()

    //创建新区快
    var newBlock = CreateNewBlock(&genesisBlock, "new block")

    //打印新区快信息
    fmt.Println(newBlock)
    fmt.Println(newBlock.Validator.Address)
    fmt.Println(newBlock.Validator.Tokens)

}

Output result: {1 new block
72e8838ad3bb761c7d3ba42c4e6bad86409dd3f4ce958c890409c4b9ddf44171
e4f9575cfb14ee146810862c9e5cc78ebff185f5888f428dbb945bd9060b31f
7 2018-06-29 19:29:04.827332898 +0800 CST m=+0.000837770 0xc42007e0a0}
0x12341

2.3 Delegated Proof-of-Stake (DPOS)

Advantages:
Energy-saving, fast, and high-traffic blogging website Steemit uses it. The block time of EOS is 0.5 seconds.
Disadvantages:
Slightly centralized, participants with high stakes can vote to become a validator. This is a problem that has appeared in EOS recently.
Adopters: BitShares, Steemit, EOS, Lisk, Ark.
Type: Collaborative Consensus
Explanation: In the DPoS system, stake holders can elect leaders (or witnesses). With authorization from stake holders, these leaders can vote. This mechanism makes DPoS faster than normal PoS.
For example, 21 witnesses are elected in EOS, and there are a bunch of nodes (potential witnesses) as candidates. Once a witness node dies or commits a malicious act, a new node will immediately replace the witness node. Witnesses receive a payment for generating blocks. This fee is established by the equity holder.
Usually, all nodes use a polling method to generate one block at a time. This mechanism prevents one node from publishing consecutive blocks and thereby performing a "double spend" attack. If a witness does not generate a block in the time slot assigned to it, then the time slot is skipped and the next witness generates the next block. If a witness continues to lose his blocks, or publishes incorrect transactions, the stake holders will vote him out and replace him with a better witness.
In DPoS, miners can cooperate to generate blocks instead of competing as in PoW and PoS. Through partial centralization of block generation, DPoS can run orders of magnitude faster than other consensus algorithms.
From a certain perspective, DPOS is a bit like a parliamentary system or a People's Congress system. If a representative fails to perform their duties (fails to generate a block when it is their turn), they will be removed from the list and a new supernode will be elected to replace them. EOS uses the DPOS consensus algorithm.
Technical principle:
Suppose n is 21. There are hundreds of nodes running for election. The currency holders vote on these nodes and select the 21 with the most votes. These 21 will take turns to produce blocks.
GO DEMO simple implementation:

package main

import (
    "fmt"
    "math/rand"
    "time"
    "strconv"
    "crypto/sha256"
    "encoding/hex"
)

type Block struct {
    
    
    Index int
    Timestamp string
    Prehash string
    Hash string
    Data []byte

    delegate *Node// 代理 区块由哪个节点挖出
}


func GenesisBlock()  Block {
    
    
    gene := Block{
    
    0, time.Now().String(),"", "", []byte("genesis block"), nil}

    gene.Hash = string(blockHash(gene))

    var delegate *Node = new(Node)
    delegate.Name = "Genis Block"
    delegate.Votes = 0;
    gene.delegate = delegate

    return gene
}

func blockHash(block Block) []byte  {
    
    

    record := strconv.Itoa(block.Index) + block.Timestamp + block.Prehash + hex.EncodeToString(block.Data)

    h := sha256.New()
    h.Write([]byte(record))
    hashed := h.Sum(nil)
    return hashed
}


//节点类型
type Node struct {
    
    
    Name  string //节点名称
    Votes int    // 被选举的票数
}

func (node *Node)GenerateNewBlock(lastBlock Block, data []byte) Block  {
    
    

    var newBlock = Block{
    
    lastBlock.Index+1, time.Now().String(), lastBlock.Hash, "", data, nil}

    newBlock.Hash = hex.EncodeToString(blockHash(newBlock))
    newBlock.delegate = node
    return newBlock

}

//创建节点
var NodeArr = make([]Node,10)
func CreateNode() {
    
    

    for i := 0; i < 10; i++ {
    
    
        name := fmt.Sprintf("NODE %d num", i+1)
        NodeArr[i] = Node{
    
    name, 0}
    }

}

//简单模拟投票
func Vote()  {
    
    
    for i := 0; i < 10; i++ {
    
    
        rand.Seed(time.Now().UnixNano())
        vote := rand.Intn(10) + 1
        NodeArr[i].Votes = vote
    }
}


//选出票数最多的前3位
func SortNodes() []Node  {
    
    
    n:= NodeArr
    for i := 0; i<len(n) ;i++  {
    
    
        for j := 0; j < len(n)-1 ;j++  {
    
    
            if n[j].Votes < n[j+1].Votes {
    
    
                n[j],n[j+1] = n[j+1],n[j]
            }
        }
    }

    return n[:3]
}


func main() {
    
    

    CreateNode()
    fmt.Println(NodeArr)
    Vote()
    nodes := SortNodes()

    fmt.Println(nodes)


    //创建创世区块
    gene := GenesisBlock()

    lastBlock := gene
    for i:= 0; i< len(nodes) ;i++  {
    
    
        //打印新区块信息
        // var node *Node
         node := lastBlock.delegate
         fmt.Println("区块号:",lastBlock.Index,"节点名称:",node.Name,"节点投票数:",node.Votes)

        lastBlock =  nodes[i].GenerateNewBlock(lastBlock,[]byte(fmt.Sprintf("new block %d",i)))
    }

}

Output result: [{NODE 1 num 0} {NODE 2 num 0} {NODE 3 num 0} {NODE 4 num 0} {NODE 5 num 0} {NODE 6 num 0} {NODE 7 num 0} {
NODE 8 num 0} {NODE 9
num 0} {NODE 10 num 0}] [{NODE 1 num 3} {NODE 2 num 3} {NODE 3 num 3}] Block number: 0 Node name
: Genis Block Node vote count: 0 Block number: 1 Node name: NODE 1 num Number of node votes: 3
Block number: 2 Node name: NODE 2 num Number of node votes: 3

2.4 Practical Byzantine Fault Tolerance (PBFT)

Advantages: high speed, scalable.
Disadvantages: Typically used in private and permissioned networks.
Adopted by: Hyperledger Fabric, Stellar, Ripple, Dispatch
Explanation: The Byzantine Generals Problem is a classic problem in distributed computing. The problem is described as several Byzantine generals led their troops to surround a city. They must decide unanimously whether to launch a siege. If some generals decide to launch a siege without the participation of other generals, their efforts will end in failure. The generals are separated from each other by a certain distance and must rely on information transmission to communicate. Some cryptocurrency protocols use specific versions of BFT when reaching consensus, each version has its own advantages and disadvantages:
[1] Practical Byzantine Fault Tolerance (PBFT): The first proposed solution to this problem is called "Practical Byzantine Fault Tolerance" (PBFT) is currently adopted by Hyperledger Fabric. PBFT uses a small (less than 20, and will increase slightly later) preselected number of generals and therefore runs very efficiently. Its advantage is high transaction throughput and throughput, but its disadvantage is that it is centralized and used in permissioned networks.

From a certain perspective, PBFT is a bit like the gameplay of "Close Your Eyes After Dark Murdering Game".

[2] Federated Byzantine Agreement (FBA): Another solution to the Byzantine Generals Problem is FBA, which has been used by tokens such as Stellar and Ripple. The general idea of ​​FBA is that each Byzantine general is responsible for its own chain, and once the message arrives, the facts are established through sorting. In Ripple, generals (validators) are pre-selected by the Ripple Foundation. In Stellar, anyone can become a validator, and users need to choose which validator to trust.
Because FBA provides incredible throughput, low transaction overhead, and network scalability, I believe that the FBA-like formula algorithm is the best distributed consensus discovery algorithm currently proposed.
Technical principle:
PBFT is based on the Byzantine Generals Problem. Ensuring consistency is mainly divided into three stages: pre-prepare, prepare and commit. The process is shown in the figure below:

Among them, C is the requesting end, 0123 is the server, and 3 is the downed server. The specific steps are as follows:

1.Request: Requester C sends a request to any node, here is 0
2.Pre-Prepare: Server 0 broadcasts after receiving C's request, spreading to 123
3.Prepare: 123, record and repeat after receiving Broadcast, 1->023, 2->013, 3 cannot broadcast due to downtime
4.Commit: 0123 node is in the Prepare phase. If it receives more than a certain number of the same requests, it will enter the Commit phase and broadcast the Commit request;
5.Reply :0123 In the Commit phase, if the node receives more than a certain number of the same requests, it will give feedback to C;

For more principle details, please refer to "Lesson 13 Consensus Layer PBFT Consensus Algorithm"
)

GO demo code sample:

package main

import (
    "os"
    "fmt"
    "net/http"
    "io"
)

//声明节点信息,代表各个小国家
type nodeInfo struct {
    
    
    //标示
    id string
    //准备访问的方法
    path string
    //服务器做出的相应
    writer http.ResponseWriter

}

//存放四个国家的地址
var nodeTable = make(map[string]string)

//拜占庭在Fabric中的使用
func main() {
    
    

    //获取执行的参数
    userId :=os.Args[1]//获取执行的第一个参数
    fmt.Println(userId)

    //./main Apple

    //创建四个国家的地址
    nodeTable = map[string]string {
    
    
        "Apple":"localhost:1111",
        "MS":"localhost:1112",
        "Google":"localhost:1113",
        "IBM":"localhost:1114",
    }

    node:=nodeInfo{
    
    userId,nodeTable[userId],nil}
    fmt.Println(node)

    //http协议的回调函数
    //http://localhost:1111/req?warTime=8888
    http.HandleFunc("/req",node.request)
    http.HandleFunc("/prePrepare",node.prePrepare)
    http.HandleFunc("/prepare",node.prepare)
    http.HandleFunc("/commit",node.commit)

    //启动服务器
    if err:=http.ListenAndServe(node.path,nil);err!=nil {
    
    
        fmt.Print(err)
    }



}

//此函数是http访问时候req命令的请求回调函数
func (node *nodeInfo)request(writer http.ResponseWriter,request *http.Request){
    
    
    //设置允许解析参数
    request.ParseForm()
    //如果有参数值,则继续处理
    if (len(request.Form["warTime"])>0){
    
    
        node.writer = writer
        //激活主节点后,广播给其他节点,通过Apple向其他节点做广播
        node.broadcast(request.Form["warTime"][0],"/prePrepare")

    }


}


//由主节点向其他节点做广播
func (node *nodeInfo)broadcast(msg string ,path string ){
    
    
    //遍历所有的国家
    for nodeId,url:=range nodeTable {
    
    

        if nodeId == node.id {
    
    
            continue
        }
        //调用Get请求
        //http.Get("http://localhost:1112/prePrepare?warTime=8888&nodeId=Apple")
        http.Get("http://"+url+path+"?warTime="+msg+"&nodeId="+node.id)
    }

}

func (node *nodeInfo)prePrepare(writer http.ResponseWriter,request *http.Request) {
    
    
    request.ParseForm()
    //fmt.Println("hello world")
    //在做分发
    if(len(request.Form["warTime"])>0){
    
    
        //分发给其他三个人
        node.broadcast(request.Form["warTime"][0],"/prepare")
    }

}

func (node *nodeInfo)prepare(writer http.ResponseWriter,request *http.Request){
    
    

    request.ParseForm()
    //调用验证
    if len(request.Form["warTime"])>0{
    
    
        fmt.Println(request.Form["warTime"][0])
    }
    if len(request.Form["nodeId"])>0 {
    
    
        fmt.Println(request.Form["nodeId"][0])
    }

    node.authentication(request)
}


var authenticationsuccess = true
var authenticationMap = make(map[string]string)
//获得除了本节点外的其他节点数据
func (node *nodeInfo)authentication(request *http.Request) {
    
    

    //接收参数
    request.ParseForm()

    if authenticationsuccess!=false  {
    
    
        if len(request.Form["nodeId"])>0 {
    
    
            authenticationMap[request.Form["nodeId"][0]]="ok"
        }
    }

    if len(authenticationMap)>len(nodeTable)/3 {
    
    
        //则拜占庭原理实现,通过commit反馈给浏览器
        node.broadcast(request.Form["warTime"][0],"/commit")

    }
}


func (node *nodeInfo)commit(writer http.ResponseWriter,request *http.Request){
    
    

    //给浏览器反馈相应
    io.WriteString(node.writer,"ok")

}

How to run: Open 4 terminals, eg:

./pbft Apple
./pbft IBM
./pbft MS
./pbft Google

Then enter in the browser: http://localhost:1112/req?warTime=1234 Output result:

okokok

2.5 Distributed Consistency Protocol-RAFT Algorithm

Advantages:
The model is simpler than Paxos but provides equivalent security. Implementations are available in multiple languages.
Disadvantages: Typically used in private and permissioned networks.
Adopters: IPFS Private Cluster, Quorum.
Explanation:
Simplify the Byzantine Generals Problem based on a common work problem: assuming there are no rebels among the generals and the messenger's information is reliable but may be assassinated, how can the generals reach a unanimous decision?
There are many solutions to this simplified problem. The first proven consensus algorithm is Paxos, proposed by Leslie Lamport, the author of the Byzantine Generals Problem, in 1990. However, its paper is famous for being difficult to understand, so a professor at Stanford University In 2014, the new distributed protocol Raft was released. Compared with Paxos, Raft has basically the same operating efficiency, but is easier to understand and easier to use in system development.
We still use the example of a Byzantine general to help understand Raft.

假设将军中没有叛军,信使的信息可靠但有可能被暗杀的情况下,将军们如何达成一致性决定?

Raft's solution can probably be understood as first selecting a general among all generals, and all decisions will be made by the general. Election link: For example, there are three generals A, B, and C. Each general has a countdown timer with a random time. Once the countdown is over, the general will regard himself as a candidate for general, and then send a messenger to ask Can the other generals choose me as the general? Assume that the countdown of General A is now over, and he sends a messenger to deliver the election voting information to Generals B and C. If Generals B and C have not considered themselves as candidates (the countdown has not ended yet) and have not voted for others, They voted for General A, and when the messenger returned to General A, General A knew that he had received enough votes and became the general. After that, it is up to the general to decide whether to attack, and then send a messenger to notify the other two generals. If no reply is received after a period of time (the messenger may have been assassinated), then another messenger will be sent until the response is received. to reply.
Technical principle:
Raft requires the system to have at most one Leader at any time, and only Leader and Followers during normal operation. The Raft algorithm divides time into terms, and the beginning of each term is Leader election. After the Leader is successfully elected, the Leader will manage the entire cluster throughout the term. If the leader election fails, the term will end because there is no leader.

(1) The Raft node status is
mapped from the story of Byzantine generals to the distributed system. Each general is equivalent to a distributed network node. Each node has three states: Follower, Candidate, and Leader. The states are converted to each other. You can refer to the picture below:

There is a countdown timer (Election Timeout) on each node, and the time is randomly between 150ms and 300ms. There are several situations where Timeout will be reset:
(1) Receiving an election request
(2) Receiving the Leader's Heartbeat (will be discussed later)
During the running of Raft, there are two main activities:
(1) Selecting the Leader Election
(2) Log Replication

Technical principles
(1) Leader Election
1) Leader election under normal circumstances
Assume that there are 5 nodes as shown in the figure, and the initial status of the 5 nodes is Follower.

After the countdown of a node ends (Timeout), the status of this node changes to Candidate and the election starts. It sends election requests (RequestVote) to several other nodes.

The other four nodes all return successfully. The status of this node changes from Candidate to Leader, and after a short period of time, a Heartbeat is sent to all Followers to maintain the status of all nodes. After the Follower receives the Heartbeat from the Leader Reset Timeout.

This is the simplest leader election situation. As long as more than half of the nodes vote in support, Candidate will be elected as Leader. In the case of 5 nodes, 3 nodes (including Candidate itself) will vote in support.

(2) 2.2 Leader selection in case of Leader failure

There is already a Leader at the beginning, and all nodes are running normally.

If the Leader fails and hangs up, the other four Followers will re-elect the leader.

The leader selection process for 4 nodes is similar to that for 5 nodes. After a new leader is selected, the original leader recovers and rejoins. How to deal with this situation? In Raft, the election rounds are recorded. The rejoining Leader was elected in the first round of elections (Term 1), and the current Leader is Term 2. All original Leaders will consciously downgrade to Followers.

(3) 2.3 Choosing the candidate in the case of multiple candidates

Assume that there are 4 nodes at the beginning, and they are all Followers.

Two Followers timed out at the same time, and both became Candidates to start the election, sending voting requests to one Follower respectively.

The two Followers returned ok respectively. At this time, both Candidates only have 2 votes, and it takes 3 votes to be selected as Leader.

The two Candidates will respectively send voting requests to the other Follower who has not yet voted for themselves.

However, because Followers had already voted in this round of elections, their requests were rejected. So in Term 2 no Leader is selected.

At this time, the status of the two nodes is Candidate and the status of two is Follower, but their countdown timers are still running. The node that Timeout first will initiate a new round of Term 3 voting.

The two Followers have not voted in Term 3, so they return OK. At this time, the Candidate has a total of three votes and is elected as the Leader.

If the Leader Heartbeat time is later than another Candidate timeout, the other Candidate will still send an election request.

The two Followers have already finished voting and have rejected the Candidate's voting request.

The Leader performs Heartbeat. After receiving the Candidate, the status automatically changes to Follower to complete the leader election.

Implementation code reference: https://github.com/goraft/raft or
https://github.com/happyer/distributed-computing/tree/master/src/raft

2.6 Directed Acyclic Graphs (DAG, Directed Acyclic Graphs)

Advantages:
Due to the nonlinear structure of DAG, it is highly scalable, fast, energy-saving, and achieves finality immediately.
Disadvantages: Smart contracts can only be implemented using Oracle.
Adopters: Iota, HashGraph, Byteball, RaiBlocks/Nano.
Explanation: DAG is a more general form of blockchain. Due to its unique structure, DAG inherently supports high scalability and is therefore widely used.

Fundamentally, any blockchain system has a linear structure, as blocks are added to the chain sequentially. This makes linear blockchains inherently very slow compared to adding blocks to the chain in parallel. But for DAG, each block and transaction only needs a few previous blocks to be confirmed and can be added to the blocks and transactions in parallel. This means that DAG is highly scalable in nature.

There are many variations of DAG, depending on:
· How to choose the algorithm for early block verification, also known as the "Tip selection algorithm".
· The order in which transactions are completed.
· How to reach completion state.

Listed below are some widely used DAG projects.

1 Tangle(IOTA)
image

Explanation: Tangle is a DAG consensus algorithm used by IOTA. In order to send an IOTA transaction, the user needs to verify the first two transactions received. This two-to-one, forward-paying consensus enhances the effectiveness of transactions as more transactions are added to the Tangle. Since consensus is determined by transactions, in theory, if someone can generate a third of the transactions, then he can convince the rest of the network that his invalid transactions become valid. Once the transaction volume is large enough, making it difficult for an individual to create one-third of the transaction volume, IOTA will "double" all transactions in the network on a central node called "The Coordinator" -checking). According to ITOA, the coordinator's job is similar to training wheels. Once the Tangle reaches a certain size, the coordinator is removed from it.

2 Hashgraph
explanation: Hashgraph is a gossip protocol consensus developed by Leemon Baird. Nodes randomly share their known transactions with other nodes, and eventually all transactions are propagated (Gossip around) to all nodes using the gossip protocol. Hashgraph is a great choice for private networks. But we will not see it implemented in a public network like Ethereum, or randomly propagate transactions through the Gossip protocol.

3 Holochain
explanation: Holochain is very similar to HashGraph, but different from Hashgraph. It provides a data structure that can be used to build decentralized applications. Users can have their own chain and add data including financial transactions to it. Chains can be merged, split, and interacted in complex ways. Data is stored in a decentralized manner (similar to Bittorrent). Data has a hash value, a mathematical fingerprint that corresponds to the data. If someone intends to tamper with the data, then we will notice that there is a mismatch between the data and the hash value, and the data can be rejected as invalid. Digital signatures guarantee the authorship of the data. Holochain can be thought of as "Bittorrent+git+digital signature".

4 Block-Nano

Explanation: Nano (formerly known as Raiblocks) operates in a way that is wrapped around the blockchain, which is called "Block-lattice". In the Block-lattice structure, each user (address) has its own chain, which is writable only by the user itself, and each user has a copy of all chains.

Each transaction can be broken down into a sending block on the sender's chain, and a receiving block on the receiver's chain. Block-lattice may seem too simple to work, but it's already working. The unique structure of Block-lattice is indeed unable to resist some unique attack vectors, such as Penny-spend attacks. In this attack, the attacker sends a negligible amount of money to a large number of empty wallets, causing the number of chains that must be tracked to balloon.

5 SPECTRE

Explanation: SPECTER, which stands for "Serialization of Proof-of-work Events, Confirming Transactions via Recursive Elections", is a proposed Bitcoin extension solution. It utilizes a combination of PoW and DAG to achieve scalable consensus. In SPECTER, a mined block points to multiple parent nodes instead of just a single node, which allows the network to process multiple blocks per second. And mining blocks that point to some parent block will support the validity of the block. Compared with PoW's "longest chain wins" principle, the principle used by SPECTER can be described as "the block with the most child nodes wins." SPECTER has not yet been tested in real-life operations, so there may be some new attack vectors. But I think SPECTER has the potential to be a potentially good way to fix Bitcoin's problems.

6 ByteBall

Explanation: ByteBall uses DAG to establish a partial order relationship between transactions, and also adds a "main chain" (MC, Main Chain) to the DAG.

The “main chain” shown in bold in the figure DAG

MC allows the definition of total order relationships between transactions, that is, transactions that join MC earlier (directly or indirectly) must appear earlier in the total order. If there is a "double spend" problem, the transaction version that appears earlier in the total sequence will be considered valid, and all other transactions will be considered invalid.

Depending on the transaction's position in the graph, MC can be deterministically defined. See the white paper for details. As a general rule, MC tends to accept transactions given by well-known users. Such users are called "witnesses". The witness list is defined by the user himself, as every transaction posted by the user is included in the list. Then, the MC advances along the intra-DAG path. Advancing principles include:

· The witness lists for adjacent transactions on MC are either identical or have only one mutation.

· Compared with other chains, MC has the largest number of transactions certified by witnesses.

ByteBall is also the first platform to include Oracle in the system. Oracle is required to add smart contract functionality in the DAG.
2.7 Proof of Capacity (PoC, Proof of Capacity)

Advantages:
It is similar to PoW, except that space is used instead of calculation. Therefore more environmentally friendly.

Can be used for malware detection. By determining whether the processor's L1 cache is empty (ie, has enough space to compute the PoSpace procedure without a cache miss), or contains a routine that refuses to be evicted.

Can be used for anti-spam measures and to protect against Denial of Service (DoS) attacks.

Disadvantages: There may be problems with the incentive system.

Users: Butcoin, Chia, SpaceMint.

Type: collaborative consensus.

Explanation: PoSpace, also known as PoC, shows that someone has a legitimate interest in a service (such as sending mail) by allocating a certain amount of memory or disk space to solve a challenge provided by the service provider. The concept was formally defined by Dziembowski et al. in 2015. Although the name of Ateniese et al.'s paper is also "Proof-of-space", it is actually a PoW protocol that uses MHF (Memory Hard Function, a hash algorithm whose computational cost depends on memory).

PoSpace is very similar to PoW, except that storage is used to replace the calculation in Pow. PoSpace is related to MHF and Proof of Retrievability (PoR), but is also very different.

PoSpace is a small piece of data sent by the Prover to the Verifier, which confirms that the Prover has reserved a certain amount of space. For practical reasons, the verification process needs to be as efficient as possible, that is, consuming as little space and time as possible. For fairness reasons, if a validator does not reserve the declared amount of space, it should have difficulty verifying. One implementation of PoSpace is by using a graph that is difficult to Pebbling. The verifier requests the prover to construct a token for a "non-Pebbling graph". The prover submits the token, and the verifier in turn requests the prover to open multiple random positions in the submission.

Due to the universal nature of storage, and the lower energy consumption required for storage, PoSpace is considered a fairer and greener alternative.
2.8 Delayed Proof-of-Work (dPoW, Delayed Proof-of-Work) ,

Advantages:
energy saving, increased security, the ability to indirectly provide Bitcoin (or any other security chain) and add value to other blockchains without paying the price of Bitcoin (or any other security chain) transactions.
Disadvantages:
This consensus algorithm can only be used in blockchains using PoW or PoS.
In Notaries ActIve mode, the hashrate of different nodes (notaries or normal nodes) must be calibrated, otherwise the difference between the hashrates will explode (explained in detail below).
Adopter: Komodo
Type: Collaborative consensus
Explanation: dPoW is a hybrid consensus method that allows one blockchain to take advantage of the security provided by the hashing power of a second blockchain. This mechanism is implemented through a set of Notary Nodes. The notary node implements adding data from the first blockchain to the second blockchain. In turn, the second blockchain requests a compromise between the two blockchains, weakening the security of the first blockchain. Komodo is the first blockchain to use this consensus method, and it is attached to the Bitcoin blockchain.

Blockchains using dPoW can also work using PoW or PoS consensus methods and can be attached to any blockchain that adopts PoW. But for blockchains provided with security by dPoW, Bitcoin currently provides the highest security level hash rate. The image below shows a single record of the main blockchain and the PoW blockchain to which it is attached.

There are two types of nodes in the dPoW system: notary nodes and normal nodes. The 64 notary nodes are elected by the stakeholders of the dPoW blockchain and can add notarized blocks from the dPoW blockchain to the attached PoW blockchain. Once a block is added, the hash of the block is added to a Bitcoin transaction signed by 33 notary nodes and creates a dPow block record that hashes to the Bitcoin blockchain. The record has been notarized by a majority of the notary nodes in the network.

In order to avoid mining wars between notary nodes and thus reduce the efficiency of the network, Komodo designed a mining method using a polling mechanism. This method has two modes of operation. In the "No Notary" mode, all network nodes are supported to participate in mining, which is similar to the traditional PoW consensus mechanism. In the "Notaries ActIve" mode, network notaries mine using a significantly reduced network difficulty rate. In the "Notary Activation" mode, each notary is allowed to mine a block using its current difficulty, while other notary nodes must mine at 10 times the difficulty, and all normal nodes use 100 times the difficulty of the notary node to mine.

But this can cause some problems. I mentioned in a conversation with the founder of Komodo that this would result in a high hash rate difference between notary miners and normal miners:

Screenshot of the communication between the author of this article and the founder of Komodo on inconsistency issues

The dPoW system is designed to allow the blockchain to continue operating without notary nodes. In this case, the dPoW blockchain can continue to operate based on the initial consensus method, but will no longer have the security added by the attached blockchain.

All blockchains using dPoW increase security while reducing energy consumption. For example, Komodo uses the Equihash hashing algorithm to prevent ASIC mining. Its notary nodes rely on a round-robin mining method, and the reward mechanism takes into account the possibility of reducing competition among nodes. These nodes will cause excessive energy consumption or computing power.

In addition, by providing Bitcoin security indirectly, dPoW blockchains like Komodo can add value to other blockchains without paying any Bitcoin transaction costs. Komodo has since attached to Bitcoin, and a third blockchain using dPoW could attach itself to Komodo. Using this approach, the dPoW blockchain does not have to be directly attached to the Bitcoin blockchain to benefit from Bitcoin's high hash rate.

Finally, the function of separating the notary node from the normal node ensures that the initial consensus mechanism continues to operate when the notary node fails. This mutual independence establishes a reward mechanism that allows other networks to support the continued maintenance of the Bitcoin network without relying on the direct functionality of the Bitcoin network.
2.9 Proof of Authority (PoA, Proof-of-Authority)

Advantages: energy saving, fast.
Disadvantages: Slightly centralized. Although available for public blockchains, it is typically used for private and permissioned blockchains.

Users: POA.Network, Ethereum Kovan testnet, VeChain.
Type: collaborative consensus.

Explanation: Networks, transactions and blocks based on PoA are certified by some recognized accounts. These recognized accounts are called "Validators". The software run by the validator allows the validator to place transactions into blocks. The process is automatic and does not require validators to constantly monitor the computer, but does require maintaining the computer (authoritative node) uncompised.

Validators must meet the following three conditions:

  1. Their identity must be formally verified on-chain, and the information can be cross-verified in the publicly available domain.
  2. Qualification must be difficult to obtain so that the resulting right to verify blocks is valuable (e.g., potential validators need to obtain a notarized certificate).
  3. The checks and procedures for establishing authority must be completely uniform.

With PoA, each individual has the right to become a validator, so there is an incentive to maintain a validator position once acquired. By attaching a reputation to an identity, validators can be encouraged to maintain the transaction process. Because validators do not want to gain a negative reputation, which would cause them to lose their hard-earned validator status.
2.10 Proof of Weight (PoWeight, Proof-of-Weight)

Pros: Energy efficient, highly customizable, and scalable
Cons: May be difficult to incentivize,
Adopters: Algorand.
Type: Competing consensus.
Explanation: Proof of weight (PoWeight) is a very broad type of consensus algorithm, which is based on the Algorand consensus model. The basic idea is that in PoS, the percentage of tokens in the network owned by a user represents the probability of that user "discovering" the next block. Some other relative weighting values ​​are also used in the PoWeight system, including Proof of Reputation (PoR, Proof of Reputation) and Proof of Space.
2.11. Proof of Reputation (PoR, Proof of Reputation)

Pros: Great for private and permissioned blockchains.
Disadvantages: Can only be used on private blockchains and permissioned blockchains.
Adopter: GoChain.
Type: collaborative consensus.
Explanation: PoR is similar to PoA. The following description is given in the GoChain documentation:
The PoR consensus model relies on the reputation of participants in keeping the network secure. Participants (block signers) must have a sufficiently important reputation. If they try to cheat the system, they will face severe financial and reputational consequences. This is a relative concept, and if they were caught trying to deceive, almost any business would be severely affected. The larger the business, the more it will usually lose. In this way, larger businesses are more likely to be selected than fewer businesses (i.e. smaller businesses).

Once a business has proven their reputation and passed verification, they must participate in the authoritative node network through voting. At this time, PoR operates the same as the PoA network, that is, only authoritative nodes can sign and verify blocks.
2.12. Proof of Elapsed Time (PoET, Proof of Elapsed Time)

Advantages:
Low cost of participation. More people can easily join, thereby achieving decentralization.
It is easier for all participants to verify that the leader was legitimately elected.
The cost of controlling the leader selection process is proportional to the value gained from it.
Disadvantages:
Although PoET is cheap, it requires the use of specific hardware. Therefore it will not be adopted on a large scale.
Not applicable to public blockchains.

Adopted by: HyperLedger Sawtooth

Type: Competing Consensus

Explanation: The PoET consensus mechanism algorithm is usually used in permissioned blockchain networks, which determines the mining rights of those who obtain blocks in the network. Permissioned blockchain networks require any prospective participants to verify their identity before joining. According to the principles of a fair lottery system, each node has an equal possibility of becoming the winner. The PoET mechanism gives a large number of possible network participants an equal chance of winning.

PoET works as follows: every participating node in the network must wait for a randomly selected period, and the first node to complete the set waiting time will receive a new block. Each node in the blockchain network will generate a random waiting time and sleep for a set time. The node that wakes up first, i.e. the node with the shortest waiting time, wakes up and submits a new block to the blockchain, then broadcasts the necessary information to the entire peer-to-peer network. The same process will be repeated to discover the next block.

In the PoET network consensus mechanism, two important factors need to be ensured. First, participating nodes will naturally choose a random time in nature, rather than one participant deliberately choosing a shorter time in order to win. Second, the winner did complete the waiting time.

The PoET concept was proposed by the famous chip manufacturing giant Intel in early 2016. Intel has implemented a high-tech tool available to solve the computational problem of "random leader election".

This inherent mechanism allows applications to execute trusted code in a protected environment. It ensures that the two requirements set out above are met, namely that the waiting time of all participating nodes is randomly selected, and that the winning participant actually completes the waiting time.

This mechanism for running trusted code in a secure environment also takes into account other network needs. It ensures that the trusted code is indeed running in a secure environment and cannot be changed by other external parties. It also ensures that results can be verified by external participants and entities, thereby increasing the transparency of network consensus.

PoET implements the consensus process by controlling the cost, which is still proportional to the value obtained from the process. This is a critical requirement to ensure the continued prosperity of the cryptocurrency economy.
2.13 Historical proof (PoHistory, Proof of History)

Adopted by: Solana

Explanation: The basic idea is not to trust the timestamp in the transaction, but to prove that the transaction occurred at a certain moment before or after an event.

If we take a photo of the cover of an issue of The New York Times, we create proof that we took the photo after the newspaper was published, or perhaps that we influenced the New York Times in some way. Normal release. We can use PoHistory to create a historical record that proves that an event occurred after a specific time.

A comprehensive and detailed explanation of the blockchain consensus algorithm

PoHistory is a high-frequency verifiable delay function (VDF, Verifiable Delay Function). VDF evaluation requires a specific number of sequential steps to be completed and then produces a unique output. This output can be efficiently and publicly verified.

One specific implementation of VDF uses a Pre-image Resistant Hash that is continuously run on it, where the output generated by the previous iteration is used as the input of the next iteration. The count and current output form a periodic record.

If the SHA256 hash function is used, it is impossible to parallelize the process without using a brute force attack of 2128 cores.

So we can confirm that each counter does take a certain amount of time during its generation. Furthermore, the order recorded by each counter is consistent with the real-time situation.

2.14 Single Point Consensus (SOLO)

User: Frabric
explains: Solo consensus mode means that the Order node is a single-node communication mode, and the messages sent by the Peer node are sorted and blocks generated by an Order node.
Since the sorting service has only one Order serving all nodes (Peers), it does not have high availability and scalability, and is not suitable for use in production environments. It can be used in development and testing environments.
Technical principle:
The Solo consensus working sequence is shown in the figure below. The scope described in the figure is the entire process from the SDK initiating the transaction to the transaction landing.

When the Order node container starts, start the Solo sorting service, start monitoring the messages sent by the SDK, and call the Solo service for data block processing after receiving the messages. Among them, the Solo mode calling process description:
(1) SDK connects to Peer through gRPC and sends transaction information Tx;
(2) After Peer calls the contract, it will return the result and then reply to SDK;
(3) SDK connects to Order through gRPC, and (2) ) sdkPeerReply is sent to Order to execute the Solo consensus service:
A. Receive messages
B. Message enqueuing
C. Message sorting
D. Message cutting (divided according to time or number of transactions)
E. Generate blocks
F. Write blocks File
G. Notify Peers

First, order sets the consensus mechanism to "solo". Multi-machine multi-node deployment requires at least two servers, one Order sorting service node and one peer node. Each additional server can be added as a new peer node. .
2.15 Proof of Activity (PoActivity, Proof Of Activity)

User: Decred

Explanation: To avoid hyperinflation (which occurs when large amounts of money flood the system), only 21 million Bitcoins will be created. This means that, at some point, the Bitcoin block reward subsidy will end and Bitcoin miners will only be able to collect transaction fees.

Some speculate that this could lead to security issues caused by a "tragedy of the commons," where people act in their own self-interest and undermine systems. Therefore, PoActivity has been proposed as an alternative incentive structure to Bitcoin. PoActivity is a hybrid approach that combines PoW and PoS.

In PoActivity, mining begins with traditional PoW, with miners competing to solve cryptographic puzzles. Depending on the implementation, mined blocks do not contain any transactions, they are more like templates. Therefore, the winning block will only contain header information, and the miner’s reward address.

At this point, the system will switch to PoS. PoActivity selects a group of random validators to sign the new block based on the header information. The more tokens in the system a validator owns, the more likely that validator is to be selected. Once all validators have signed, the template becomes a complete block.

If some of the selected validators are unavailable when the block is completed, then the next winning block is selected and a new set of validators are selected, and so on until the block receives the correct number of validators. sign. The fee is split between the miners and the validators who sign the blocks.

Criticisms of PoActivity include the high energy consumption of mining blocks (like PoW) and the inability to prevent validators from double-signing (like PoS).

3, Reference

(1) Distributed consensus algorithm column - a collection of various consensus algorithms
https://recomm.cnblogs.com/blogpost/11284374?page=1

(2) A comprehensive and detailed explanation of the blockchain consensus algorithm http://www.elecfans.com/blockchain/843819.html

(3) Principle and implementation of consensus algorithm DPOS https://www.meiwen.com.cn/subject/hxqzyftx.html

(4) Simple implementation of Byzantine PBFT https://www.meiwen.com.cn/subject/prvjuftx.html

(5) PBFT algorithm https://www.meiwen.com.cn/subject/owzvyxtx.html

Guess you like

Origin blog.csdn.net/leaning_java/article/details/126485023