BTC
ETH
HTX
SOL
BNB
View Market
简中
繁中
English
日本語
한국어
ภาษาไทย
Tiếng Việt

Technical Analysis: What Are the Differences Between Smart Contracts on Ethereum, Bitcoin, and Bitcoin Cash?

This article is about 7911 words, reading the full article takes about 12 minutes
Evenly divided, each has its own merits.
AI Summary
Expand
Evenly divided, each has its own merits.

Editor's Note: This article comes fromFirst Class Warehouse (ID: first_vip1), reprinted by Odaily with authorization.

Editor's Note: This article comes from

First Class Warehouse (ID: first_vip1)

, reprinted by Odaily with authorization.

This article focuses on the salient differences between smart contracts on these three platforms. Since the focus is on smart contracts and scripting functionality, the basics of the platform or blockchain will not be discussed here. This article also hereby introduces on-chain smart contracts, and the existence of several second-layer smart contract solutions, such as RSK. These solutions are definitely worth discussing, and I will not do a very in-depth study due to the space.

secondary title

Ethereum: It has its own state and is Turing complete

image description

Figure: EVM fee structure

Each transaction costs a significant amount of Gas, depending on the opcode used. Gas fees are paid with Ethereum's native cryptocurrency, ETH. In order to limit the amount of computation these nodes must perform per block, there is a limit on the amount of gas that can be used in a single block, called the "block gas limit".

During the execution of smart contract functions, contracts can store and access necessary data. Depending on its use, these data can be stored in different locations, i.e. in different data locations. The first is the "stack", which contains the values ​​used in the computation. Only the first 16 items in the stack are easily accessible, so not suitable for long-term storage. The calculation using the stack is shown below.

image description

Figure: Stack-based computing

Second, to supplement the stack, "contract memory" can be used to store, retrieve and pass data during the current contract execution. These values ​​can be retrieved from memory to be used for calculations on the stack, and the results stored back to memory. These values ​​only persist for the duration of the current execution. At the end of contract execution, the contract memory and stack are erased.

Ultimately, where the data lives is "contract storage", which is used to persist data during contract execution. Persistent variables such as token balances are stored in contract storage. For data persistence, contract memory is stored on each Ethereum node. So its memory is like RAM, and its storage is like a hard drive or a persistent database.

More details on how the Ethereum Virtual Machine works can be found in MyCrypto's article.

Writing Smart Contracts Although all smart contracts use the EVM, most smart contracts are not hand-written using EVM bytecode, just like most JVM bytecode are not hand-written. Instead, there are several high-level languages ​​that can be used to write smart contracts in Ethereum, the most popular being Solidity, but also Vyper, an EVM-oriented programming language. The image below contains an example of a very simple Solidity smart contract.

These deployed contracts only exist in the network as "fragments" of EVM bytecode, and are hardly usable on their own. In order to "interface" with them, an Application Binary Interface (ABI) needs to be provided, which includes a list of all public functions and their parameters. To make users more aware of these contracts, services like Etherscan help verify contract source code so that users can inspect the code before using the contract.

All smart contracts can be directly accessed by connecting to an Ethereum node and using its JSON-RPC interface. However, many smart contracts are accessed through front-end applications that connect to nodes and manage the ABI. This can be done with one of the many different Ethereum SDKs (such as web3.js or ethers.js), which can call JSON-RPC under the hood. This provides a better experience for contract users, as the most difficult part is visualized.

Smart contracts can be interacted with in two different ways: Calls and Transactions. A call is a native call to a contract function, it does not broadcast anything to the blockchain. Therefore, the calling process is "read-only", cannot make any changes to the contract state, and does not incur any fees. The transaction is a real "write operation", which will indeed be broadcast to the network and included in the blockchain, and will generate miner fees. Taking the ERC20 token as an example, the token balance is retrieved by calling, and the token is transferred by initiating a transaction.

These properties of Ethereum (with its Turing-complete EVM and persistent storage) allow the creation of any type of decentralized application that runs on-chain. A good example is the DeFi ecosystem, which includes applications such as Maker, Uniswap, and Compound, as well as ERC20 and ERC721 token standards. These applications allow complex functions with an unlimited number of dynamic actors.

Figure: DeFi interoperability in rDai

Most importantly, smart contracts can themselves become "participants" in other smart contracts, enabling powerful integration and composition between these contracts. For example, smart contracts that hold token balances and lend them to Compound or exchanges with Uniswap, or use rDai to automatically invest in DAI and contribute the accrued interest to charity.

Although smart contracts can interact with each other, every transaction on-chain must come from an external account. Therefore, the interaction between Ethereum smart contracts must still be triggered by the user through the initial transaction. After this initial trigger, interactions between contracts resemble direct access.

In other words, a smart contract can call other smart contracts' "read-only functions" or trigger "write operations" (transactions). Since only external accounts can trigger transactions, transactions between smart contracts are called internal transactions or message calls to distinguish them from user-initiated transactions.

secondary title

Bitcoin: Stateless and Simple

All Bitcoin transactions (including regular transfers) are supported by a stack-based programming language called "Bitcoin Script" (Script). As mentioned above, Ethereum's EVM is designed for Turing-complete and interoperable smart contracts, while Bitcoin Script has intentionally added various restrictions and works in a fundamentally different way. Interpreting Bitcoin Script is like EVM, Bitcoin Script uses a stack (Stack) to hold values ​​(Value) and perform calculations on these values. But unlike the EVM, the stack is the only data location available in Bitcoin Script. This means that it is difficult to store multiple values ​​for later use in contract executions. More importantly, this means that it is impossible to store or modify values ​​that persist during contract execution (but the EVM can).

This is the biggest difference between Ethereum's smart contracts and Bitcoin. Ethereum's model is stateful, while Bitcoin is stateless. The popular understanding is that Ethereum can be thought of as similar to the common imperative mutable data programming paradigm, while Bitcoin is similar to the function-invariant data paradigm.

Bitcoin's model allows independent and much more efficient verification of transactions, which makes it easier to parallelize and shard transactions. However, without any mutable data storage, it is more difficult to create complex smart contracts like Ethereum on Bitcoin, for example, ERC20 contracts must track token balances and make changes.

In addition to these state differences, there are other factors that limit the complexity of Bitcoin smart contracts. Notably, Bitcoin Script lacks support for certain arithmetic functions as well as any form of looping or recursion. Its contracts also have an effective size limit of 520 bytes and can only contain up to 201 opcodes.

Most smart contracts on Bitcoin fall into a few categories of simple contracts. For example, a multi-signature contract that can be used by multiple participants, or a hashed time-locked contract (HTLC).

And because these contracts on Bitcoin are so simple, most of the value is captured by combining different contracts with other off-chain application logic. This way, simple contracts can be combined to create complex solutions, such as the Lightning Network or cross-chain auctions, to name a few.

Explaining Bitcoin Transactions Every transaction in Bitcoin is realized through a so-called "transaction output". When these transaction outputs are available in an account, they are called Unspent Transaction Outputs (UTXOs). These UTXOs are locked by a locking script (or scriptPubKey) and specified usage conditions. When attempting to spend UTXOs, an unlocking script (or ScriptSig) is provided, and these scripts then perform calculations together. The transaction takes effect only if the script executes without errors and the result value is TRUE.

Like the EVM, all Bitcoin nodes execute these scripts to verify transactions, but the Bitcoin blockchain has no concept of gas costs, so miners are paid per byte of transaction data. In order to limit the amount of work that a node has to do, some restrictions have also been put on some of the more intensive script operations.

Interacting with Smart Contracts Smart contracts in Bitcoin are written using the P2SH model (first-class warehouse note: there is translation as "payment to script hash"). A lock script in P2SH mode contains a script hash and needs to provide an unlock script for the full script (called a redeem script) and an unlock script for that redeem script. The figure below shows this pattern.

image description

Figure: P2SH mode

First-class warehouse knowledge: The P2SH mode was introduced to simplify the use of complex scripts (the traditional mechanism is P2PKH), and the complex locking script is compiled into a simple script with 20 byte hashes, just like the Bitcoin address is A 20-byte public key based on Base58 encoding. The biggest difference between P2SH and the traditional P2PKH method is that the person who sets the transfer conditions is changed from the sender to the receiver. Various forms of transactions, such as multi-signature transactions, can be realized by adding various transfer-out conditions in the redemption script.

Bitcoin nodes verify these smart contract transactions in two stages. First, the Redeem Script is hashed and checked against the hash in the Lock Script. If they match, the "Lock Script" is used to unlock the "Redemption Script", as if the "Redemption Script" was the original lock script.

These deployment differences encourage the combined use of both types of smart contracts. A good example is LocalCryptos, which supports non-custodial local transactions for Ethereum and Bitcoin. For Ethereum, it uses one big smart contract to keep track of all transactions, while for Bitcoin, it creates separate contracts for each transaction.

Writing Smart Contracts While Ethereum has multiple high-level languages ​​that compile to EVM bytecode, Bitcoin has paid less attention to this. Despite the complexity of the systems that can be built with Bitcoin Script, the contracts themselves are often simple. Therefore, there is little need to abstract away the underlying system. And since Bitcoin contracts have size limitations and the high cost of each additional byte, it's important to keep contracts "as small as possible."

Although these high-level languages ​​are less important in Bitcoin, they do exist. Ivy is the "most polished" high-level language in Bitcoin, created by Dan Robinson in 2017. The figure below shows an example smart contract written in Ivy. The contract can be used to send money that can be recovered by the sender if the receiver does not spend it in time.

Recently, several researchers at Blockstream released Miniscript, a language that focuses on the analysis and composability of smart contracts rather than abstracting the underlying system. Given that Bitcoin contracts often lack abstract complexity, this seems like the right path to take.

secondary title

The above is on the one hand Ethereum, which is capable of creating many powerful and useful smart contracts that exist entirely on the Ethereum chain, and at the same time, due to its stateful nature (Stateful), it also raises scalability issues. On the other hand, Bitcoin's smart contract stateless (Stateless) model allows independent and simple verification of smart contract transactions, but its scripting system limits the practicality of the contract.

Before the fork, Bitcoin Cash and Bitcoin shared the same history, so their underlying scripting systems are functionally identical, and Bitcoin Cash benefits from these same aspects. Since then, a large portion of the Bitcoin Cash community has recognized the need for "more useful smart contracts." Bitcoin Cash enables new features that make its smart contracts more useful, while retaining the fundamental properties that allow for stateless verification of Bitcoin.

Feature Upgrades for BCH To understand the possibilities of Bitcoin Cash smart contracts, we need to look at its biannual network upgrades. These network upgrades have been performed every May and November since the original hard fork in 2017. We specifically discuss changes to the Bitcoin scripting engine, although some other improvements have been made, such as Schnorr signatures.

In the early days of Bitcoin, some opcodes were disabled due to unsafe usage. Within the first year after the Bitcoin Cash fork, the developers of the Bitcoin-ABC node addressed these issues and reintroduced the opcode with slightly modified functionality, as shown in the diagram below. Most importantly, the upgrade makes it possible to encode and decode structured data in Bitcoin Script.

image description

Figure: BCH enabled a new opcode in May 2018

Half a year later, another new opcode was released in the November 2018 Bitcoin Cash network upgrade. Among them is the update OP_CHECKDATASIG, which allows users to verify the signature of any message in Bitcoin Script. If we combine script updates introduced in 2018, these updates can be used to introduce new and useful smart contract functionality to Bitcoin Cash.

Writing Smart Contracts Bitcoin Cash's new features add a lot of extra complexity to its smart contracts relative to the original Bitcoin Script. This makes it even more important to have an ecosystem that provides higher-level abstraction layers through high-level languages, SDKs, and tools.

Two big projects currently working on this problem are Spedn (created by the pseudonym Tendo Pein) and CashScript (created by the author of this article, Rosco Kalis, inspired by Ethereum's Solidity language). Although they are still under active development, these tools make it easier to work with smart contracts in Bitcoin Cash. Some of the functionality is illustrated below using CashScript code snippets.

An example of this can be viewed in the HODLVault example contract below. This contract enforces HODLing until a certain BCH/USD price is reached. The required BCH/USD price feed is published by the oracle provider and passed into the contract by the user. For added decentralization, smart contracts can be set up to use multiple data sources instead of trusting a single centralized service.

Covenants The second big use case is a technique called Covenants, which gets its name from a term used in property law to limit the use of objects. In the case of Bitcoin Cash, it limits the use of the currency in smart contracts. So while smart contracts in Bitcoin can only authorize monetary spending in general, Bitcoin Cash contracts are able to impose restrictions on the amount that can be spent or the identity of the recipient.

When transferring bitcoins, the sender must provide a signature to authorize the transaction. To generate this signature, the sender signs a hash representation of the transaction. This hash is called a Sighash, and the actual transaction data is contained in the Sighash preimage.

By using _OP_CHECKSIG_ and _OP_CHECKDATASIG_ with the same signature, we can access Sighash data. The data format can be checked in the specification and is included in the image below. An important field is scriptCode, which contains the bytecode of the smart contract itself. The other is hashOutputs which allows users to enforce transaction outputs.

image description

Figure: Bitcoin Cash Sighash data format

It's nice to know how guarantee contracts work on a technical level, but CashScript already abstracts away most of the complexities associated with contracts. When writing smart contracts using CashScript, these fields are readily available without the manual steps of verifying and decoding Sighash originals.

The first smart contract to use guaranteed contract technology is Licho's Last Will, a smart contract that allows users to transfer the estate of a deceased person to their own. The contract defines three different functions. The first allows the successor to claim the funds after 180 days. The second allows the owner's cold key (ColdKey) to be spent in any way. The third allows the owner's Hot Key to refresh the 180-day period by forcing the entire contract balance to be sent back to the contract.

A CashScript version of Last Will is included below, but the original version was written by Spedn and can be viewed here.

This is one of the simple examples of useful guarantee contracts, but guarantee contracts enable even more complex functionality. After the Last Will contract was signed, its creator Karol Trzeszczkowski went on to create Mecenas, a company that enforces recurring payments on Patreon and the like.

Guaranteed contracts were originally proposed in a paper titled "Bitcoin Covenants", which required a new opcode _OP_CHECKOUTPUTVERIFY_. Other suggestions followed, such as _OP_CHECKTEMPLATEVERIFY_ or _OP_CHECKSIGFROMSTACK_. The latter is very similar to Bitcoin Cash's covenant implementation. More information on contracts of guarantee can be learned in Tendo Pein's article.

Simulated state looks at the "last will" contract, it may be valuable to change heirs when the contract is in place. Since we can force a send to the current contract by looking at the current contract's bytecode, we can force a send to a slightly different contract by changing this bytecode slightly. A function can be created that sends the entire contract's balance to a contract with the exact same bytecode but a different heir.

By using this technique, it is possible to change certain variables in a contract while retaining the same rules of the contract. We call it "simulated state" because it provides some of the benefits of contract state without the scalability issues of stateful systems like Ethereum. This approach has other disadvantages as a tradeoff has to be made somewhere.

in conclusion

Replacing these variables inside the bytecode can feel cumbersome, especially when trying to replace variables deeper inside the bytecode. This functionality should be abstracted in a high-level language so that new bytecode is automatically generated by supplying new parameters. This abstraction might look like this:

looking to the future

A lot of abstraction comes at the cost of larger contracts, resulting in higher fees. But Bitcoin Cash’s transaction fees are generally low, so it’s the best of both worlds. But Bitcoin Cash has the same size limit as Bitcoin, so these abstractions do make it harder to stay within the limit. This resulted in many developers having to manually optimize compiled bytecode.

in conclusion

Every cryptocurrency weighs in its smart contract system. Ethereum is the most commonly used smart contract platform with the widest range of features. Bitcoin provides a more basic version of smart contracts through its stateless scripting system, which is more efficient to verify but less functional. Bitcoin Cash has the same foundation as Bitcoin, but adds new features that try to strike a compromise between efficient verification and useful smart contracts. In the end, all move toward similar goals.

开发者
ETH
BTC
Welcome to Join Odaily Official Community