Technical analysis of smart contracts on | ethereum, bitcoin, and bitcoin cash
First class
What is a smart contract? Determining the use of an asset by one or more conditions is equivalent to executing a contract, which becomes a smart contract when it can be executed completely by code and automatically without trust. Rosco Kalis is a senior blockchain technician and the inventor of CashScript.
Although ethereum was the first platform to have a fully intelligent contract with Turing, it was already possible to create a basic contract on bitcoin using a language called "bitcoin Script". Bitcoin cash has been improving its smart contracts recently. Although not as advanced as ethereum, they all support the existence of smart contracts on the chain in their own unique ways and advantages.

This article focuses on the salient differences between smart contracts on these three platforms. Since the focus is on smart contracts and scripting capabilities, the basics of the platform or blockchain are not discussed here. This article also describes smart contracts on the chain, as well as the existence of several tier 2 smart contract solutions, such as RSK. These solutions are definitely worth discussing because they don't require much in-depth research.
Ethereum: self - contained and Turing complete
Ethereum is the largest smart contract platform to date, implemented using the ethereum virtual machine (EVM), a turing-complete virtual machine. This means that with enough resources, EVM can compute anything. Conceptually, this is similar to many other common platforms, such as the Java virtual machine JVM, that are used to execute Java programs.
Explain the EVM entry
But the biggest difference between those common platforms and ethereum's EVM is that ethereum's smart contract code is executed by all ethereum nodes to validate transactions. For the reward node to execute this code, all EVM opcodes have associated gas costs, as shown below.

Figure: EVM cost structure
Each transaction costs a significant amount of Gas, depending on the opcode used. Use ETH, ethereum's native cryptocurrency, to pay for Gas. To limit the amount of computation that each block of these nodes must perform, there is a limit on the amount of Gas that can be used in a single block, known as the "block Gas limit".During the execution of the smart contract function, the contract can store and access the necessary data. Depending on its purpose, the data can be stored in different locations, that is, in different data locations. The first is the "stack," which contains the values used in the calculation. Only the first 16 items in the stack are easily accessible, so long-term storage is not appropriate. The calculation using the stack is shown below.
Figure: stack-based calculation
Second, to supplement the stack, "contract memory" can be used to store, retrieve, and pass data during the execution of the current contract. These values can be retrieved from memory to be used for calculations on the stack and the results stored back in memory. These values persist only during the current execution. At the end of contract execution, the contract memory memory and stack are erased.Finally, the location of the data is "contract storage," which is used to persist the data for the duration of the contract. Persistence variables, such as token balances, are stored in the contract store. For data persistence, the contract memory is stored on each ethereum node. Thus, its memory is similar to RAM, while its storage is similar to hard disk drives or persistent databases.See MyCrypto's article for more details on how the ethereum virtual machine works.Writing smart contractsAlthough all smart contracts use EVM, most smart contracts are not written by hand in EVM bytecode, just as most JVM bytecodes are not written by hand. Instead, several high-level languages are available to write smart contracts in ethereum. The most popular language is sollion, along with Vyper, a programming language for EVM. The following figure contains a very simple example of a solfat smart contract.
Interact with smart contractsSmart contracts in ethereum exist as bytecode on the ethereum network. This means compiling soloffshore code into bytecode and then deploying it to the network by sending a deployment transaction. This is a special kind of transaction where there is no receiver, but the bytecode is the transaction data.These deployed contracts exist only in the network as "shards" of EVM bytecode and are almost impossible to use alone. To "hook up" with them, you need to provide an application binary interface (ABI) that includes a list of all common functions and their parameters. To give users a better understanding of these contracts, services like Etherscan help validate the contract source code so that users can check the code before using the contract.All smart contracts can be accessed directly by connecting to the ethereum node and using its json-rpc interface. However, many smart contracts are accessed by front-end applications that connect to the node and manage the ABI. This can be done through one of the many different eethernet SDKS (such as web3.js or ethers.js) that can call json-rpc in the background. This provides a better experience for contract users, which is equivalent to visualizing the most difficult part.Smart contracts can be interacted with in two different ways: Calls and transactions(the Transactions). The call is a local call to the contract function that does not broadcast anything to the blockchain. Therefore, the calling process is "read-only" and no changes can be made to the state of the contract and no fees are incurred. The transaction is a real "write operation" that does broadcast to the network, is included in the blockchain, and incurs miners' fees. In the case of the ERC20 token, the token balance is retrieved by calling, while the token is transferred by initiating the transaction.Smart contracts interoperateThese properties of ethereum (with turing-complete EVM and persistent storage) allow the creation of any type of decentralized application running on the chain. A good example is the DeFi ecosystem, which includes applications such as Maker, Uniswap, and Compound, as well as the ERC20 and ERC721 token standards. These applications allow for the complex functionality of an unlimited number of dynamic actors.
Figure: DeFi interoperability in rDai
Most importantly, smart contracts themselves can become "participants" in other smart contracts, enabling powerful integration and composition among these contracts. For example, holding token balances and lending them to Compound or smart contracts with the Uniswap exchange, or using rDai to automatically invest in DAI and contribute accrued interest to charities.Although smart contracts can interact with each other, every transaction on the chain must come from an external account. Thus, the interaction between ethereum smart contracts still has to be triggered by the user through the initial transaction. After this initial trigger, the interaction between contracts is similar to direct access.In other words, a smart contract can invoke a "read-only function" of another smart contract or trigger a "write operation" (trade). Since only external accounts can trigger transactions, transactions between smart contracts are called internal transactions or message invocations to distinguish them from user-initiated transactions.Bitcoin: stateless and simpleAll bitcoin transactions, including periodic transfers, are supported by a stack-based programming language called bitcoin Script. While ethereum's EVM was designed for turing-complete and interoperable smart contracts, the bitcoin script intentionally adds restrictions and works in fundamentally different ways.Explain the bitcoin scriptLike EVM, the bitcoin script USES a Stack to hold values and perform calculations on them. But unlike EVM, the stack is the only data location available in the bitcoin script. This means that it is difficult to store multiple values for later contract execution. More importantly, this means that it is not possible to store or modify values that still exist during contract execution (but EVM can).This is the biggest difference between ethereum's smart contract and bitcoin. Ethereum's model is stateful, while bitcoin is stateless. In layman's terms, ethereum can be thought of as akin to a common imperative variable data programming paradigm, while bitcoin is akin to an unchanging data paradigm.The bitcoin model allows transactions to be validated independently and much more efficiently, making it easier to parallelize and shard transactions. However, without any variable data store, it is more difficult to create complex smart contracts on bitcoin like ethereum, where, for example, the ERC20 contract must track token balances and make changes.In addition to these status differences, there are other factors that limit the complexity of bitcoin smart contracts. Notably, bitcoin scripts lack support for certain arithmetic functions and for any kind of loop or recursion. The contract also has a valid size limit of 520 bytes and a maximum of 201 opcodes.Most smart contracts on bitcoin fall into a few simple categories. For example, a multi-signed contract that can be used by multiple participants, or a hashed time locking contract (HTLC).For example, if you buy a video from me, and the video is accessed by password, then in the transaction contract, I change the access password of the video into one of the keys. Once you know (you get the video), the money is paid to me, and the whole transaction must be completed within a set time, beyond which the contract will automatically trigger.And because these contracts on bitcoin are so simple, most of the value is captured by combining different contracts with other de-linking application logic. In this way, simple contracts can be combined to create complex solutions, such as lightning networks or cross-chain auctions.Explain bitcoin transactionsEvery transaction in bitcoin is made through what is known as "transaction output." When these transaction outputs are available in an account, they are called unused transaction outputs (UTXOs). These UTXOs are locked by a locked script (or scriptPubKey) and are specified for use. When you try to use UTXOs, an unlocking script (or ScriptSig) is provided, and these scripts perform calculations together. The transaction takes effect only if the script executes error-free and the resulting value is correct (TRUE).Like EVM, all bitcoin nodes execute these scripts to verify transactions, but the bitcoin blockchain does not have a concept of Gas cost, so miners are paid per byte of transaction data. To limit the amount of work that nodes have to do, restrictions have been added to some of the more intensive script operations.Interact with smart contractsSmart contracts in bitcoin are written using P2SH mode. The locking script in P2SH mode contains a script hash and needs to provide the full script (called the redemption script) as well as the unlocking script for the redemption script. The following figure shows this pattern.
Figure: P2SH mode
The P2SH pattern was introduced to simplify the use of complex scripts (the traditional mechanism is P2PKH), compiling complex locking scripts into a simple script with a 20-byte hash, just as the bitcoin address is a Base58 encoded 20-byte public key. The biggest difference between P2SH and traditional P2PKH is that the person who sets the transfer condition changes from sender to receiver. Multiple transactions, such as multi-signature transactions, can be implemented by adding various roll-out conditions to the redemption script.Bitcoin nodes validate these smart contract transactions in two phases. First, hash the call script and check against the hash values in the lock script. If they match, unlock the call script with the lock script as if the call script were the original lock script.Because only the bytecode hash values are stored on the bitcoin chain, the full bytecode must be stored outside the chain and included in any unlocking script executed by the contract. As a result, the "deployment" of a bitcoin smart contract is free, but it costs more to execute the contract later. In contrast, ethereum was relatively expensive to initially deploy and cheap to execute later contracts.These differences in deployment encourage a combination of the two smart contracts. A good example is LocalCryptos, which supports unmanaged local transactions of ethereum and bitcoin. For ethereum, it USES a large smart contract to track all transactions, while for bitcoin, it creates a separate contract for each transaction.Writing smart contractsWhile ethereum has a number of high-level languages that can be compiled into EVM bytecode, bitcoin has received less attention. While the systems that can be built with bitcoin scripts are complex, the contracts themselves are often simple. Therefore, there is little need to abstract out the underlying system. And because bitcoin contracts have size limits and high costs for each additional byte, it's important to keep them "as small as possible."Although these high-level languages are not very important in bitcoin, they do exist. Ivy is the "most elaborate" high-level language in bitcoin, created by Dan Robinson in 2017. The following figure shows an example of a smart contract written with Ivy. If the recipient fails to use the contract in a timely manner, the contract may be used to send payments that can be recovered by the sender.
Recently, several Blockstream researchers released Miniscript, a language that focuses on the analysis and composability of smart contracts rather than abstracting the underlying system. Given the often lack of abstract complexity in bitcoin contracts, this seems like the right path.Bitcoin cash: composable functionalityThis is ethereum on the one hand, which is capable of creating many powerful and useful smart contracts that reside entirely in the ethereum chain, and, because of its Stateful nature, raises the question of scalability. On the other hand, the Stateless model of smart contract of bitcoin allows independent and simple verification of smart contract transactions, but its scripting system limits the practicality of contracts.Before the fork, Bitcoin Cash and Bitcoin have the same history, so their underlying scripting systems are functionally identical, and Bitcoin Cash benefits from these same aspects. Since then, a large part 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 basic attributes that allow for stateless validation of bitcoin.BCH feature upgradeTo understand the possibilities of bitcoin cash smart contracts, we need to look at its biannual network upgrades. These network upgrades will be performed in May and November each year since the original hard fork in 2017. In particular, we discussed the changes to the bitcoin script engine, although some other improvements have been made, such as the Schnorr signature.In bitcoin's early days, it was banned because some opcodes were unsafe to use. In the first year after the bitcoin cash fork, the developers of the bitcoin-abc node resolved these issues and reintroduced slightly modified opcodes for the functionality, as shown below. Most importantly, the upgrade makes it possible to encode and decode structured data in bitcoin scripts.
Photo: BCH enabled new opcodes in May 2018
Six months later, another new opcode was released in a November 2018 upgrade to the bitcoin cash network. This includes the update OP_CHECKDATASIG, which allows users to verify the signature of any message in the bitcoin script. If we combine the script updates that came out in 2018, they can be used to bring new and useful smart contract features to bitcoin cash.Writing smart contracts
Compared to the original bitcoin script, the new power of bitcoin cash adds a lot of additional complexity to its smart contracts. This makes it all the more important to have an ecosystem that provides a higher level of abstraction through high-level languages, SDKS, and tools.Two of the big projects currently working on this issue are Spedn (created by the pen name Tendo Pein) and CashScript (created by Rosco Kalis, inspired by ebt's solorti). While they are still actively in development, these tools make it easier to process smart contracts in bitcoin cash. The CashScript snippet is used to illustrate some of the features below.OraclesWhen past bitcoin script updates are combined, they allow you to bring external data into the smart contracts of bitcoin cash through trusted predictors. Structured data can be encoded as byte arrays and signed by the oracle provider. Smart contracts can then validate signatures and decode structured data.
You can view this example in the HODLVault sample contract below. The contract enforces hoexchange until a certain BCH/USD price is reached. The required BCH/USD price feed is published by the oracle provider and passed to the contract by the user. To increase dispersion, smart contracts can be set up to use multiple data sources instead of trusting a single centralized service.CovenantsThe second big use case is a technique called Covenants, named after the term used in property law to restrict the use of objects. In the case of bitcoin cash, it limits the use of currency in smart contracts. So while smart contracts in bitcoin can only authorise general currency spending, bitcoin cash contracts can impose restrictions on the amount that can be spent or the identity of the payee.When transferring bitcoins, the sender must provide a signature to authorize the transaction. To generate this signature, the sender signs the hash representation of the transaction. This hash is called Sighash, and the actual transaction data is contained in the original Sighash image.We can access the Sighash data by using OP_CHECKSIG and OP_CHECKDATASIG with the same signature. The data format can be checked in the specification and included in the image below. One important field is scriptCode, which contains the bytecode for the smart contract itself. Another is that hashOutputs allow users to enforce the outputs of trades.
Photo: bitcoin cash Sighash data format
It's nice to know how a guaranteed contract works technically, but CashScript abstracts out most of the complexities associated with contracts. When writing a smart contract with CashScript, these fields are easy to obtain without having to perform the steps of manually verifying and decoding the original Sighash image.The first smart contract to use the surety technology is Licho's Last Will, a smart contract that allows users to transfer the deceased's property to their own. The contract defines three different functions. The first allows the successor to claim the money after 180 days. The second allows the owner's ColdKey to be spent in any way. The third allows the owner's Hot Key to refresh the 180-day period by forcing the full contract balance to be sent round.The Last Will for the CashScript version is included below, but the original version was written by Spedn and can be viewed here.
This is one of the simple examples of a useful warranty contract, but a warranty contract can achieve even more complex functionality. After the Last Will deal was signed, founder Karol Trzeszczkowski went on to create Mecenas, a company that enforces regular payments like Patreon.The warranty contract was originally proposed in the paper "Bitcoin Covenants", which required a new OP_CHECKOUTPUTVERIFY. Other Suggestions follow, such as OP_CHECKTEMPLATEVERIFY or OP_CHECKSIGFROMSTACK. The latter is very similar to the implementation of the covenant for bitcoin cash. Learn more about securing contracts in Tendo Pein's article.Simulation status (Simulated state)Look at the last will and testament contract. It may be valuable to change the inheritor when the contract is in place. Since we can force sending to the current contract by looking at the bytecode of the current contract, we can force sending to a slightly different contract by changing this bytecode slightly. You can create a function that sends the balance of the entire contract to a contract with exactly the same bytecode but with a different successor.We can only do this with constructor arguments of a known size (for example, 20 bytes). The constructor argument is always the first data in the contract bytecode, which is how we can easily replace old data with new data. The inheritor is an argument to the first constructor, and its size is 20 bytes, so we can apply the technique, as you can see below.
Using this technique, you can change certain variables in a contract while keeping the same rules in the contract. We call this "simulation state" because it provides some of the benefits of contract state and there are no extensibility issues of Stateful systems like ethereum. There are other downsides to this approach, since trade-offs must be made somewhere.The main problem is that we didn't actually change any of the variables in the original contract, because that's impossible because of the stateless nature of bitcoin cash. Instead, create a new contract (with a new address) and transfer the full balance to that new contract. This can cause UX problems due to the new address, but can be mitigated by having good application-level abstractions on these smart contracts.Replacing these variables inside the bytecode can be cumbersome, especially when trying to replace deeper variables inside the bytecode. This functionality should be abstracted in a high-level language to automatically generate new bytecode by providing new parameters. The abstraction might look something like this:
Much of the abstraction comes at the expense of larger contracts, leading to higher fees. But the transaction fees for bitcoin cash are usually low, so it's a combination of the two. But bitcoin cash has the same size limits as bitcoin, so these abstractions do make it harder to stay within those limits. This results in many developers having to manually optimize the compiled bytecode.conclusionEach cryptocurrency is weighed in its smart contract system. Ethereum is the most versatile and commonly used smart contract platform. Bitcoin offers a more basic version of the smart contract through its stateless scripting system, which is more efficient at validating but less functional. Bitcoin cash shares the same foundation as bitcoin, but adds new features that try to compromise between effective verification and useful smart contracts. In the end, everyone moved toward a similar goal.Looking to the futureWritten in the fourth quarter of 2019, this article reflects the current state of the platform. Cryptocurrencies are a fast-paced field, so people involved in these platforms are always working on improvements that could change the landscape of the ecosystem.Ethereum is working on a major ethereum 2.0 release, with phase 0 scheduled to launch in the first quarter of 2020. Ethereum 2.0 is intended to address ethereum 1.x's performance issues by moving to proof of interest, implementing fragmentation and other improvements. The full roadmap for ETH2.0 is yet to be established and could take years to roll out. However, if this major update achieves its goals, it could provide strong support for ethereum.The smart contract research in bitcoin aims to further improve the efficiency and privacy of smart contracts, including solutions such as Taproot and unscripted scripts. Bitcoin cash, on the other hand, continues to work on enabling other smart contracts and making these changes more accessible.The author | Rosco Kails
Compile | first class (www.First.VIP)Source:weixin.qq.com
Welcome to join the official BlockBeats community:
Telegram Subscription Group: https://t.me/theblockbeats
Telegram Discussion Group: https://t.me/BlockBeats_App
Official Twitter Account: https://twitter.com/BlockBeatsAsia