Home  >  Article  >  Starting from Bitcoin application programming, ten thousand words explain the programmability of CKB in detail

Starting from Bitcoin application programming, ten thousand words explain the programmability of CKB in detail

PHPz
PHPzOriginal
2024-06-10 15:35:311047browse

Starting from Bitcoin application programming, ten thousand words explain the programmability of CKB in detail

The following content is reproduced from the Nervos Talk forum, written by Ajian (Editor-in-Chief of the Bitcoin content platform BTC Study).

Abstract

Understanding the programmability of a system requires us to identify the structural characteristics of the system. The exploration of application programming based on Bitcoin script helps us understand the basic structure of CKB Cell and its programming paradigm. Not only that, but it breaks down the programming elements of CKB into the appropriate parts and helps us understand the programmability gains each part brings.

1. Introduction

"Programmability" is a dimension that people often take when comparing blockchain systems. However, disagreements are common about how programmability is described. A common expression is, "XX blockchain supports Turing-complete programming language", or, "XX blockchain supports general programming", which is intended to mean that "XX blockchain" here has powerful programmability sex. There is some truth to the implication of these statements: systems that support Turing-complete programming are generally easier to program than systems that do not. However, there are many aspects to the structural characteristics of smart contract systems, and this statement only touches on one of them. Therefore, it is not enough to gain a deep enough understanding: developers cannot get guidance from it, and ordinary users cannot distinguish it from it. Scam.

The structural characteristics of the smart contract system include:

  • The basic form of state expression (contract) (account vs. transaction output)
  • Whether arbitrary programming is allowed Computation (this is what the term "Turing completeness" refers to)
  • Can the execution process create new data, or does it just pass out Boolean values? (Computation vs. Verification)
  • Whether additional states are allowed to be recorded in the contract
  • Whether one contract can access the state of another contract during execution

Therefore, in addition to "whether arbitrary calculations can be programmed", there are at least four characteristics that will affect the programmability of a smart contract system. It can even be said that these other characteristics are more important, because they determine in a deeper level what is easy to implement and what is difficult to implement; what is a more economical implementation and what is a less efficient implementation.

For example, people often take Ethereum as an example of good programmability. However, the basic form of state expression in Ethereum is an account, and it is difficult to program peer-to-peer contracts (for example, payment channels, one-to-one (One bet contract) - It's not absolutely impossible to achieve, it's just thankless. It is not that the Ethereum ecosystem has never had projects trying to implement payment channels/status channels. There are also many theoretical discussions, but these projects seem to be inactive as of today - this obviously cannot be attributed to lack of effort by developers. It is not accidental that the projects active on Ethereum today all take the form of “fund pools” rather than “point-to-point contracts”. Similarly, people may be very satisfied with the programmability of Ethereum, but when it comes to achieving “account abstraction” (which can also be understood as a generalization of the wallet concept), the account model is inherently deficient.

Similarly, exploring the programmability of CKB also requires us to understand the structural characteristics of the CKB smart contract system in these aspects. What we already know is that CKB allows programming of arbitrary calculations, allows recording of additional states within contracts, and allows one contract to access the state of another contract during execution. However, the form of its contract is the output of the transaction (called a "Cell"), which makes it fundamentally different from Ethereum. Therefore, understanding the Ethereum smart contract system and the contract instances in it does not help us understand how CKB implements these structural features, nor does it help us understand the programmability of CKB.

Fortunately, smart contracts on Bitcoin seem to provide the best foundation for us to understand the programmability of CKB. This is not only because the basic form of Bitcoin’s state expression is also the output of a transaction (called “UTXO”), but also because, with the help of a concept “covenants” proposed by the Bitcoin community, we can understand that CKB has the above structural characteristics, and the programmability gain brought by appropriately splitting the final effect into several parts and identifying them one by one.

2. CKB vs. BTC: What’s more?

Basic Structure

As the basic form of Bitcoin state expression, Bitcoin’s UTXO (“Unspent Transaction Output”) has two fields:

  • The amount, in Satoshi, represents the Bitcoin value of the UTXO; the
  • script public key, also known as the locking script, represents the conditions that need to be met to spend the funds, that is, to unlock the funds. A smart contract program that sets conditions for funds.

Compared with the smart contract systems that emerged later, Bitcoin scripts are quite limited:

  • It does not allow programming of arbitrary calculations; there are only a few practical calculations that can be used for verification (signature check, hash preimage check, time check)
  • It does not allow recording in the contract Additional state; (for example, you cannot use a script to limit the proportion/limit of a single spend; nor can you hide a token in it)
  • It also does not allow access to another contract during execution. State (each script is an independent universe and does not depend on each other).

Although this kind of script is limited, it does not lack the ability to program amazing applications, and it is also the basis for us to explore the programmability of CKB. There will be a special section later to introduce two examples of Bitcoin script programming.

In contrast, the state unit of CKB is called "Cell" and has four fields:

  • Capacity, similar to the amount of UTXO, expresses the amount that the Cell can occupy The size of the space, in bytes;
  • Lock Script, similar to the script public key of UTXO, defines the ownership of the Cell; only when the provided data can pass the Lock Script, it can be "updated" "This Cell (it can also be said to release this Cell and use these Capacities to cast new Cells);
  • Data, data, any data, its volume is limited by Capacity;
  • Type Script, can The selected script is used to set conditions for the update of Data.

In addition, Lock Script and Type Script can also program arbitrary calculations. You can program any signature verification algorithm, you can program any preimage check for any hash algorithm, and so on.

Readers can easily see the improvement in programmability of Cell compared to UTXO:

  • Cell can program any calculation, instead of only certain specific types. Calculation; its ownership verification will be more flexible;
  • Because of the Data and Type Script fields, Cell can record additional states; this allows the Cell to carry the so-called "UDT (User-defined Token").

Combined with the "transaction output" structure of Cell itself, the benefits that these two points can bring are already very, very huge. However, from the above description alone, we do not yet know how Cell implements it. One contract accesses the state of another contract at runtime". To do this, we need to turn to a concept that the Bitcoin community has been discussing for a long time: "covenants".

Restrictions and introspection

The original intention of restrictions is to limit where a sum of money can be spent. On current Bitcoin (which has yet to deploy any constraint proposals), once a fund is unlocked, it can be spent anywhere (payable to any script public key). But the idea of ​​the restriction clause is that it can be restricted in some way to only be spent in certain places. For example, a certain UTXO can only be spent by a certain transaction. Then, even if someone can provide a signature for this UTXO, What it can be spent on has also been determined by the deal. This function may seem a bit strange, but it can produce some interesting applications, which will be introduced in a dedicated section later. Importantly, it is key to our further understanding of CKB programmability.

Rusty Russell correctly pointed out that the restriction clause can be understood as the "introspection" ability of the transaction, that is, when a UTXO A is spent by a transaction B, the script operator can read the part of the transaction B (or all of them) and then check that they match the parameters the script pre-required. For example, whether the script public key of the first output of transaction A is consistent with the script public key of UTXO A (this is the original meaning of the restriction clause).

Keeping readers will realize that if you have complete introspection capabilities, then the input of one transaction can read the status of another input of the same transaction, which realizes the "one" we mentioned earlier. The ability of a contract to access the state of another contract at runtime. In fact, CKB Cell is designed exactly this way.

Based on this, we can divide this complete introspection capability into four situations:

  • Lock Script reads other (input and output) Lock Script
  • Lock Script reads other (input and output) Type Script (and Data)
  • Type Script reads other (input and output) Lock Script
  • Type Script reads other (Input and output) Type Script (and Data)

This allows us to analyze the introspection capabilities of each part under certain assumptions (the functional division of Lock Script and Type Script). The role in the application scenario is to analyze the programmability gains that each part brings to us.

In the following two chapters, we will respectively understand the current (not yet proposed restriction clause) Bitcoin script programming, and the functions that the restriction clause proposal is expected to implement, so as to specifically understand how CKB Cell is programmed and does better. good.

3. Bitcoin Script Programming

This section will use “Lightning Channel/Lightning Network” and “Discreet Log Contract (DLC)” as examples of application programming based on Bitcoin script. Before proceeding, we need to understand two concepts.

OP_IF and "Commitment Transaction"

The first concept is the process control opcode in Bitcoin script, such as: OP_IF, OP_ELSE. These opcodes are no different from IF in computer programming. Their function is to execute different statements based on different inputs. In the context of Bitcoin scripts, this means we can set up multiple unlocking paths for funds; paired with the timelock feature, this means we can assign priority to actions.

Take the famous "Hash Time Lock Contract (HTLC)" as an example. This script translated into vernacular is:

Or, Bob can reveal the reason behind a certain hash value H Original image, and then give her signature to spend the funds;

Alternatively, Alice can spend the funds with her signature after a period of time T.

This "either...or..." effect is achieved through the process control opcode.

The most prominent advantage of HTLC is that it can bundle multiple operations together and achieve atomicity. For example, if Alice wants to exchange BTC for CKB with Bob, Bob can first give a hash value and create an HTLC on the Nervos Network; then Alice creates an HTLC on Bitcoin using the same hash value. Alternatively, Bob takes the BTC paid by Alice on Bitcoin and also reveals the original image, allowing Alice to take CKB on the Nervos Network. Or, if Bob does not reveal the original image, both contracts will expire, and both Alice and Bob can get back the funds they invested.

After the activation of the Taproot soft fork, this feature of multiple unlocking paths has been further strengthened by the introduction of MAST (Merkle Abstract Syntax Tree): we can turn an unlocking path into a Merkle A leaf on the tree, each leaf is independent, so there is no need to use such flow control opcodes; and, because revealing one path does not need to expose other paths, we can add a greater number of unlocking paths to an output , without having to worry about economic issues.

The second concept is "commitment transaction". The idea of ​​a committed transaction is that, under certain circumstances, a valid Bitcoin transaction is still true and binding even if it is not confirmed by the blockchain.

For example, Alice and Bob jointly own a UTXO, and this UTXO requires both of their signatures to be spent. At this point, Alice constructs a transaction to spend it, transferring 60% of the value to Bob and the remaining value to herself; Alice provides her own signature for the transaction and sends it to Bob. Then, for Bob, there is no need to broadcast the transaction to the Bitcoin network or have the transaction be confirmed by the blockchain. The payment effect of the transaction is also real and credible. Because Alice cannot spend this UTXO on her own (and therefore cannot spend it again), and because the signature provided by Alice is valid, Bob can add his own signature at any time and then broadcast the transaction, thereby cashing in the payment. In other words, Alice provides Bob with a “credible commitment” through this valid (not on-chain) transaction.

Commitment transactions are the core concept of Bitcoin application programming. As mentioned before, Bitcoin's contracts are based on verification, stateless, and do not allow cross-access; however, if the contract does not carry state, where are these states stored and how can the contract be safely advanced (changed state)? Commitment transactions give a straightforward answer: the state of the contract can be expressed in the form of transactions, so that contract participants can save the states themselves without having to show them on the blockchain; the problem of contract state changes can also be Transformed into a problem of how to safely update committed transactions; in addition, if we are worried about the danger of entering a contract (for example, entering a contract that requires both parties to sign before spending, we will face the risk of the other party not responding and getting stuck), then, Simply generating and signing a commitment transaction that spends the contract ahead of time eliminates risk and eliminates trust in other participants.

Lightning Channel and Lightning Network

Lightning channel is a one-to-one contract in which both parties can pay each other an unlimited number of times without allowing any one payment to be blocked. Blockchain confirmation. As you might expect, it uses promise transactions.

In the section explaining "Commitment Transactions", we have introduced a payment channel. However, this contract, which only utilizes 2-of-2 multi-signatures, only enables one-way payments. That is, either Alice always pays Bob, or Bob pays Alice until his balance in the contract is exhausted. If it is a two-way payment, it means that after a certain status update, one party's balance may become less than before, but he has the last committed transaction signed by the other party - Is there any way to stop him? What about broadcasting the old commitment transaction so that TA can only broadcast the latest commitment transaction?

Lightning Channel’s solution to this problem is called “LN-Penalty”. Now, assume that Alice and Bob each have 5 BTC in a channel; now Alice wants to pay Bob 1 BTC, so she signs a commitment transaction like this and sends it to Bob:

Enter #0, 10 BTC: Alie-Bob 2-of-2 multi-signature output (i.e. channel contract)

Output #0, 4 BTC: Alice single signature

Output #1, 6 BTC: Either Alice-Bob joint temporary public key #1 single signature or T1 time lock, Bob single signature

Bob also signed a signature (corresponding to the above transaction) Commit the transaction and send it to Alice:

Input #0, 10 BTC: Alie-Bob 2-of-2 multi-signature output (i.e. channel contract)

Output #0, 6 BTC: Bob single signature

Output #1, 4 BTC: Either Bob-Alice joint temporary public key #1 single signature or T1 time lock, Alice single signature

The trick here lies in this " "Joint temporary public key", which is generated using a public key of one's own party and a public key provided by the other party. For example, the Alice-Bob joint temporary public key means that Alice uses one of her own public keys and a public key provided by Bob. , each multiplied by a hash value and then added together. When such a public key is generated, no one knows its private key. However, if Bob tells Alice the private key of the public key he provided, Alice can calculate the private key of the joint temporary public key. ——This is the key to how Lightning Channel can “undo” the old state.

The next time both parties want to update the channel status (initiate payment), the two parties will exchange the private key of the temporary public key given to the other party in the previous round. In this way, participants no longer dare to broadcast the last commitment transaction they received: the output of this commitment transaction assigns value to oneself has two paths, and the private key of the temporary public key path is already known to the other party; so Once the old commitment transaction is broadcast, the other party can immediately use this joint temporary private key to take away all the funds in this output. – This is what “LN-Penalty” means.

Specifically, the sequence of interaction is: the party initiating the payment first requests a new temporary public key from the other party, then constructs a new committed transaction and hands it to the other party; the party who obtains the committed transaction requests the other party Expose the private key of the temporary public key you gave in the previous round. This interaction sequence ensures that participants always get new commitment transactions first, and then invalidate the commitment transactions they obtained in the previous round, so it is trust-free.

In summary, the key designs of the lightning channel are:

Both parties always use commitment transactions to express the internal status of the contract, and express payment by changes in the amount;

Commitment transactions always cost the same input (requiring both parties to provide signed inputs at the same time), so all commitment transactions compete with each other, and ultimately only one can be confirmed by the blockchain;

Two participants The ones who signed are not the same commitment transaction (although they are in pairs); the ones they sign are always transactions that are more beneficial to themselves. In other words, the commitment transactions that participants receive are always detrimental to themselves;

This disadvantage is reflected in the fact that the output that assigns value to itself has two unlocking paths: one path can be unlocked with your own signature, but you need to wait for a while; and the other path uses the other party's public The key is protected only if one of its own temporary private keys is not exposed;

In each payment, both parties exchange a new commitment transaction for the temporary private key used by the other party in the previous round. , thus, the party that handed over the temporary private key no longer dares to broadcast the old commitment transaction, so it "revokes" the previous commitment transaction and updates the status of the contract; (In fact, these commitment transactions are It is a valid transaction and can be broadcast to the blockchain, but the participants are forced to be punished and dare not broadcast it anymore)

Any party can withdraw from the contract at any time with the commitment transaction signed by the other party. ; However, if both parties are willing to cooperate, they can sign a new transaction that allows both parties to get their money back immediately.

Finally, because HTLC can also be placed in the commitment transaction, the lightning channel can also forward payments. Assuming that Alice can find a path consisting of lightning channels connecting back and forth and reach Daniel, then trust-free multi-hop payment can be achieved without opening a channel with Daniel. This is the Lightning Network:

Alice -- HTLC --> Bob -- HTLC --> Carol -- HTLC --> Daniel

Alice

When Alice finds such a path and wants to pay Daniel, she requests a hash value from Daniel , based on which a HTLC is constructed to Bob, and Bob is prompted to forward a message to Carol and provide the same HTLC; the message prompts Carol to forward a message to Daniel and provide the same HTLC. When the news reaches Daniel, he reveals the original image to Carol, thereby obtaining the value of HTLC and updating the contract status; Carol does the same, obtains Bob's payment and updates the channel status; finally, Bob reveals the original image and updates the status to Alice . Due to the characteristics of HTLC, this series of payments either succeeds together or fails together, so it is trustless.

The Lightning Network is composed of channels one after another, and each channel (contract) is independent of each other. This means that Alice only needs to know what happened in her own channel with Bob, and does not need to care about how many interactions occurred in other people's channels, nor what currency these interactions used, or even whether they are real. using channels).

The scalability of the Lightning Network is not only reflected in the fact that the payment speed within a Lightning channel is only limited by the hardware resource investment of both parties, but also in that due to the decentralized storage of state, a single node can leverage the largest amount of transactions at the lowest cost. lever.

Discreet Log Contract

The Discreet Log Contract (DLC) uses a cryptographic technique called an "adaptor signature" to allow Bitcoin scripts to be programmed to depend on external events. financial contract.

Adapter signature allows a signature to become a valid signature only after adding a private key. Taking Schnorr signature as an example, the standard form of Schnorr signature is (R, s), where:

R = r.G # The nonce value r used in the signature is multiplied by the elliptic curve generating point, which can also be said to be the public key of r

s = r + Hash(R || m || P) * p # p is the signature private key, P is the public key

Verifying the signature means verifying s.G = r.G + Hash( R || m || P) * p.G = R + Hash(R || m || P) * PK

Suppose I am given a pair of data (R, s'), where:

R = R1 + R2 = r1.G + r2.G

s' = r1 + Hash(R || m || P) * p

Obviously, this is not A valid Schnorr signature cannot pass the signature verification formula, but I can prove to the verifier that as long as TA knows the private key r2 of R2, it can be turned into a valid signature:

s'.G + R2 = R1 + Hash(R || m || P) * P + R2 = R + Hash(R || m || P) * P

Adapter signature lets a signature Validity relies on a secret data and is verifiable. But what does this have to do with financial contracts?

Suppose Alice and Bob want to bet on the outcome of a football game. Alice and Bob bet 1 BTC on Green Goblin and Alina respectively. Moreover, the football commentary website Carol promises to use a nonce R_c to publish the signature s_c_i of the result when the result of the football game is announced.

It can be seen that there are three possible results (so Carol's signature has 3 possibilities):

  • The Green Goblin wins and Alice wins 1 BTC
  • Arina wins, Bob wins 1 BTC
  • In a draw, the two people’s funds are returned the same way

To this end, the two create a commitment transaction for each outcome. For example, the commitment transaction they created for the first outcome looks like this:

Input #0, 2 BTC: Alie-Bob 2-of-2 Multi-Signature Output (i.e. Bet Contract)

Output #0, 2 BTC: Alice single signature

However, the signature created by Alice and Bob for this transaction is not (R, s), but the adapter signature (R, s'); that is, , the signatures given by both parties to each other cannot be directly used to unlock the contract, but a secret value must be revealed. This secret value is exactly the original image of s_c_1.G, which is Carol’s signature! Because the nonce value of Carol's signature has been determined (it is R_c), s_c_1.G can be constructed (s_c_1.G = R_c + Hash(R_c || 'The Green Goblin wins' || PK_c) * PK_c).

When the result is announced, assuming the Green Goblin wins, Carol will release the signature (R_c, s_c_1). Then both Alice and Bob can complete the opponent's adapter signature and add their own signature. Make the above transaction a valid transaction, broadcast it to the network, and trigger the settlement effect. But if the Green Goblin hadn't won, Carol wouldn't have released s_c_1, and the committed deal wouldn't have been a valid deal.

The same goes for the other two transactions. In this way, Alice and Bob make the execution of this contract dependent on external events (to be precise, relying on the assertion machine's broadcast of external events in the form of a signature) without trusting the counterparty. Financial contracts, large and small, such as futures and options, can be implemented in this way.

Compared with other forms of implementation, the biggest feature of the cautious log contract is its privacy: (1) Alice and Bob do not need to tell Carol that they are using Carol's data, which does not affect the execution of the contract at all; (2) On-chain observers (including Carol) cannot determine which website services they are using by executing transactions on Alice and Bob's contracts, or even determine that their contract is a betting contract (rather than a lightning bolt). aisle).

4. Introduction to the application of restrictive clauses

OP_CTV and congestion control

Developers in the Bitcoin community have proposed a variety of proposals that can be classified as restrictive clauses. From the current point of view, the most famous proposal is OP_CHECKTEMPLATEVERIFY (OP_CTV). Its concept is relatively simple, but it retains considerable flexibility, so it is welcomed by the Bitcoin community that advocates simplicity. The idea of ​​OP_CTV is to commit a hash value in the script to constrain that the funds can only be spent by the transaction represented by the hash value; this hash value commits the output of the transaction and most fields, but does not commit The input of the transaction only commits to the input quantity.

"Congestion Control" is a good example that can reflect the characteristics of OP_CTV. Its basic application scenario is to help a large number of users withdraw from the exchange (an environment that requires trust) into a capital pool; since this capital pool uses OP_CTV to plan future spending methods, it can ensure that users can exit this trust-free environment. The fund pool does not require anyone’s help; and because this fund pool only appears as a UTXO, it avoids paying a large amount of handling fees when the demand for on-chain transactions is high (reduced from n outputs to 1 output; also from n transactions Transactions reduced to 1 transaction). Users in the pool can wait for an opportunity and then withdraw from the pool.

Suppose Alice, Bob, and Carol want to withdraw 5 BTC, 3 BTC, and 2 BTC from the exchange respectively. Then the exchange can make an output with 3 OP_CTV branches in the amount of 10 BTC. Suppose Alice wants to withdraw money, she can use branch 1; the transaction represented by the hash value used by the OP_CTV of this branch will form two outputs, one output is to allocate 5 BTC to Alice; the other output is a fund pool, Also use OP_CTV to commit a transaction that only allows Bob to withdraw 3 BTC and send the remaining 2 BTC to Carol.

The same applies if Bob or Carol wants to withdraw money. When they withdraw money, they will only be able to use transactions that can pass the corresponding OP_CTV check, that is, they can only pay themselves the corresponding amount, and cannot withdraw money at will; the remaining funds will enter a fund pool locked using OP_CTV, thus ensuring that no matter what the Regardless of the order in which users withdraw their funds, the remaining users can withdraw from the pool trustlessly.

Abstractly speaking, the role of OP_CTV here is to plan the path for the contract to the end of the life of the contract, so that no matter which path the capital pool contract takes or which state it reaches, it can maintain trust-free exit. Attributes.

This kind of OP_CTV also has a very interesting usage: "hidden one-way payment channel". Suppose Alice forms such a pool and guarantees that the funds can be withdrawn trustlessly into an output with a script like this:

Either, Alice and Bob spend it together or, after a while, Alice can do it alone Spend it

If Alice does not reveal it to Bob, Bob will not know that such an output exists; once Alice reveals it to Bob, Bob can treat this output as a time-sensitive one-way payment channel, and Alice The funds can be used to pay Bob immediately without waiting for confirmation from the blockchain. Bob just needs to let Alice get his committed transaction on-chain before Alice can spend it on her own.

OP_Vault and Vault

OP_VAULT is a restriction clause proposal specially proposed for constructing "vaults".

Vault contracts are designed to be a safer and more advanced form of self-custody. Although the current multi-signature contract can avoid the single point of failure of a single private key, if an attacker does obtain a threshold number of private keys, the owner of the wallet will be unable to do anything. The Vault hopes to impose a single spend limit on the funds; at the same time, when withdrawing from it using regular routes, the withdrawal operation will enforce a waiting period; during the waiting period, the withdrawal operation can be interrupted by an emergency wallet recovery operation. Even if such a contract is compromised, the owner of the wallet can initiate countermeasures (using the emergency recovery branch).

Theoretically, OP_CTV can also program such a contract, but there are many inconveniences, one of which is the handling fee: while committing to a transaction, it also commits to the handling fee that will be paid for the transaction. . Given the purpose of such a contract, the time between setting up the contract and withdrawing money must be very long, making it almost impossible to predict an appropriate fee. Although OP_CTV does not limit input, so you can increase the handling fee by increasing the input, but all the input provided will become handling fees, so it is unrealistic; the other way is CPFP, that is, by spending the funds withdrawn, in Fees are provided on new transactions. In addition, the use of OP_CTV also means that such a safe contract cannot withdraw in batches (and of course cannot restore in batches).

The OP_VAULT proposal attempts to solve these problems by proposing new opcodes (OP_VAULT and OP_UNVAULT). OP_UNVAULT is designed for batch recovery, so we won't mention it for now. The action of OP_VAULT is like this: when we put it on a branch of the script tree, it can be used to promise an actionable opcode (such as OP_CTV) without specific parameters; when spending this branch, Transactions can pass in specific parameters, but other branches cannot be changed. Therefore, it does not need to set a handling fee, and can set the handling fee when spending this branch; assuming that this branch also has a time lock, then it will enforce a time lock; finally, because it can only change the location of Branch, other branches on the new script tree (including the emergency recovery branch) will not be changed, thus allowing us to interrupt such a withdrawal operation.

In addition, there are two points worth mentioning: (1) The action of the OP_VAULT opcode is similar to another restriction proposal: OP_TLUV; Jeremy Rubin correctly pointed out that this has given rise to the concept of "computation" to a certain extent : OP_TLUV/OP_VAULT first promises an opcode to allow the user to pass in parameters to the opcode through a new transaction, thereby updating the entire script tree leaf; this is no longer "verifying the incoming data according to certain conditions" ” instead of “generating new meaningful data based on incoming data”, although the calculations it can enable are relatively limited.

The complete OP_VAULT proposal also makes use of some proposals on the transaction pool policy (mempool policy) (such as v3 format transactions) to achieve better results. This reminds us that “programming” can mean a lot more than we think. (A similar example is Open Transaction in Nervos Network.)

5. Understanding CKB

In the above two chapters, we introduced a more restricted structure ( Bitcoin UTXO), how we can use scripts to program interesting applications; we also introduced proposals to try to add introspection capabilities to this structure.

UTXO Although there is no lack of ability to program these applications, readers can easily detect their shortcomings, or areas that can be optimized, such as:

  • In LN-Penalty , Channel participants must save each past commitment transaction and the corresponding penalty secret value to deal with the opponent's fraud, which constitutes a storage burden. If there is a mechanism that can ensure that only the latest commitment transaction will take effect, and the old commitment transaction will not take effect, then this burden can be eliminated, and it can also eliminate the possibility of nodes mistaking older commitments due to failures. The problem of unexpected penalties due to transactions being uploaded to the chain.
  • In DLC, it is assumed that there are many possible outcomes of the event, and both parties have to generate many signatures in advance and submit them to each other. This is also a huge burden; in addition, the income of the DLC contract is directly tied to It is fixed on the public key, so its position is not easy to transfer. Is there any way to transfer the contract position?

In fact, the Bitcoin community has proposed answers to these questions, basically related to a Sighash proposal (BIP-118 AnyPrevOut).

However, if we are programming on CKB, BIP-118 is available now (this Sighash tag can be simulated with the ability to introspect and specifically verify signatures).

By learning Bitcoin programming, we not only know how to program the "transaction output" format (what CKB can program), but also know how to improve these applications (if we program these on CKB applications, how CKB's capabilities can be used to improve them). For CKB developers, programming based on Bitcoin script can be regarded as a learning textbook or even a shortcut.

Below, we analyze the programmability of each module of CKB programming one by one. Let us not consider introspective abilities for now.

Lock Script that can be programmed for arbitrary calculations

As mentioned above, UTXO cannot be programmed for arbitrary calculations. Lock Script can, which means that Lock Script can program (before the restrictions are deployed) everything based on UTXO programming, including but not limited to the lightning channel and DLC mentioned above.

In addition, this ability to verify any calculation also allows Lock Script to use more authentication methods and is more flexible than UTXO. For example, we can implement a Lightning channel on CKB where one party uses ECDSA signature and the other party uses RSA signature.

In fact, this is one of the earliest areas that people began to explore on CKB: using this flexible identity verification capability in users' autonomous custody to achieve the so-called "account abstraction" - Authorization of transaction validity and restoration of control are extremely flexible and virtually unlimited. In principle, this is a combination of “multiple spending branches” and “any authentication method”. Examples of implementations include: JoyID Wallet, UniPass.

In addition, Lock Script can also implement the eltoo proposal, thereby realizing a lightning channel that only needs to retain the latest committed transaction (in fact, eltoo can simplify all point-to-point contracts).

Type Script that can program arbitrary calculations

As mentioned above, one of the major uses of Type Script is to program UDT. Combined with Lock Script, this means we can implement UDT-backed Lightning channels (as well as other types of contracts).

In fact, the separation of Lock Script and Type Script can be regarded as a security upgrade: Lock Script focuses on implementing custody methods or contractual protocols, while Type Script focuses on the definition of UDT.

In addition, the ability to initiate checks based on the definition of UDT also enables UDT to participate in contracts in a manner similar to CKB (UDT is first-class citizen).

For example: The author once proposed a protocol to implement trustless NFT secured lending on Bitcoin. The key to this protocol is a commitment transaction in which the value of the input is less than the value of the output (so it is not yet a valid transaction). However, once sufficient input can be provided for this transaction, it is A valid transaction: Once the lender is able to repay, the lender cannot keep the pledged NFT as its own. However, the trustless nature of this commitment transaction is based on the transaction checking the amounts of the inputs and outputs, so the lender can only repay the loan in Bitcoin - even if both the lender and lender are willing to accept another currency (such as in RGB USDT issued by the protocol), Bitcoin's commitment transaction cannot guarantee that as long as the lender returns the sufficient amount of USDT, it will be able to get back its NFT, because the Bitcoin transaction does not know the status of USDT at all! (Edit: In other words, it is impossible to construct a commitment transaction that is conditional on USDT repayment.)

If we can initiate a check based on the definition of UDT, it will be possible for the lender to sign another commitment transaction, allowing the lender to Use USDT to repay. The transaction will check the amount of USDT input and the amount of USDT output, giving users trust-free repayment using USDT.

Revision: Assuming that the NFT used as collateral and the token used for repayment are issued using the same protocol (such as RGB), then the problem here can be solved, and we can construct it according to the RGB protocol A commitment transaction that allows the state transition and repayment of NFT to occur simultaneously (a transaction is used to bind two state transitions within the RGB protocol). However, because RGB transactions also rely on Bitcoin transactions, the construction of the commitment transaction here will be somewhat difficult. All in all, while the problem can be solved, token is first-class citizen.

Next we consider the ability of introspection.

Lock Script reads other Lock Scripts

This means full programming possibilities on Bitcoin UTXOs after the proposed restrictions are implemented. Including the safe contract mentioned above, as well as applications based on OP_CTV (such as congestion control).

XueJie once mentioned a very interesting example: you can implement a collection account Cell on CKB. When using this Cell as the input of a transaction, if the Cell it outputs (using the same Lock Script Cell) has more Capacity, so this input does not need to provide a signature and will not affect the validity of the transaction. In fact, such a Cell would not be possible without the ability to introspect. This kind of collection account Cell is very suitable as a collection method for institutions because it can pool funds. The disadvantage is that it has poor privacy.

Lock Script reads other Type Scripts (and Data)

An interesting application of this ability is equity tokens. Lock Script will determine whether it can use its own Capacity based on the number of Tokens in other inputs, and where the Capacity can be spent (requires the ability to introspect Lock Script).

Type Script reads other Lock Scripts

Not sure, but it can be assumed to be useful. For example, Lock Scripts that can check the inputs and outputs of a transaction in Type Script remain unchanged.

Type Script reads other Type Scripts (and Data)

Trading cards? Collecting n tokens can be exchanged for a larger token: )

6. Conclusion

Compared with the previous smart contract systems (such as Ethereum) that can program any calculation, Nervos Network adopts a different structure; therefore, understanding of previous smart contract systems is often difficult to form the basis for understanding Nervos Network. This article proposes a method to understand the programmability of CKB Cell starting from the application programming of a structure that is more restricted than CKB Cell - BTC UTXO. Moreover, by using the concept of "introspection" to understand Cell's "cross-contract access" capability, we can divide the situations in which introspection capabilities are used and determine specific uses for them.

Revision:

1. Regardless of Cell’s cross-access capability (i.e., introspection capability), lock scripts can be considered Bitcoin Scripts with state and extreme programming capabilities. Therefore, based on This makes it possible to program all applications based on Bitcoin Script;

2. Regardless of Cell's cross-access capability (ie, introspection capability), the distinction between lock scripts and type scripts can be considered a security upgrade: It separates UDT's asset definition and storage methods; in addition, type scripts (and Data) that can expose state realize the effect of UDT being first-class citizen.

The above is the detailed content of Starting from Bitcoin application programming, ten thousand words explain the programmability of CKB in detail. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn