The first well known application of blockchain technology was Bitcoin, a peer-to-peer system custom-designed to make value transfer function without relying on a central party. It worked really well and still works today as arguably the most robust deployment of blockchain applications. But blockchain will never have made to the forefront of the technological innovations were it not for a number of key technologies that were added to the limited functionalities in Bitcoin, and smart contracts was a critical foundation of that revolution. There are many business advantages to using smart contracts, including trust, transparency, security, autonomy and accuracy. This article will focus on explaining what a smart contract is, how it works, and the various approaches for deployment.
In a decentralized world, trust is not an essential ingredient to make things work. Blockchain relieves participants from having to rely on a centralized party to operate truthfully. No more entrusting your business’ livelihood to a 3rd party intermediary in hopes they will always do the right thing. With blockchain, every participant is in control, yet no one has total control. There are a number of technologies employed by blockchain designs to materialize this self-governance. Smart contracts are so far the most mature and widely adopted technology.
A smart contract refers to a piece of computer program that gets executed by a quorum of blockchain nodes independently in order to record the latest program state. This may seem complex, so let’s take some time to unpack it.
Smart contracts are executable programs. They are usually written in high-level computer programming languages in order to represent arbitrary business logic or pre-determined criteria to trigger transfer of values. For a smart contracts engine to be effective in supporting a wide range of use cases, the language needs to be Turing complete, a fancy computer science term meaning the language can be programmed to solve any computation problem. For this reason, even though it is possible to program in Bitcoin scripting language, because it is very limited in functionalities, Bitcoin is not considered to have smart contracts. Ethereum first introduced smart contract support, ushering in an era of rapid innovations to solve some of the most challenging problems in technology and society alike.
Smart contracts get executed by the blockchain nodes, as a result of processing transactions that are submitted by the user. A blockchain transaction has a designated target smart contract function, a payload that contains input values to the function call, and always signed by the submitter. A transaction can be submitted to any node in the blockchain network, which broadcasts it to the entire network so all the nodes will see the transaction. At some point, the transaction gets processed by each individual node using the executable program in the target smart contract. If the transaction execution is successful, the internal state of the blockchain will be updated. A smart contract may also consider the input to be invalid and reject the transaction as failed, in which case the state is not affected.
Smart contracts must be independently executed by a quorum of blockchain nodes. Unlike traditional databases, blockchains are decentralized. Every node assumes others are potentially malicious and never trusts states maintained by other nodes in the network. Instead each node maintains its own state database by executing the transactions themselves using the smart contract code.
How does this independent execution mechanism in every node guarantee that all nodes end up with the same state? All nodes must have the same beginning state, same input values and the same execution logic. If all three parts are identical, the end state is guaranteed to be identical. The chain of blocks with the linked hashes each representing the full list of transactions (input values) and current states (beginning state), plays a critical role in forming consensus among the blockchain nodes. Finally, different blockchain protocol employ different techniques in guaranteeing the same smart contract code are executed to process the transaction. In Ethereum, smart contract code themselves are stored on-chain directly as state. In Hyperledger Fabric and Corda, the other leading enterprise blockchain protocols, contract code are stored off-chain, an on-chain hash is used to represent the intended version of the smart contract.
The main purpose of smart contracts is to maintain program states. State is an arbitrary piece of data that gets updated by executing a transaction. In this sense, a blockchain can be conceptualized as a database, although it’s designed to lean heavily toward data consistency and immutability, at the cost of speed and query support. Almost all blockchain protocols are designed to follow a state transfer conceptual model.
Each smart contract maintains its own set of states. Most transactions submitted to a blockchain target a smart contract, with the exception of pure value transfers that do not involve smart contracts. Once a transaction is executed, the target smart contract updates its state. A smart contract can call another smart contract, in order to query the downstream contract’s state or update it.
The best way to understand smart contracts is to think of it as program functions: there are inputs, logic to process the inputs, and output. Execution of smart contracts often results in updated states.
The logic inside smart contracts will determine if a transaction is valid or not. Examples of an invalid transaction may include not operating on the right level of beginning state, such as attempting to spend tokens without having sufficient balance. Only valid transactions result in updated states. Invalid transactions are either rejected by the network from being included in the blockchain, or included but marked as failed, depending on different blockchain designs.
Smart contracts may also publish events as a way to inform the outside world. Event listeners are notified when the block containing the transaction gets committed to the blockchain on the node.
A smart contract may have more than one public function that can be invoked by a transaction. Each function may either cause the state to be updated or simply returns the latest state. For example, a standard fungible token smart contract typically has the following functions useful in scenarios such as payments and commodity trading:
Functions that update states (require transactions to invoke):
transferFrom(from, to, amount)
Functions that query the latest states (do not require transactions to invoke):
If the state needs to be updated, it must be done via a transaction and be processed through the full transaction cycle. Due to the decentralized nature of blockchain architecture, transactions must be handled by a consensus mechanism, so that the system ensures all the copies maintained by the blockchain network’s participating nodes have identical records.
On the other hand, querying for the latest state without updating it can be accomplished much faster and involves only a single node in the network. Any node that has the smart contract installed locally can execute the query request and return the result by reading from the locally maintained state database.
Before a smart contract can process transactions, it must be first deployed on the blockchain. The deploy process must guarantee that all blockchain nodes have exactly the same code. Different blockchain designs handles this requirement differently, but there are in general two approaches: save the contract code itself in the blockchain which guarantees global consensus (on-chain), or let each node owner decide if the node should have the code installed locally, and use a hash-based commitment in the blockchain as reference for validating the code integrity (off-chain).
Hyperledger Fabric requires an elaborate administration scheme to first install the chaincode onto a blockchain node, and instantiate it globally in the chain via a special type of transaction. Because of the Fabric’s unique consensus framework design, only a selective subset of node, called endorsers, need to have the chaincode installed. Details of this design is beyond the scope of this book, but you can think of it as committee based governing rather than popular votes. Once a chaincode has been instantiated, there is a chain-wide common view to which vote should be executed when that chaincode is called. As a result, execution of the chaincode is guaranteed to be consistent on every endorser node.
Enterprise Ethereum, with the public Ethereum inheritage, offers a simple one-step process to deploy smart contracts. The deployment is done via a transaction, making it a chain-wide operation by nature. Code for the smart contract is saved on-chain as state. As a result, all nodes are guaranteed to have access to the code and they all have the same version.
Corda adopts a peer-to-peer transaction coordination architecture, without utilizing a globally maintain common ledger of transactions. Because of this, smart contract deployment are done on a per-node basis based on the need to perform bi-lateral or multi-lateral transactions. Similar to Fabric, the administrator of the Corda node is responsible for ensuring that the smart contract required to process a transaction has been installed on the node.
Despite the name, smart contracts are neither smart nor legally binding.
“Smart” is typically associated with artificial intelligence that is built on massive amounts of data and employs computation intensive algorithms. Smart contracts exists to build trust with decentralization, in that multiple parties execute the same code and maintain the same state, independently. Efficiency is sacrificed for security through duplication. This means smart contracts is not a great place to build intelligence through machine learning, or carry out any amount of deep analytics.
Smart contracts are not typically considered legally binding either. Besides duplicating computation, smart contracts also results in state data being stored in every node. When considering what kind of data should be maintained by smart contracts, best practice is to only use it to keep track of information that either represents commitment of data stored somewhere else, so that they can not be changed after the fact, or information that need to be updated. Legal documents typically are overly verbose and have a lot of boilerplate content. Saving the whole legal document inside smart contracts would be a very inefficient way to utilize blockchain.
Despite some limitations, smart contracts are key to many use cases (check out this post for 5 examples of smart contracts) and provide us with an opportunity to make transactions and processes more streamlined and automated. Smart contracts are here to stay; the steady increase of deployments year over year only emphasizes their significance within the blockchain ecosystem. The open-source community has fully embraced the concept and have developed many high-quality libraries in various smart contract languages. OpenZeppelin, for example, is widely utilized in the Solidity developers community for Ethereum-based blockchains.
For more details on how smart contracts get utilized in building decentralized consortiums, visit our Solutions page. Ready to start build with smart contracts? Learn more about Kaleido's smart contract management solutions, sign up for a free trial or reach out to the team for a free consultation.
Kaleido is your easy button for developing next era blockchain based business applications.