Lightning Network (on)|How to break through the ternary impossible: Re-implement the principle of lightning network technology with Solidity language

The Lightning Network was presented in a white paper co-authored by Joseph Poon and Thaddeus Dryja in 2015. It has generated a lot of repercussions in the Bitcoin community. It is widely regarded as the second largest in many papers and white papers on Bitcoin, and its value is second only to Nakamoto's creation paper.

Because lightning networks rely on isolation verification, they remain in the concept and internal development phases. After entering the normal development track from the bitcoin isolation verification in 2017, Lightning Labs developed and launched the first test version in March 2018, after which ACINQ and Blockstream also launched different implementations.  

According to the 1ml data of the statistical website, Lightning Network currently has 8,204 nodes, 37,901 payment channels, and the total payment channel is 1,021.37 BTC (about 5.34 million US dollars) . Explain that the lightning network has achieved significant growth in the past year.

The vision of Lightning Networks is to address the expansion of the Bitcoin network.

As we all know, the original intention of Bitcoin is to realize an end-to-end electronic cash system, providing the world with a trusted, 7×24-hour electronic payment network. But Bitcoin's performance is far from satisfactory. Based on an average of 300 bytes per transaction, the average throughput of Bitcoin is 5.6 TPS. However, Visa's peak throughput can reach 47,000 TPS. If this throughput is benchmarked, the block size of Bitcoin will be expanded to about 8GB, and 400 TB of block data will be added each year. This is obviously unrealistic.

In addition to the lightning network , the blockchain community has also proposed a number of expansion solutions, such as large blocks, DPoS, DAG, fragmentation, sidechain cross-chain and so on . These solutions are optimized based on Bitcoin's distributed ledger technology, such as adjusting configuration parameters, optimizing data structures, modifying consensus algorithms, accounting partition processing, optimizing network resource management, and so on. But at present, the effect is not ideal. After paying a high price (increasing storage capacity, increasing network traffic, increasing logic complexity, weakening decentralization), it only gets a very limited performance improvement, compared with Visa. There are still several orders of magnitude difference.

Only the lightning network has a wide open brain and a new path.

Due to the complexity of Bitcoin smart contracts, which is not conducive to understanding the technical principles of Lightning Networks, the OK Research team re-implemented the lightning network with the Solidity language and deeply understood the technical implementation of Lightning Networks. The basic processes and principles of the lightning network are now abstracted out so that everyone can quickly understand.

The key technical principle of 01 lightning network

The core solution of the lightning network is to create a temporary chain payment channel, so that the multiple transactions of the payee and the party are updated under the chain, and only the final payment result is recorded in the chain, so that a large number of transactions do not have to wait. Blocks on the chain update consensus, which increases payment efficiency. How to achieve the transaction without the chain can also be final, to prevent tampering, is the core content of the lightning network program.

1. Lightning network solutions are built on three important concepts: virtual banking , mutual commitment, and payment channels .

1) Virtual Bank

The smart contract on the chain simulates the banking institution as the debtor of Alice and Bob. Virtual banking has the following characteristics:

➤ Mini: There are only two accounts: Alice/Bob

➤ No trust: open, transparent, non-tamperable, unforgeable, irrevocable

➤ User autonomy: Alice and Bob manage bank assets together

➤Double signature: asset redistribution must be signed by both Alice and Bob

2) Joint commitment

Both parties reached an agreement on the debt adjustment plan and signed the two sides. This message is not immediately broadcast to the chain, but is stored locally by both parties, called a common commitment.

The common commitment is the expression of the true will of both parties, and it is the commitment of each other to the asset allocation plan, which has the following characteristics:


Don't change

➤ can cover

3) Payment channel

The payment parties use the virtual bank to escrow the assets of both parties and re-liquidate the balance of the deposits through mutual commitment to achieve the effect of value transfer. This payment instrument is called the payment channel.

2. The commitment scheme is divided into direct connection and non-direct connection of the payment channel: RSMC (Recoverable Sequence Maturity Contract) commitment scheme, HTLC (Hash Time Lock Contract) commitment scheme

1) RSMC Commitment Plan

Participants include the offensive party (actively submitting a commitment plan to the virtual bank, allocating assets) and the defending party (passively accepting the asset allocation plan submitted by the offensive party).

The RSMC Commitment Program prevents evil motives through a good faith margin mechanism.

When the offensive party initiates a liquidation application, the defender's funds, such as $100, are immediately cashed and returned to the defender's account. The attacker's asset of 100 US dollars will be locked as a security margin, and the lock time is the freeze_time parameter set by the smart contract (freeze_time refers to the length of the offensive asset lock, which can be negotiated by both parties).

If the defending party finds that the current attacking party's request for the assigned plan has been revoked, the defending party can remove the unrestricted lock during the lock-up period and take the security margin of the offender's mortgage as the fine. On the contrary, after the lock-up period, the offensive party will be able to retrieve their own integrity deposit.

RSMC is committed to two copies of each other and is a dual commitment. The offensive party and the defender each hold one copy, and for virtual banks, they are equally effective. A dual commitment can prevent a failure of one party from causing the payment channel to lock up, and either party has the initiative to honor the commitment plan.

相同 The same points of the two dual commitments: number, asset allocation plan, asset freeze time.

不同 The difference between the two dual commitments: the offensive and defensive positions are reversed, the signature position is reversed, and the offense is different (integrity deposit, unlock lock).

The RSMC Commitment Plan Clearing Process can be divided into three parts:

Commitment plan construction process:

a) Alice and Bob establish the #1 RSMC Commitment Plan and deposit them into 100 BTCs.

The RSMC solution change process, the payment process:

b) Alice and Bob create a new credit relationship, re-establish the #2 RSMC commitment scheme and sign and exchange the assets, and then distribute the assets twice (note that both parties get the signature of the other party, but they also sign It can take effect immediately).

c) Both parties disclose #1 RSMC's commitment plan to revoke the private key of the lock, while the #1 RSMC commitment scheme is invalid.

The RSMC solution can be continuously replaced, and the commitment number is increased by one after each replacement.

RSMC scheme clearing, channel closure process (assuming the latest commitment number is N):

d) Alice signs the #N RSMC Commitment Plan (a commitment scheme that has been signed by Bob) and initiates a clearing application to the Virtual Bank.

e) Alice acts as an offensive party, her own 50BTC is frozen as a security deposit, and Bob's 150BTC is immediately released. During the margin freeze, Bob finds that the promised scheme that was requested to be assigned fails, for example, the invalid #1 RSMC commitment scheme. At this time, Bob can unlock the unlock lock at any time through the previously disclosed private key, and take away the integrity guarantee of the offender's mortgage. Gold as a fine.

f) If the commitment plan does not expire, Alice may receive the deposit after the freeze period.

As mentioned above, RSMC can basically meet the basic clearing requirements, but it also has obvious limitations. That is, both parties who settle through the RSMC scheme must establish a direct payment channel to pay. Based on this pain point, the HTLC (Hash Time Lock Contract) commitment plan was born. The HTLC can form a payment path by connecting a plurality of end-to-end payment channels in series, and supports both the first and last parties to complete the payment through the payment path, that is, the payment channel without the direct connection can also be paid.

2) HTLC Commitment Plan: Guarantee the atomicity of two adjacent payments on the payment path

The HTLC promises two new elements: time locks and hash locks.

➤ ExpireTime: The appointment is valid within a certain time T, and the timeout promises that the scheme is invalid.

➤ HashLock: Book a number H, give the slang R, so that Hash( R ) = H, the promise is valid; otherwise it fails.

Typically, the HTLC scheme includes the RSMC scheme in which it acts as a bridge between two long-term effective RSMC schemes. If the time lock and hash lock match, a new RSMC commitment scheme can be established, otherwise it will be returned to the old RSMC commitment scheme.

HTLC promises the payment process:

From left to right, the commitment plan is established in the forward direction; from right to left, the lingo R is transmitted backward, and the payment is completed.

1. Carol generates the slang R and calculates H = hash(R), which are sent to Alice;

2. Establish an HTLC commitment scheme between Alice and Bob. Expire Time can be set to 2T, and Alice sends H to Bob.

3. Establish an HTLC commitment between Bob and Carol. ExpireTime can be set to T (or other, the duration is shorter than 2T). Bob sends H to Carol;

4. Carol provides R corresponding to H to Bob, Bob checks. If there is no timeout and the hash lock matches, the long-term effective RSMC commitment scheme is established according to the HTLC allocation scheme, and the temporary HTLC commitment scheme is cancelled. At this time, the HTLC commitment scheme completes its own bridge role. If the R provided by Carol does not match or fails to provide the R value within the T duration, the HTLC commitment scheme is invalidated and returned to the previous RSMC commitment scheme.

5. Bob passes Carol to his own R and passes it to Alice, who checks it. Followed by Carol and Bob above.

Among the three, Alice and Carol are the two parties that ultimately trade, and Bob is in the role of market maker, playing the role of establishing payment channels for Alice and Carol. In essence, a payment relationship can be established between any party that establishes a payment channel with Bob. The commitment between Bob and Alice and Carol can be set to be non-equivalent. For example, Bob pays Carol $9.9, but then charges Alice $10, which is $106.

3. The main risks to be addressed in the two commitment schemes: the risk of cheating by the counterparty and the non-atomic nature of the payment channel.

1) Opponent risk in the channel: What if one party does not cooperate?

For the RSMC scheme, from the #N-1 to #N commitment scheme, the payer has the benefit of not canceling the #N-1, and requires external payment scenario constraints to prompt it to open the lock.

For the HTLC scheme, from the #N-1 to #N commitment scheme, the receiver only has a public cryptic language (equivalent to canceling the #N-1 scheme) to get the payment amount; and if the payer does not revoke #N-1 The receiver can cash the #N-1 plan directly to the virtual bank. Therefore, HTLC constructs a balanced binary game rule, so that rational participants do not arbitrarily cheat.

2) Opponent risk across payment channels: Adjacent channel payments are atomic

First, along the payment path, the HTLC commitment scheme is established in turn from the sender to the receiver; then, in the reverse direction, the sender is transmitted from the receiver to the receiver. So be sure to complete the right payment first, then complete the left payment.

For any intermediate node, the payment is completed to the node on the right, meaning that the cryptic R is obtained within the specified time. The time lock on the left side is longer than the right side, so the intermediate node must be able to obtain equal compensation from the right node. That is to say, the interests of market makers come from the party with a shorter lock-up time. Conversely, if the node on the right does not complete the payment, then it cannot know the cipher R. So the payment on the left side can't be completed, which means that the connected channel payment is atomic.

On the whole, the trust mechanism is based on the autonomy of both parties. In the decision-making stage, the defending party signs first and then signs the offensive party. Therefore, the defending party has the right of first instance and the attacking party has the right to review. In the execution stage, the attacking party has the right to submit the initiative, the virtual bank has the right to execute, and the defending party has the The right to review within a certain period of time.

02 The fundamental crux of 'three yuan impossible' and the key breakthrough point of ' Lightning Network '

Bitcoin is a peer-to-peer electronic cash payment network. The key breakthrough is that electronic payment has the characteristics of “cash payment”, that is, “transaction is settlement” – the transfer of value symbol represents value transfer, information of funds The flow transfer and the transfer of creditor's rights and debts are completed simultaneously. The reason why electronic payment is difficult to achieve this synchronization is fundamentally because the electronic age indicates that the “digital” of funds is reproducible, leading to two fundamental problems: the issue of confirmation of rights and the problem of double flowers .

For the problem of determining the right, Bitcoin is solved by means of signature, that is, who owns the private key has the right to control the bitcoin.

For the double-flower problem, the following figure is an example. When Bob accepts Alice's transfer, it needs to confirm that Alice has not transferred the same amount of money to anyone. This requires traversing the full amount of books, preventing double-flowers from being essentially a borderless non-existence. Prove the problem.

Nakamoto wrote in "Bitcoin: A Peer-to-Peer Electronic Cash System":

Weneed a way for the payee to know that the previous owners did not sign anyearlier transactions. For our purposes, the earliest transaction is the onethat counts, so we don't care about later attempts to double-spend. The onlyway to confirm the absence Of a transaction is to be aware of all transactions.

The only solution to the double-flower problem is to obtain all transaction history records. On this basis, Nakamoto has proposed a distributed global ledger solution. But the cost of distributed ledgers is very high.

➤ Storage: Each verification node must maintain a full copy of the ledger.

➤ Verification: Every verification node has to verify all transactions.

➤ Communication: Each verification node must communicate with other nodes.

➤ Consensus: Every verification node must provide power for consensus.

Moreover, the storage, calculation, and communication complexity required for each transaction to be confirmed is proportional to the number N of verification nodes. In this way, the longer the time is reached in the more dispersed nodes, the longer it takes, the decentralization, security and transaction performance are difficult to balance, which is the “three-dimensional impossible” of the blockchain expansion that we often say.

Over the past few years, blockchain technology communities have emerged with new expansion solutions, such as large blocks, new data structures (DAGs), new formula algorithms (DPOS, PBFT), and fragmentation and sidechain cross-chain technologies. Wait. Among them, the DPOS and PBFT consensus algorithms are typically sacrificed to a certain degree of “decentralization”, which narrows the scope of the consensus nodes participating in the verification transaction.

The current hot segmentation technology and sidechain cross-chain technology are further based on this, although the same is to allow transaction verification to be carried out within a smaller node, avoiding inefficient global consensus, but the verification node begins to have The concept of "group" is to avoid having a small number of fixed nodes complete the transaction verification, resulting in the risk of manipulation cheating. But so far, the fragmentation technology is still in the early stage. How to overcome the "randomness" and "balance" and "dependency" of the group still needs further exploration and argumentation. That is to say, from the practical level, there has not been a chain expansion plan to achieve a breakthrough in the "three yuan impossible" , only the "lightning network" such a chain expansion program is unique!

The fundamental reason is that the lightning network jumped out of the concept of “point-to-point cash payment” and introduced a “debt settlement” mechanism similar to bank transfer . That is, A to B transfers not the ownership of “cash” but the “virtual” Bank's claims.

In the solution of the double flower problem, "Bob needs to confirm to as many people as possible that Alice has not transferred money to anyone" and changed to "Bob only needs to confirm the account balance to the virtual bank". It can be a borderless one. The existence proves that the problem is greatly simplified. However, unlike traditional banks, the “virtual bank” in the lightning network does not involve the “credit center” category, but through the intelligent contract technology to ensure that the virtual bank will honestly perform the obligation of debt clearing.

In essence, Lightning Networks has completed the act of securing and preventing double-flowering in countless groups by creating a chain of payment channels, greatly reducing the number of transactions that require a global consensus , and because there is no group between the groups. Strong dependencies reduce local security threats to overall security.

03 The main technical advantages of Lightning Network

The technical advantages of Lightning Network mainly include the following five items:

➤ Low transaction fee

No need for miners to participate, just pay channel rent for the intermediate node

实时 Real-time confirmation

A few nodes participate in the payment, and the transaction time ranges from a few hundred milliseconds to a few seconds.

High concurrency

Payment channel cap = Bitcoin TPS x 3600 x 24 x Average lifetime of the payment channel / 4 = 3,952,800

Maximum number of concurrency = upper limit of payment channel / number of channels per payment = 658,800

* The average lifecycle of the payment channel is:; the number of channels occupied by each payment is set to 6 according to the six-dimensional theory.

➤ Small data storage

Most of the data is stored under the chain, and there is little pressure on the storage on the chain.


Transaction data is not on the chain and will not reveal privacy

More on "Why is the debt clearing model more efficient?" and "What are the current flaws and new technical solutions for Lightning Networks?" we will expand on subsequent articles.

Source: OK Research