14. Extending the Ethereum Protocol

In the previous chapters of this book, you learned about the power and also the limitations of Ethereum. Ethereum is one of the first and certainly the most popular blockchain smart contract platform. It is a protocol with multiple open source implementations from the community and has a robust software upgrade process known as Ethereum Improvement Proposals (EIPs). However, as a big organization with many stakeholders, Ethereum improvement is a slow process. As a “world computer,” Ethereum is also unlikely to optimize for specific applications.

I believe there are opportunities for many different public blockchains. Each of them will optimize Ethereum for specific application protocols. However, all of them will need to fix at least a few of Ethereum’s most glaring problems, as described here:

  • The Ethereum Virtual Machine (EVM) has many limitations. While the EVM is Turing complete, it is inefficient to implement many algorithms. For example, it is currently impossible to implement public-private key applications on Ethereum because a single public key infrastructure (PKI) encryption operation will consume Ethereum gas fees worth hundreds of dollars. Even basic string operations are slow and expensive with the standard EVM.

  • Ethereum is too slow. At about 20 transactions per second (fewer for smart contract transactions), Ethereum is not suitable for most application use cases.

  • It does not yet scale. With the Ethereum public blockchain in 2019, the more people who use it, the worse the user experience gets.

  • It could be unsafe, especially for beginners. It is easy to send Ethereum assets to the wrong address or lose assets because of poorly written smart contracts.

  • Smart contract programming is hard. Code audits have shown that Ethereum smart contracts average about 100 obvious bugs per 1,000 lines of code. That is an astonishing number for applications managing financial assets. In contrast, Microsoft business applications, which are a lot less mission critical, average about 15 bugs per 1,000 lines of code.

In this chapter, I provide an overview of the technical approaches that could potentially alleviate these Ethereum shortcomings.

Fully Compatible, Yet Faster

Second State creates Ethereum-compatible virtual machines that can run on a variety of underlying consensus mechanisms. This allows developers to choose the most suitable blockchain to deploy their applications. For example, the virtual machine can run as a Tendermint application (see Chapter 20) to take advantage of the Byzantine fault tolerant (BFT) Tendermint consensus engine, as well as the various delegated proof-of-stake (DPoS) mechanisms that can be implemented on top of Tendermint (e.g., the CyberMiles public blockchain).

The performance impediment of Ethereum is primarily a result of its proof-of-work (PoW) consensus mechanism. A huge amount of meaningless computation must be performed for each block of data that can be added to the blockchain. An Ethereum-compatible blockchain can easily achieve 100× performance gain by simply replacing the PoW module with a DPoS or delegated Byzantine fault tolerance (DBFT) module. For example, on the CyberMiles blockchain, consensus is reached by 19 validator nodes (i.e., super nodes) before a new block is created. The validators are elected by CyberMiles token holders and are required to run high-performance hardware in tier 1 data centers.

Note

Being Ethereum-compatible, all Ethereum scalability solutions are also available on EVM-based blockchains. This allows users to take advantage of extensive research conducted by the Ethereum community and contribute improvements back to the Ethereum community. A great example here is the Plasma protocol, which aims to build layer 2 networks to scale Ethereum to millions of transactions per second.

Furthermore, as we will discuss in the next section, the virtual machine can offload complex computational tasks to native library functions. That allows for vastly improved smart contract execution speed and much lower gas costs for such tasks. For many operations, the native functions could represent four to six orders of magnitudes in terms of performance gains (see Chapter 18 for more).

Smart Enhancements to the EVM

Lity is a new programming language extension to Solidity, with support for its features in an extended EVM version. Here are some of Lity’s features:

  • Lity provides a new language keyword to call native library functions written in C or C++. This is known as the libENI framework. Through libENI, each Lity-based blockchain can be customized and optimized for address-specific application scenarios. I will discuss libENI in Chapter 18.

  • Lity supports fixed-point math and sophisticated math operations. It provides deterministic results for fractional number operations, which was a key limitation in Ethereum.

  • Lity supports timer-based operations scheduled for a future time. The scheduled execution is crucial for many classes of use cases, such as interest and dividends payment, trust and will, delivery confirmations, and so on. This is also called long-running contracts.

  • Lity supports “trusted” operations that can be invoked only by current validators or super nodes of the underlying blockchain. This allows for trusted smart contracts on the blockchain that can provide a first-class substitute for community-based oracles, which connect the blockchain to the outside world.

  • Lity supports secure random numbers generated by validators or super nodes of the underlying blockchain.

  • Lity supports alternative mechanisms for paying for gas fees in blockchains that require gas for executing smart contracts.

  • Lity supports a new type of “upgradeable” smart contract. Those contracts only expose the function interfaces to the world at the contract address. The actual implementation of those functions are proxy contracts deployed at other addresses on the blockchain. Lity supports virtual machine operations to change the smart contract’s proxy implementation. That allows developers to upgrade or fix critical bugs on smart contracts.

  • Lity supports new language constructs such as rule expressions so that application developers can build business rules directly into the smart contract (see Chapter 17). Those are commonly known as domain-specific language (DSL) features.

Next, let’s look into some concrete examples from this list.

Trusted Oracles

One of the most important services on blockchains is the oracle service. An oracle is typically a smart contract that makes external data (i.e., off-chain, real-world, or cross-chain data) deterministically available on the blockchain. It provides a single source of truth for off-chain states and hence allows blockchain nodes to reach consensus.

The traditional oracle is highly centralized and goes against the spirit of the decentralized blockchain. For example, Fedex might establish a delivery service oracle that provides delivery status of packages. A weather station might establish a weather oracle. To use those oracles, blockchain users and dapps must trust the entities behind those oracles.

A second approach for oracles is to create a community-based cryptoeconomic game for members of the community to compete and provide the truth in a smart contract. Examples of such oracles include the BTC Relay to provide information about the Bitcoin blockchain, and the Ethereum Alarm Clock to provide time.

Lity, however, takes a different approach to create trusted smart contracts and make oracles first-class citizens. This approach works on DPoS blockchains. In a DPoS blockchain, the validators (super nodes) are trusted entities. They must stake a large number of tokens from their own account and from their supporters/community. Those tokens are subject to slashing and confiscation if the validator misbehaves. So, if a smart contract can be updated only by current validators, data from this contract should have a high level of trust on the DPoS blockchain.

In the Lity language, a built-in function called isValidator checks whether the current transaction sender/function caller is a validator. It works on any Lity-based DPoS blockchain.

// isValidator is a built-in function provided by Lity.
// isValidator only takes one parameter, an address,
// to check this address is a validator or not.
isValidator(<address>) returns (bool returnValue);

Then with the ValidatorOnly modifier, we can construct smart contracts that act as trusted oracles on the blockchain.

contract BTCRelay {
  uint[] BTCHeaders;
  modifier ValidatorOnly() {
      require(isValidator(msg.sender));
      _;
  }

  function saveBTCHeader(uint blockHash) ValidatorOnly {
    BTCHeaders.append(headerHash);
  }

  function getBTCHeader(uint blockNum) pure public returns (uint) {
    return BTCHeaders[blockNum];
  }
}

Secure Random Numbers

Getting secure random numbers is a significant challenge for blockchain smart contracts. Lity pioneered an approach to access a random number series from a seed in the current block header. The random seed is based on the hashes of all transactions in the current block, and it is extremely difficult to manipulate even for the validator node that builds and proposes the block.

Inside the smart contract, you can access the random number series by simply calling the built-in function rand(). The following is an example:

pragma lity >=1.2.6;

contract RandDemo {
  uint x;
  function getRand () public returns (uint) {
    x = rand();
    return x;
  }
}

You should not call rand() in a view or pure function. If the random number does not need to be recorded on the blockchain (i.e., outside of a transaction in a view function executed on a single node), it does not need to be generated by the blockchain. The calling application should simply generate a random number locally, which is much cheaper in terms of resource consumption.

Alternative Gas Fees

One of the major hurdles of blockchain application adoption is that end users are asked to pay a gas fee to perform certain functions on the blockchain. The gas mechanism is crucial for the blockchain’s security, as it prevents DoS attackers from overwhelming the blockchain nodes with computationally intensive requests. However, the gas requirement also means that new end users must be taught to purchase cryptocurrencies and manage private keys before they can even start to use decentralized applications.

Lity provides an alternative approach to onboard new users to blockchain applications. Through the freegas keyword, the smart contract owner can designate a contract function that should have gas fees paid by the owner herself. When the user calls those functions, she would indicate that she is not paying gas by setting gasPrice to 0.

  • If the gasPrice=0 transaction calls a function that is not freegas, the transaction will fail.

  • If the gasPrice=0 transaction calls a freegas function in a contract that does not have a balance, the transaction will fail.

Of course, the caller can specify a regular gasPrice (e.g., 2Gwei), and in that case, the caller pays for gas even if the contract function is freegas.

If the gasPrice=0 transaction calls a freegas function in a contract that has a sufficient balance, then the function executes, and the gas fee is deducted from the contract address. The caller pays nothing, and the contract pays gas at the system’s standard gas price.

Note

There is a configurable rate limit for making gasPrice=0 transactions. The blockchain node software can prevent users from exploiting the system by sending a lot of free transactions.

The following is an example. On the CyberMiles blockchain, if an end user calls the test function with gasPrice=0 and the contract address has a CMT balance, the transaction’s gas fee will come out of the contract address.

pragma lity >= 1.2.7;

contract FreeGasDemo {
  int a;
  function test (int input) public freegas returns (int) {
    a = input;
    return a;
  }

  function () public payable {}
}

The payable function is important as it allows the contract to receive funds that will later be used as gas. Figure 14.1 shows the freegas transaction in action on the CyberMiles public blockchain.

image

Figure 14.1 The caller makes a freegas transaction by setting gasPrice to zero.

Safety First

Through language and virtual machine enhancements in Lity, we can proactively prevent many classes of security problems. The following are some examples:

  • The Lity compiler automatically checks the structural signature of the smart contracts it compiles. If it detects the smart contract is likely to be one of the popular types (e.g., an ERC20 or ERC721 token contract), it will check that all required methods are implemented and the contract is free of common errors. The Lity compiler throws errors if it sees a noncompliant ERC20 contract (learn more in Chapter 15).

  • The Lity compiler checks for known code issues and bug patterns, such as the ERC20 contract’s compliance to the ERC223 safety standard. It throws warnings and can attempt to automatically fix some most serious issues.

  • The Lity language provides access to secure random numbers generated by blockchain validators, when the consensus mechanism allows.

  • The Lity virtual machine automatically checks for unsafe operations at runtime, such as integer overflow, which is a common ERC20 issue that had resulted in billions of dollars of value destruction. When a contract encounters an integer overflow in Lity runtime, it will stop execution with an error instead of proceeding with the overflowed buffer, as Ethereum does today. This eliminates a whole class of errors.

As an open source collaborative effort, the Lity project aims to continuously bring updates to those security features, such as support for new ERCs and new code vulnerability patterns, to the community.

Conclusion

In this chapter, I discussed how the Lity project extends the Ethereum protocol both at the consensus layer and at the virtual machine layer to create Ethereum-compatible blockchains that support much needed performance/security/usability enhancements as well as experimental features. In the next several chapters, we will look into application design and development on the Lity language and virtual machine.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.155.100