11email: {firstname}.{secondname}@data61.csiro.au
22institutetext: School of Computer Science and Engineering, University of New South Wales, Sydney, Australia
33institutetext: University of Lugano, Lugano, Switzerland
33email: [email protected]
44institutetext: Technical University of Munich, School of CIT, Munich, Germany
44email: [email protected] 55institutetext: Fraunhofer-Gesellschaft, Munich, Germany
An Extended Pattern Collection
for Blockchain-based Applications
Abstract
Blockchain is an emerging technology that enables new forms of decentralized software architectures, where distributed components can reach agreements on shared system states without trusting a central integration point. Blockchain provides a shared infrastructure to execute programs, called smart contracts, and to store data. Since blockchain technologies are at an early stage, there is a lack of a systematically organized knowledge providing a holistic view on designing software systems that use blockchain. We view blockchain as a component of a bigger software system, which requires patterns for using blockchain in the design of the software architecture. In this paper, we collect a list of patterns for blockchain-based applications. The pattern collection is categorized into five categories, including interaction with external world patterns, data management patterns, security patterns, structural patterns of contracts, and user interaction patterns. Some patterns are designed considering the nature of blockchain and how blockchains can be specifically introduced within real-world applications. Others are variants of existing design patterns applied in the context of blockchain-based applications and smart contracts.
Keywords:
Blockchain Smart contract Pattern.1 Introduction
Blockchain is the technology behind Bitcoin [17], which is a digital currency based on a peer-to-peer network and cryptographic techniques. The blockchain provides immutable, append-only, shared data storage, which only allows inserting transactions without updating or deleting any existing ones, thus preventing any tampering or revision of previously stored data on blockchain as long as the majority of the network peers do not agree to allow such revision. The blockchain enables decentralization as new forms of distributed software architectures, where components can reach agreements on the historical log of shared states for decentralized and transactional data sharing, across a large network of untrusted participants without relying on a central integration point.
Financial transactions are the first, but far from the only use case being investigated for blockchain. Many start-ups, enterprises, and governments [20] are exploring blockchain-based applications in areas as diverse as supply chain, electronic health records, voting, energy supply, ownership management, and protecting critical civil infrastructure. Despite of the wide array of interest in blockchain technology, there is a lack of a systematic and holistic view when applying blockchain in the design of software applications.
Previous work has characterized blockchain from a software architecture perspective as a software connector [26] that provides a shared infrastructure for storing data and running programs (known as smart contracts). Blockchain guarantees unique properties including immutability, non-repudiation, data integrity, transparency, and equal rights. It also has two main limitations, namely, lack of privacy and poor performance [26]. The taxonomy presented in [27] discusses such properties for different types and configurations of blockchain technology. To better leverage the positive properties of blockchain and avoid or reduce the impact of its limitations, more architectural guidance on blockchain-based applications is needed.
In this paper, we present a set of patterns for the design of blockchain-based applications. In software engineering, a design pattern is a reusable design solution to a problem that commonly occurs within a given context during software design [4]. A design pattern defines constraints that restrict the roles of architectural elements (processing, connectors and data) and the interaction among those elements. Adopting a design pattern causes trade-offs among quality attributes. Our pattern collection includes four patterns about interaction between blockchain and the external world, four data management patterns, four security patterns, five structural patterns of smart contract and two user interaction patterns. The pattern collection provides an architectural guidance for developers to build applications on blockchain.
The remainder of the paper is organized as follows. Section 2 presents a background of blockchain and smart contracts. Section 3 gives an overview of the pattern collection, followed by detailed patterns discussed from Section 4 to Section 8. Related work on blockchain-based applications and design patterns is discussed in Section 9. Section 10 concludes the paper and outlines the future work.
2 Background
2.1 Blockchain
Blockchain is a data structure of an ordered list of blocks, where every block "chained" back to the previous block through containing a hash of a presentation of the previous block. Every block on blockchain contains a list of transactions (possibly empty). A transaction is a data package that stores information for money transfer, like sender, receiver, and monetary value, or the (compiled) code of smart contracts, or parameters of function calls of smart contracts. Due to the security properties of hash function, the historical transactions on blockchain can not be deleted or altered without invalidating the chain of hashes. In addition to the design of the data structure, there are computational constraints and consensus protocols applied to the creation of blocks. All together, blockchain can in practice prevent revision and tampering of the information on blockchain.
When using a blockchain, one design decision is the deployment, i.e. , whether to use a public blockchain, consortium/community blockchain or private blockchain [27]. Most cryptocurrencies use public blockchains, which can be accessed by anyone on the Internet. Using a public blockchain results in better information transparency and auditability, but sacrifices performance and has a different cost model compared with a conventional data storage. It costs monetary value to store data or execute code on a public blockchain. In a public blockchain, data privacy relies on encryption or cryptographic hashes. A consortium blockchain is used across multiple organizations. The consensus process in a consortium blockchain is controlled by a set of pre-authorised nodes. The right to read the blockchain may be public or may be restricted to specific participants. In a private blockchain network, write permission is kept within one organization, although this may include multiple divisions of a single organization.
2.1.1 Properties
The data contained in a transaction on blockckchain is seen as immutable in practice. The chain of immutable cryptographically-signed historical transactions provides non-repudiation of the stored data. Cryptographic techniques used by blockchain support data integrity, the public access provides data transparency, and equal rights allows every participant to have the same ability to manipulate the data on blockchain. Such rights can be weighted by the computational power (Proof-of-work) or stake (Proof-of-stake) owned by a node. Trust of the blockchain is built based on the interactions between nodes within the blockchain network. The participants of a blockchain network rely on the design of blockchain, the cryptographic techniques used by blockchain and the blockchain network itself rather than relying on trusted third-party to facilitate transactions.
2.1.2 Limitations
Data privacy and scalability are the main two limitations of public blockchains. Data privacy on public blockchain is limited because there is no privileged user, and every participant can join the network to access all the information on blockchain and validate new transactions. There are scalability limits on (i) the size of the data included into a transaction, (ii) the transaction processing rate, and (iii) the latency of data transmission and commits. Latency between submitting a transaction and it being committed on a blockchain is affected by the consensus protocol. This is around 1 hour (10-minute block interval with time for inclusion and 5-block confirmation) on Bitcoin, and around 3 minutes (14-second block interval with 11 confirmation blocks) on Ethereum111https://www.ethereum.org/. Times in practice can be even longer [21]. The number of transactions included in each block is also limited by the bandwidth of nodes participating in the network (for Bitcoin the current bandwidth per block is 1MB) [1]. Ethereum applies a so-called gas limit to blocks (gas is the internal pricing unit for executing a transaction or storing data), which limits the number and complexity of transactions that can fit into a block.
2.1.3 Blockchain as a Software Component
When used in a large software system, blockchain can be viewed as a software component [26]. In such software system, blockchain is responsible for storing and sharing data, and executing smart contracts. Due to the limitations of privacy and performance, there might be off-chain auxiliary databases used in the system. For example, private or large sized data can be stored in an internal database. There is normally a API layer between the data storage layer and the applications using the blockchain, which is same as with conventional technology. When blockchain interacts with other off-chain components, an “oracle” [13] is needed to bridge blockchain with the external world.
2.2 Smart Contract
The first generation of blockchains, like Bitcoin, provides a public ledger to store cryptographically-signed financial transactions [19]. There is very limited capability to support programmable transactions, and only very small pieces of auxiliary data could be embedded in the transactions to serve other purposes, such as representing other digital assets or physical assets.
The second generation of blockchains provides a general-purpose programmable infrastructure with a public ledger that records the computational results. Programs, known as smart contracts [18], can be deployed and run on a blockchain. Smart contracts can express triggers, conditions and business logic [22] to enable more complex programmable transactions. The signature of the transaction initiator authorizes the data payload of a transaction or the creation or execution of a smart contract. A common simple example of a smart contract-enabled service is escrow, which can hold funds until the obligations defined in the smart contract have been fulfilled. Smart contracts are pure functions by design, which cannot access the state of external systems directly.
Smart Contract Languages
Script used by Bitcoin is a simple stack-based scripting language222https://en.bitcoin.it/wiki/Script, which is intentionally designed not to be Turing-complete. Script provides the flexibility to define conditions required to spend the Bitcoin associated with the transactions, for example, requiring multiple private keys to authorize the payment. Ethereum is currently the most widely-used blockchain that supports general-purpose (Turing-complete) smart contracts. The primary smart contract language used on Ethereum blockchain is Solidity333https://solidity.readthedocs.io/. DigitalAsset444http://www.digitalasset.com/ proposed DAML555https://daml.com/as a domain specific smart contract language for financial institutes. Smart contracts running on Hyperledger Fabric666https://www.hyperledger.org/use/fabric are called Chaincode, which can be written in any programming language and executed in containers inside the fabric context layer.
3 Overview of Blockchain-based Application Patterns
In this section, we discuss the overview of the blockchain-based application pattern collection, which currently includes nineteen design patterns that shape the architectural elements and their interactions in blockchain-based applications. Figure. 1 gives an overview of these patterns as well as their mutual relationships. The arrows in Figure. 1 illustrate how to navigate through the pattern collection during a design process. Applying the patterns to an blockchain-based application can better align it with the unique properties provided by blockchain, avoid its limitations, and achieve other quality attributes.

The patterns about interaction between blockchain and the external world describe different ways for blockchain to communicate data with the external world, including Centralized oracle (Section 4.1), Decentralized oracle (Section 4.2), Reverse oracle (Section 4.4) and Voting (Section 4.3). The four data management patterns are about managing data on and off blockchain, including Tokenisation (Section 5.1), Off-chain data storage (Section 5.2), State channel (Section 5.3) and Legal and smart contract pair (Section 5.4). The four security patterns concern the security aspect of the blockchain-based applications. Multiple authorization (Section 6.2) and Dynamic authorization (Section 6.3) are aimed at adding dynamism to authorization of transactions and smart contracts. Embedded permission (Section 6.4) aims to improve security of smart contracts, and On-chain Encryption (Section 6.1) can be used to improve security of on-chain data.
The five contract structural patterns define the dependencies among smart contracts and behaviour of smart contract. Smart contracts on blockchain are immutable. Upgrading a smart contract to a new version is a challenge which hinders the evolution of blockchain-based applications. Contract registry (Section 7.1), Factory contract (Section 7.3) and Data contract (Section 7.2) can used together to improve upgradability of smart contracts. Incentive execution (Section 7.4) and Security deposit (Section 7.5) provide incentive mechanism for execution and maintenance of smart contracts. The two user interaction patterns summarise different ways for users to interact with DApps, including DApp (Section 8.1) and Semi-DApp (Section 8.2).
In this paper we follow the extended pattern form from [14], which includes the name of the pattern, a short summary, the context, the problem statement, an explicit discussion of the forces which make the problem difficult, the solution, its consequences, and some examples of real-world known uses of the pattern. Forces are identified with the corresponding quality attribute, as sometimes the solution will propose a trade-off between them. Regarding the consequences, we distinguish the benefits and drawbacks. Finally, we discuss features only applicable to a certain deployment of blockchain, such as monetary cost of data storage and code execution.
4 Interaction with External World Patterns
As a component of a big software system, blockchain needs to communicate data with other components within the software system. This section discuss four patterns applicable to the interaction between blockchain and external world.
4.1 Pattern 1: Centralized Oracle
Summary: Introduce the state of external systems into the closed blockchain execution environment through a single centralized connector (called oracle). Fig. 2 is a graphical representation of the pattern.
Context: From the software architecture perspective, blockchain can be viewed as a component or connector within a large software system [26]. In the case where blockchain is used as a distributed database for more general purposes other than financial services, the applications built on blockchain might need to interact with other external systems. Thus, the validation of transactions on blockchain might depend on states of external systems.

Problem: Smart contracts running on blockchain are pure functions by design. The execution environment of smart contract is self-contained. It can only access information present in the data and transactions on the blockchain.The state of external systems are not directly accessible to smart contracts. How can function calls in smart contracts be enabled to access the state of the external world from within smart contracts?
Forces: The problem requires to balance the following forces:
-
•
Closed environment. Blockchain is a secure, self-contained environment, which is isolated from external systems. Smart contracts on blockchain cannot read the states of the external systems.
-
•
Connectivity. In addition to the data found on the blockchain, general-purpose applications might require information from external systems. For example, a parcel tracking application needs context information like geo-location information, a gambling application might need weather data from a Web API777https://openweathermap.org/api.
Solution: To connect the closed execution environment of blockchain with the external world, oracle is introduced to assist in evaluating conditions that cannot be expressed in a smart contract running within the blockchain environment. If the information flows from blockchain to external world, Reverse Oracle (Section 4.4) should be used. An centralized oracle is a trusted third party that provides the smart contracts with information about the external world. When validation of a transaction depends on external state, the oracle is requested to check the external state and inject the result to the blockchain in a transaction signed using its own key pair. The validators (miner) take the result provided by the oracle into account when validating the transaction. From the perspective of validator, by introducing the oracle, the validation of transactions is based on the authentication of the oracle (through digital signature) rather than the external state because what provided by oracle is trusted by the validator. From the perspective of the validator, the data injected from oracle is no different from data provided (through embedding into a transaction or as a variable value) by other users. What validators can do is to ensure the data integrity by checking the digital signature of the sender and executing the smart contract based on the input data, but they cannot check the originality or correctness of the input data from external world. More technical details of implementing the pattern could be found in [16].
Consequences:
Benefits:
-
•
Connectivity. The closed execution environment of blockchain is connected with external world through a centralized oracle. The applications based on blockchain can access external states through the oracle and use the external states to validate transactions.
-
•
Efficiency. Centralized oracle is more efficient in terms of monetary and time cost. It is easier to manage compared with Decentralized Oracle (Section 4.2)
Drawbacks:
-
•
Trust. Using a centralized oracle introduces a trusted third party into the system. The oracle selected to verify the external state needs to be trusted by all the participants involved in relevant transactions.
-
•
Validity. The external states injected into the transactions can not be fully validated by miners. Thus, when miners validate the transaction including external state, they rely on the oracle to check the validity of the information from external world.
-
•
Long-term availability and validity. It could happen that while transactions are immutable, the external state used to validate them may change after the transactions were originally appended to the blockchain.
-
•
Single point of failure. A centralized oracle introduces a single trusted element, whose unavailability or failure may prevent the blockchain from successfully completing the transaction verification process.
Related patterns:
Known uses:
-
•
Oracle in Bitcoin is an instance of this pattern 888https://en.bitcoin.it/wiki/Contract#Example_4:_Using_external_state. Oracle is a server outside the Bitcoin blockchain network, which can evaluate user-defined expressions based on the external state.
-
•
Provable999https://provable.xyz/ is an oracle service provider, which utilises trusted hardware to directly fetch information from external trusted execution environment (TEE). Provable introduces three different proofs for fetching data from external data sources, namely, TLS-Notary, Ledger proof and Android proof.
-
•
Corda101010https://www.corda.net/ has a centralized oracle mechanism embedded in its platform. The oracle mechanism uses Intel Software Guard Extensions (SGX) for hardware attestation to prevent unauthorised access outside of the SGX environment.
4.2 Pattern 2: Decentralized Oracles
Summary: Introduce the state of external systems into the closed blockchain execution environment through a cluster of connectors (called oracles). Fig. 3 is a graphical representation of the pattern.

Context: In the case where blockchain is used as a distributed database for more general purposes other than financial services, the applications built on blockchain might need to interact with other external systems. A centralized oracle (Section 4.1) can be applied to inject the states of external systems into blockchain.
Problem: A centralized oracle introduces a single trusted third party into the system, which might becomes a single point of failure of the whole software system.
Forces: The problem requires to balance the following forces:
-
•
Reliability and Availability. A centralized oracle becomes a single point of failure from an architecture perspective. In the case that the status injected into the blockchain is a faulty status, the whole system might behave inaccurately. In the case that the oracle is unable to inject any state to the system, the whole system might be stuck and unavailable depending on how critical the state is.
-
•
Cost. The cost of data retrieval from external world is proportional to the number of oracles.
Solution: To improve trustworthiness of the oracle, a decentralized oracle mechanism is introduced, which is based on multiple oracles. These oracles can get data from one data source or multiple independent data sources. Voting (Section 4.3) can be applied to decentralized oracle to reach a consensus on the status to be injected into the blockchain.
Consequences:
Benefits:
-
•
Reliability and Availability. By having multiple oracles retrieving data from external world, the risk of validating transactions based on faulty external data is reduced from a single centralized oracle. Acquiring data by multiple oracles also improves the reliability and the confidence of the final accepted value.
Drawbacks:
-
•
Trust. Although using decentralized oracle avoids the single-point-of-trust, it still introduces trusted third parties into the system. All the oracles that verify the external state needs to be trusted by all the participants involved in relevant transactions. So trust needs to be extended from a single entity to a cluster.
-
•
Cost. Cost of using a piece of data from external world increases with the number of oracles being used.
-
•
Time. It might take longer time for multiple oracles to get the required information and reach a consensus over the final result. If all oracles need to agree, the time is bound by the slowest oracle. If a subset of the oracles is sufficient, then the slowest oracles can be ignored, thus potentially speeding up the process.
-
•
Uncertainty. Compared with centralized oracle, decentralized oracle introduces more uncertainties. When human is involved, the value what majority vote becomes the result, which might be different from the truth in the physical world.
Related patterns:
Known uses:
-
•
Orisi111111http://orisi.org/ on Bitcoin maintains a set of independent oracles. Orisi allows the participants involved in a transaction to select a set of oracles and define the value of M (number of oracles) before initiating a conditional transaction.
-
•
Gnosis121212https://gnosis.io/ is a decentralized prediction market that allows users to choose any oracle they trust, such as another user or a web service, e.g. , for weather forecasts. A human oracle is also called arbitrator, who is trusted by the interacting participants to resolve disputes or check external state.
-
•
Augur131313https://www.augur.net/ is another prediction market that leverages the capability of human oracles to do prediction and resolve disputes.
4.3 Pattern 3: Voting
Summary: To achieve an agreement on a state proposed on blockchain, anyone with blockchain account can propose tentative new state or vote for a proposed state by staking their tokens until a consensus is achieve. Fig. 4 is a graphical representation of the pattern.

Context: The public access of blockchain provides equal rights that allow [27] every participant the same ability to access and manipulate the blockchain. This property of blockchain enables a way for blockchain users to make decisions together and achieve consensus on the result. During the consensus process, everyone has equal right to participate in decision making. In the context of decentralized oracle, especially the one using human oracles, blockchain users use different sources to report the result. They may have different preferences.
Problem: During a process to achieve an agreement on certain state on blockchain, what if the state proposed by an blockchain account (oracle or human) is disputed?
Forces: The problem requires to balance the following forces:
-
•
Fairness. Every participant in blockchain network has a equal right to access and manipulate the blockchain. Each participant’s vote should have the same weight as the others.
-
•
Consensus. Multiple participants in different opinions need to reach an agreement to make decision. Participants also need to agree on which of the many paths leading to an outcome based on their preferences (e.g., simple or qualified majority) is taken.
-
•
Transparency/Auditability. The voting process should be deterministic and auditable so that the outcome can be reproduced from the same input (which should not disappear after the vote).
Solution:
Voting is a mechanism commonly used by a group of participants to make a collective decision when the state originally proposed by participant is disputed. Anyone with a blockchain account that does not agree with the state can propose another state as tentative answer. To make a decision, every participant vote through sending transaction through her/his blockchain account. The voting transaction is signed by the private key of the participant, which represents the right of the participant to make decision. Such right can be weighted by the resource owned by the participant, like the application-specific tokens. Normally, majority rule is used to select the alternative which has the most votes (or with heavier weight in terms of stake) among all alternatives.
One possible extension to the solution is to support secret voting by leveraging digital signatures. The voters can encrypt their choice when casting a vote, which can be decrypted using the corresponding public key when the votes are being counted. However, by linking the voting transaction with other transactions from and to the account, the anonymity of the user might be compromised. A more privacy-preserving way for the voter is to create a new account for voting only. It is debatable whether blockchain is a suitable technique to solve on-line voting security due to sociological issues that are outside of technical environment141414https://theconversation.com/blockchains-wont-fix-internet-voting-security-and-could-make-it-worse-104830.
Consequences:
Benefits:
-
•
Equality. Voting method allows the participants to use their right to participate decision making.
-
•
Consensus. Multiple participants with different preferences can reach a consensus through voting.
Drawbacks:
-
•
Duplication The vote is associated with the blockchain account. Smart contract can help to avoid duplicated votes from the same blockchain account, for example by counting only the most recent vote. But since blockchain is pseudonymous, every participant can own multiple blockchain addresses to gain additional voting power, which is similar to the Sybil attack at network layer.
-
•
Time. Voting may take a long time due to long voting/dispute time windows
Related patterns:
-
•
Decentralized Oracles (Section 4.2) works with voting pattern to achieve consensus on the answer reported to blockchain.
-
•
Security Deposit (Section 7.5) provides a mechanism for participants to weight their vote using their stake.
-
•
Multiple Authorization (Section 6.2) is one on-chain mechanism to enable voting.
-
•
Dynamic Authorization (Section 6.2) is one off-chain mechanism to enable voting.
Known uses:
-
•
Voting mechanism is used in DAOs (Decentralised Autonomous Organisations)151515https://www.ethereum.org/dao.
-
•
In Gnosis12 prediction market, a voting mechanism is used if someone challenges the reported outcome. This voting mechanism allows users to vote on what the correct outcome was by betting Ether on that outcome.
-
•
In Augur13 prediction market, a similar voting mechanism is used to resolve disputes on the outcome reported by oracles.
4.4 Pattern 4: Reverse Oracle
Summary: The reverse oracle of an existing system relies on smart contracts running on blockchain to validate requested data and check required status. Fig. 5 is a graphical representation of the pattern.

Context: In a software system, where blockchain is one of the components, the off-chain components might need to use the data stored on the blockchain and the smart contracts running on the blockchain to check certain conditions.
Problem: Some domains use very large and mature (or even legacy) systems, which comply with existing standards. For such domain, how to integrate the existing complex systems with blockchain in an non-intrusive approach without changing the core of the existing systems?
Forces: The problem requires to balance the following forces:
-
•
Connectivity. Integrating blockchain into an existing system to leverage the unique properties of blockchain, as discussed in Section 2.1.1.
-
•
Simplicity. Introduce minimal changes to the existing system.
Solution: The unique ID of the transactions or blocks on blockchain is a piece of data that can be easily integrated into the existing systems so that they can refer to specific transactions as having taken place or address data permanently stored in specific blocks. Reverse Oracle is a component sitting between the blockchain and the other components in the system. Reverse Oracle is mainly reading data from the blockchain, and inserting the reference (ID of transaction) of this data into other components in the system. Oracle, however, is mainly writing data into the blockchain from other components. Validation of such data is implemented by smart contracts running on blockchain. Any off-chain component is required to query the blockchain through using the ID of the referenced data. More technical details of implementing the pattern could be found in [16].
Consequences:
Benefits:
-
•
Connectivity. The blockchain is integrated into an existing system with minimal effort.
Drawbacks:
-
•
Non-intrusive. It’s not always possible to use blockchain in a non-intrusive way depending on the extensibility of the existing systems. Writing to and reading from the blockchain might need changing the existing system so that they can securely access the blockchain network.
Related patterns:
- •
Known uses:
-
•
Identitii161616https://identitii.com/ provides a solution to enrich the payments in banking systems with documents and tamper-proof attributes stored on a private blockchain. Identitii invents the concept of identity token stored on a blockchain. Every payment is associated with an identity token, which is used to exchange enriched information about a payment. The identity token is exchanged between the banks through being embedded into existing SWIFT protocol messages and can be verified against the copy in the blockchain.
-
•
Chaintrace171717https://chainflux.com/wine-traceability-using-blockchain/ records all the information about a wine, such as source, location, volume of the ingredients on blockchain. Chaintrace can be connected to external supply chain system and injects relevant information about a bottle of wine for cross verification.
5 Data Management Patterns
Due to the unique properties and limitations of blockchain, the main architectural consideration for a blockchain-based software application is to decide what data and executable code (smart contract) should be kept on-chain, and what should be kept off-chain. Two factors need particular attention, namely performance and privacy. Performance highly depends on the type of deployment of the blockchain. For example, a consortium blockchain [27] can be configured to achieve much better performance than a public blockchain. This section discusses four data management patterns that manage data on and off blockchain.
5.1 Pattern 5: Tokenisation
Summary: Using tokens on blockchain to represent fungible goods for easier distribution.
Context: The concept of tokenisation has emerged centuries ago with the first currency systems. Tokenisation is a means to reduce risk in handling high value financial instruments by replacing them with equivalents, for example, the tokens used in casino. Tokens can represent a wide range of goods which are transferable and fungible, like shares, or tickets. Blockchain is a suitable technique for asset management because of its immutability and transparency.
Problem:
How to have a representative of assets to avoid repetition and decrease risk?
Forces: The problem requires to balance the following forces:
-
•
Risk. Handling fungible financial assets with high value is risky, e.g., lost assets cannot be replaced.
-
•
Repetition. An asset should be represented by only one token as the authoritative source.
Solution: Tokenisation is a process starting from an asset (e.g., money) is locked under a custody (e.g., a bank), and gets represented in the cryptographic world through a token. The ownership of the digital token matches the ownership of the corresponding asset. The reverse process can take place by which the user redeems the token to recover the value which is sitting within the bank.
Blockchain provides a trustworthy platform to realise tokenisation. There are different ways to implement tokenisation using blockchain. A token on blockchain is the authoritative source of the physical asset. Naive tokens on a blockchain (e.g., BTC on Bitcoin, ETC on Ethereum) can be used to formulate a system where the tokens represent monetary value or other physical assets. The token is generally used to track title over the physical assets. Transactions on blockchain record the verifiable title transfer from one user to another. However, using the native token on blockchain for tokenisation is limited because it can only implement the title transfer of the physical assets, with limited conditions checking. A more flexible way is to define a data structure in a smart contract to represent physical assets. By using smart contracts, some conditions can be implemented and associated with the ownership transfer.
Consequences:
Benefits:
-
•
Risk. Tokenisation reduces risk in handling high value financial instruments by replacing them with equivalents.
-
•
Repetition. Blockchain and smart contracts provide a trustworthy infrastructure to provide authorised tokens for the corresponding assets.
Drawbacks:
-
•
Integrity. Integrity of the tokens is guaranteed by the blockchain infrastructure. But the authenticity of the corresponding physical/digital asset is not guaranteed automatically.
-
•
Standardisation. 24% of the existing financial smart contracts on Ethereum uses this tokenisation pattern [3]. Given the popularity of this pattern, ERC20181818https://eips.ethereum.org/EIPS/eip-20 (and ERC777191919https://eips.ethereum.org/EIPS/eip-777 as an advanced version) has been proposed as a fungible token standard that describes the functions and events that a token smart contract has to implement. The new proposed fungible tokens should follow the standard.
-
•
Legal processes for ownership. A token on a blockchain is not necessarily the authoritative source of information about the ownership of a physical asset. The owner of an asset may be entitled to sell the asset without being required to create a transaction on the blockchain. Also, legal processes such as court orders and bankruptcy proceedings can change the ownership of physical assets without any associated transaction being recorded on the blockchain.
Related patterns:
-
•
Off-Chain Data Storage (Section 5.2) can be used to add a hash of a digital asset as an ID on blockchain.
Known uses:
-
•
Digix202020https://digix.global/ uses tokens to track the ownership of gold as a physical property.
-
•
Elevated Returns212121https://www.elevatedreturns.com/ is an asset management firm that uses tokenisation to manage ownership on real estates.
-
•
CargoX222222https://cargox.io/ creates a smart token to replace their bill of lading. The ownership of goods are claimed by using the smart token.
5.2 Pattern 6: Off-Chain Data Storage
Summary: Use hashing to ensure the integrity of arbitrarily large datasets which may not fit directly on the blockchain. Fig. 6 is a graphical representation of the pattern solution.

Context: Some applications consider using the blockchain to guarantee the integrity of large amounts of data.
Problem: The blockchain, due to its full replication across all participants of the blockchain network, has limited storage capacity. Storing large amounts of data within a transaction may be impossible due to the limited size of the blocks of the blockchain (for example, the gas limit on Ethereum). Data cannot take advantage of the immutability or integrity guarantees without being stored on the blockchain. How to store data of arbitrary size and take advantage of the immutability and integrity guarantees provided by the blockchain?
Forces: The problem requires to balance the following forces:
-
•
Integrity. Applications leverage blockchain to achieve data integrity.
-
•
Scalability. Blockchain provides limited scalability because every bit of data is replicated across all nodes, where it is kept permanently.
-
•
Cost. If a public blockchain is used, storing data on blockchain costs real money, although the cost is a one-time cost to write the data. This is in contrast to traditional distributed data storage, like cloud, which charge based on the amount of allocated storage space over time. A piece of data can be stored on blockchain through being embedded into a transaction, or as a variable of smart contract or as a log event. Embedding data into a transaction is the cheapest way, while storing data in a contract is more efficient to enable manipulation, but can be less flexible due to the potential constraints of the smart contract languages on the value types and length [27]. Different blockchain has different cost model for storing data.
-
•
Size. There are limits of transaction size or block size. For example, on Bitcoin blockchain, The default Bitcoin client only relayed transactions up to 80 bytes, which was reduced to 40 bytes in 2014232323https://github.com/bitcoin/bitcoin/pull/3737. Ethereum has a block gas limit that restricts the amount of gas which all transactions in a block are allowed to use.
Solution: The blockchain can be used as a general-purpose replicated database, as transactions logged in the blockchain can include arbitrary data on some blockchain platforms. For data of big size (essentially data that is bigger than its hash value), rather than storing the raw data directly on blockchain, a representation of the data with smaller size can be stored on blockchain with other small sized metadata about the data (e.g., a URI pointing to it). The solution is to store a hash value (also called digest) of the raw data on chain. The value is generated by a hash function, e.g. one from the SHA2 [7] family, which maps data of arbitrary size to data of fixed size. Hash function is a one-way function which is easy to compute, but hard to invert given the output of a random input. If even one bit of the data changes, its corresponding hash value would change as well. The hash value is used for ensuring the integrity of the raw data stored off-chain, and the transaction on blockchain that includes the hash value guarantees the integrity of the hash value as well as the original raw data from which the hash was derived.
Consequences:
Benefits:
-
•
Integrity. Blockchain guarantees the integrity of the hash value that represents the raw data. The integrity of the raw data can be checked using the on-chain hash value.
-
•
Cost. If a public blockchain is used, blockchain is utilized at a lower cost (fixed cost as the size of the hash value is fixed) for integrity of data with arbitrary size.
Drawbacks:
-
•
Integrity. The raw data is stored off-chain, where the off-chain data store might not be as secure as blockchain. The raw data may be changed without authorization. This change will be detected thanks to the hash of the original data stored on the blockchain. However, without additional measures, it will neither be possible to recover the original data nor to prevent the change from happening in the first place.
-
•
Availability. Since the raw data is stored off-chain, it may be deleted or lost. Only its hash value remains permanently on the blockchain.
-
•
Data sharing. The on-chain data can be shared through using blockchain platforms. Extra communication mechanisms and storage platforms are required for data sharing off-chain.
Related patterns:
Known uses:
-
•
Proof-of-Existence (POEX.IO242424https://poex.io/) allows entering an SHA-256 cryptographic hash of a document into the Bitcoin blockchain as a “proof-of-existence” of the document at a certain time. The hash value guarantees the data integrity of the document.
-
•
Chainy252525https://chainy.info/ is a smart contract running on Ethereum blockchain. Chainy stores a short link to an off-chain file and its corresponding hash value in one place.
5.3 Pattern 7: State channel
Summary: Micro-payments transactions are too expensive to be performed on-chain because the required transaction fee might be higher than the monetary value associated with the transaction assuming a public blockchain is used. Thus, micro-payments should be exchanged off-chain while periodically recording settlements for larger amounts on chain. Such a payment channel can be generalized for arbitrary state updates for more general purposes other than monetary value. Fig. 7 is a graphical representation of the pattern.

Context: Micro-payments are payments that can be as small as a few cents, e.g., payment of a very small amount of money to a WiFi hot-spot for every 10 kilobytes of data usage. Blockchain has potential to be used for such financial transactions with tiny monetary value. The question is if it is necessary and cost effective to store all the micro-payment transactions on blockchain.
Problem: The decentralized design of blockchain has limited performance. Transactions can take several minutes or even one hour (for Bitcoin blockchain) to be committed on the blockchain [21]. Due to the long commit time and high transaction fees on a public blockchain (where fees are largely independent of the transacted amount), it is often infeasible to store every micro-payment transaction on the blockchain network. During a peak in demand, the average fee per transaction raised to the equivalent of US$55262626 https://bitinfocharts.com/comparison/bitcoin-transactionfees.html for 22 Dec 2017; accessed on 11/03/2021. on Bitcoin. On-chain transactions are suitable for transactions with medium to large monetary value, relative to the transaction fee.
Forces: The problem requires to balance the following forces:
-
•
Trustworthiness. Payment transactions on the blockchain are trusted.
-
•
Latency. Blockchain transactions may take a long time to be committed while users expect micro-payments to happen instantaneously.
-
•
Scalability. Blockchain has limited scalability because every bit of data is replicated across all nodes, and kept permanently.
-
•
Cost. Storing data on a public blockchain costs real money. The transaction fee of individual micro-payment transaction might be higher than the monetary value associated with the micro-payment transaction.
Solution: Storing every micro-payment transaction on blockchain is infeasible in certain contexts due to the small monetary value associated with it. Thus, a solution is to establish a payment channel between two participants, with a deposit from one or both sides of the participants locked up as security in a smart contract for the lifetime of the payment channel. The payment channel keeps the intermediate states of the micro-payment off-chain, and only stores the finalized payment on chain. The frequency of transaction settlement depends on the use case, and agreement between the two sides. For example, in scenarios around utilities, internet service providers or electricity companies can establish payment channel with their consumers for an agreed billing period, for example, a month. As the consumer uses data or energy daily, the intermediate state is stored in the channel until the end of the month, when the channel is closed to finalize the payment of that month. A network of micro-payment channels can be built where the transactions transferring small values occur off-chain. The individual transactions take place entirely off the blockchain and exclusively between the participants, across multiple hops where needed. Only the final transaction that settles the payment for a given channel or set of channels is submitted to the blockchain. The technologies used to implement state channel are normally specific to blockchain platform. For example, Lightning network272727https://lightning.network/ on the Bitcoin blockchain is a proposed implementation of Hashed Timelock Contracts (HTLCs)282828https://en.bitcoin.it/wiki/Hashed_Timelock_Contracts with bi-directional payment channels which allows secure payments across multiple peer-to-peer channels. A HTLC is a type of payments that use the features of Script, like hashlocks and timelocks, to require that the receiver of a payment acknowledges receiving the payment prior to a deadline by generating cryptographic proof.
Consequences:
Benefits:
-
•
Speed. Without involving blockchain for every transfer, the off-chain transactions can be settled without waiting for the blockchain network to process the transaction, generate a new block with the transaction and reach consensus, and the desired number of confirmation blocks.
-
•
Throughput. The number of off-chain transactions that can be processed is not limited by the configuration of blockchain, such as the block size, block interval, gas limit, etc., and thus a much higher throughput can be achieved than for on-chain transactions.
-
•
Privacy. Other than the final settlement transaction, the individual off-chain transactions do not show up in the public ledger, thus, the detail of these intermediate off-chain transactions is not publicly visible.
-
•
Cost. If a public blockchain is used, only the final settlement transaction costs transaction fee to be included in the blockchain. Direct individual off-chain transactions do not cost any money. Multi-hop transactions may cost small transaction fees, which are typically charged as a percentage of the transacted amount.
Drawbacks:
-
•
Trustworthiness. The individual off-chain micro-payment transactions might not be as trustworthy as the on-chain transactions because the micro-payment transactions are not stored in an immutable data store. The intermediate state of payment channels might be lost after the payment channels are closed.
-
•
Liquidity. To establish a payment channel, money from one or both sides of the channel needs to be locked up in a smart contract for the lifetime of the payment channel. The liquidity of the channel participants is thereby reduced.
-
•
Wallet. A new wallet or extension to the existing wallet is needed to support the micro-payment protocol.
Related patterns:
-
•
Off-Chain Data Storage (Section 5.2) is another mechanism that reduces data on blockchain.
Known uses:
-
•
The Lightning network uses an off-chain protocol to enable micro-payments of Bitcoin and several other crypto-currencies.
-
•
The Raiden network292929https://raiden.network/ on the Ethereum blockchain is a similar solution as lightning network. The basic idea is to avoid the consensus bottleneck by leveraging a network of off-chain payment channels that allow to securely transfer monetary value. Smart contracts are used to deposit value into the payment channels.
-
•
State channel on Ethereum303030http://www.jeffcoleman.ca/state-channels/ and Gnosis Go313131https://forum.gnosis.pm/t/how-offchain-trading-will-work/63 offer a more generalized form of state channels that support exchanging state for general-purpose applications.
5.4 Pattern 8: Legal and Smart Contract Pair
Summary: A bidirectional binding is established between a legal agreement and the corresponding smart contract. Fig. 8 is a graphical representation of the pattern.

Context: The legal industry is becoming digitized, for example, using digital signatures has become a valid way to sign legal agreements. The Ricardian contract [10] was developed in the mid 1990s to interpret legal contracts digitally without losing the value of the legal prose. Digital legal agreements need to be executed and enforced.
Problem: An independent trustworthy execution platform trusted by all the involved participants is needed to execute the digital legal agreement. How to bind a legal agreement to the corresponding smart contract on a trusted execution environment to ensure a 1-to-1 mapping?
Forces: The problem requires to balance the following forces:
-
•
Authoritative source. A 1-to-1 mapping is required between a legal contract and its corresponding smart contract to make the smart contract as the authoritative source of the legal contract.
-
•
Secure storage. A secure and trustworthy data storage is required to keep the legal agreement.
-
•
Secure execution. A trustworthy computational platform is required to execute digital agreements to enforce certain conditions as defined in a legal contract.
Solution:
Blockchain can be an ideal trusted platform to run digital legal agreements, which are bound with the corresponding on-chain smart contracts. The smart contract implements conditions defined in the legal agreement. When deployed, there is a variable to store the hash value of the legal agreement, but is initially a blank value. The address of the smart contract is included in the legal agreement, and then the hash of the legal agreement is calculated and added to the contract variable. By binding a physical agreement with a smart contract, the bridge between the off-chain physical agreement and the on-chain smart contract is established. The two directional binding makes sure that the legal agreement and smart contract have a 1-to-1 mapping.
The smart contract digitizes the conditions defined within the legal agreement. Thus, these conditions can be checked and enforced automatically by the smart contract. However, not all the legal terms can be easily digitalized. The smart contract can also enable automated regulatory compliance checking in terms of the required information and process. However, the capability of compliance checking might be limited due to the constraints of smart contract programming language.
Consequences:
Benefits:
-
•
Automation. Some of the conditions defined in the legal contract, for example, a conditional payment, can be automatically enforced by blockchain.
-
•
Audit trail. Blockchain permanently records all historical transactions related to the legal contract and the contract itself. This immutable data enables auditing at anytime in future.
-
•
Clarification. Encoding legal terms expressed in natural language into smart contracts will require to give them a clear interpretation.
Drawbacks:
-
•
Expressiveness. Smart contracts are written in programming languages. The smart contract languages might have limited expressiveness to express contractual terms of arbitrary complexity. The capability of regulatory compliance checking also depends on the expressiveness of the smart contracts. A regulation may regulate the process, for example, what should or should not be done by whom at what stage.
-
•
Enforceability. If a public blockchain is used, there is no central administering authority to decide a dispute, or perform the enforcement of a court judgment.
-
•
Interpretability. There might be different ways to interpret a certain legal term and to encode them in the smart contract. Ambiguity of natural language makes it a challenge to accurately implement a certain legal term in a way that is agreed upon by all the involved participants.
Related patterns:
-
•
Legal and Smart Contract Pair is enabled by Off-Chain Data Storage (Section 5.2) .
Known uses:
-
•
OpenLaw323232http://openlaw.io/ is a platform that allows lawyers to make legally binding and self-executable agreements on the Ethereum blockchain. The legal agreement templates are stored on a decentralized data storage, IPFS333333https://ipfs.io/. Users can create customized contracts for specific uses.
-
•
Smart Contract Template proposed by Barclays343434https://www.barclays.co.uk/ uses legal document templates to facilitate smart contracts running on Corda10 blockchain platform [5, 6].
-
•
Specific proposals for the representation of machine-interpretable legal terms have been explored in KWM’s project on digital and analog (DnA) contracts353535https://github.com/KingandWoodMallesonsAU/Project-DnA and in the Accord Project363636https://www.accordproject.org/.
6 Security Patterns
This section discusses four security patterns that mainly concern the security aspect [9] of the blockchain-based applications.
6.1 Pattern 9: On-Chain Encryption
Summary: Ensure confidentiality of the data stored on blockchain by encrypting it. Fig. 9 is a graphical representation of the pattern.

Context: For some applications on blockchain, there might be commercially critical data that should be only accessible to the involved participants. An example would be a special discount price offered by a service provider to a subset of its users. Such information should not be accessible to the other users who do not get the discount.
Problem: The lack of data privacy is one of the main limitations of blockchain. All the information on blockchain is publicly available to the participants of the blockchain network. There is no privileged user within the blockchain network, no matter the blockchain is public, consortium or private. On a public blockchain, new participants can join the blockchain network freely and access all the information recorded on blockchain. Any confidential data on public blockchain is exposed to the public.
Forces: The problem requires to balance the following forces:
-
•
Transparency. Every participant within a blockchain network is able to access all the historical transactions on blockchain, which is required to enable them to validate previous transactions. The transactions on a public blockchain are also accessible to everyone with access to the internet, simply using tools like a blockchain explorer such as Etherscan373737http://etherscan.io.
-
•
Lack of confidentiality. Since all the information on blockchain is publicly available to everyone in the network, commercially sensitive data meant to be kept confidential should not be stored on blockchain, at least not in plain form.
Solution: To preserve the privacy of the involved participants, symmetric or asymmetric encryption can be used to encrypt data before inserting the data into blockchain. One possible design for sharing encrypted data among multiple participants is as follows. First, one of the involved participants creates a secret key for encrypting data and distributes it during an initial key exchange. When one of the participants needs to add a new data item to the blockchain, they first symmetrically encrypt it using the secret key. Only the participants allowed to access the transaction have the secret key and can decrypt the information.
Consequences:
Benefits:
-
•
Confidentiality. Using encryption, the publicly accessible information on blockchain is encrypted, so that is useless to anyone who does not hold the secret key.
Drawbacks:
-
•
Compromised key. Both symmetric and asymmetric encryption require off-chain key management. If key management is not done properly, it can lead to compromise and disclosure of private or secret keys. If the required private key or secret key is compromised, the encryption mechanism does not guarantee the confidentiality nor the integrity of the data.
-
•
Access revocation. Revoking read access is a challenge after the encrypted data has been published to the blockchain. The encrypted data on blockchain is immutable. Thus, as long as the participant keeps the secret key used to encrypt the data, it has access to the encrypted data forever.
-
•
Immutable data. Even if stored in encrypted form, the critical data will remain in the blockchain forever. In addition to the risk of key compromise, the encrypted data may be subject to brute force decryption attacks at any time in the future, or breakthroughs in technology like quantum computing might render current encryption technologies ineffective. So even if the data is considered to be secure with a given key size when it is stored in the blockchain, this may no longer be the case in the future.
-
•
Key sharing. The encryption key needs to be shared off-chain before submitting any relevant transaction to the blockchain secretly. Although blockchain can be used as a software connector [26] to communicate data, secret keys can not be shared through blockchain because the shared key would be publicly accessible if being communicated through blockchain.
Related patterns:
-
•
Off-Chain Data Storage (Section 5.2) also provides data confidentiality because the raw data is not stored on blockchain.
Known uses:
-
•
Encrypted queries from Provable9. Provable is a smart contract running on Ethereum public blockchain, which provides a service to access state from external world. Provable allows smart contract developers to encrypt the parameters of their queries locally by using a public key before passing them to a smart contract. The only one who can decrypt the call parameters is Provable with the paired private key.
-
•
Crypto digital signature is suggested by MLGBlockchain383838https://mlgblockchain.com/crypto-signature.html to encrypt data and share the data between the parties who interact and transmit data through blockchain.
-
•
Hawk [11] is a smart contract system that stores transactions as encrypted data on blockchain to retain the privacy of the transactions. The compiler of Hawk can automatically generate a cryptographic protocol for a smart contract. The involved participants interact with the blockchain following the cryptographic protocol.
6.2 Pattern 10: Multiple Authorization
Summary: A set of blockchain addresses which can authorise a transaction is pre-defined. Only a subset of the addresses is required to authorize transactions. Fig. 10 is a graphical representation of the pattern.

Context: In blockchain-based applications, activities might need to be authorized by multiple blockchain addresses. For example, a monetary transaction may require authorization from multiple blockchain addresses.
Problem: The actual addresses that authorize an activity might not be able to be decided due to the availability of the authorities. How to allow multiple authorities to dynamically authorize a transaction based on their avilability?
Forces: The problem requires to balance the following forces:
-
•
Flexibility. The actual authorities who authorize the transaction can be from a set of pre-defined authorities.
-
•
Tolerance of compromised or lost private key Authentication on blockchain uses digital signature. However, blockchain does not offer any mechanism to recover a lost or a compromised private key. Losing a key results in permanent loss of control over an account, and potentially smart contracts that refer to it.
Solution: It would enable more dynamism if the set of blockchain addresses for authorization are not decided before the corresponding transaction being submited into the blockchain network, or the corresponding smart contract being deployed on blockchain. On the Bitcoin blockchain, a multi-signature mechanism can be used to require more than one private key to authorize a Bitcoin transaction. In Ethereum, smart contract can mimic multi-signature mechanism.
Consequences:
Benefits:
-
•
Flexibility. This pattern enables flexible binding of authorities, but depends on the availability of authorities when the activity is proceeded.
-
•
Lost key tolerant. One participant can own more than one blockchain address to reduce the risk of losing control over their smart contracts due to a lost private key. There could be a function that can update the list of allowed authorities, and the threshold of the authorization. In the case that the update function also requires threshold-based authorization, the list of the update addresses can be also updated through authorization from at least the minimum number of addresses.
Drawbacks:
-
•
Pre-defined authorities. Although the pattern enables flexible binding, all the possible authorities still need to be known in advance of any decision or update.
-
•
Lost key. At least a minimum number of private keys should be safely kept to avoid losing control.
-
•
Cost of dynamism. If a public blockchain is used, updating the list of authorities costs money, as does deploying the logic for multiple authorities. Besides, it costs more to store multiple addresses as the possible authorities than storing only one.
Related patterns:
Known uses:
-
•
Multi-Signature mechanism provided by Bitcoin393939https://en.bitcoin.it/wiki/Multisignature.
-
•
Multi-signature wallet, written in Solidity, running on Ethereum blochchain and is available in the Ethereum DApp browser Mist404040https://github.com/ethereum/mist.
6.3 Pattern 11: Dynamic Authorization
Summary: Using a hash created off-chain to dynamically bind authority for a transaction. Fig. 11 is a graphical representation of the pattern. This solution is sometimes referred to as Hashlock.

Context: In blockchain-based applications, some activities need to be authorized by one or more participants that are unknown when a first transaction is submitted to blockchain.
Problem: Sometimes, the authority who can authorize a given activity is unknown when the corresponding smart contract is deployed, or the corresponding transaction is submitted to the blockchain. Blockchain uses digital signature for authentication and transaction authorization. Blockchain does not support dynamic binding with an address of a participant which is not defined in the respective transaction or smart contract. All accounts that can authorize a second transaction have to be defined in the first transaction before that transaction is added to the blockchain. How to allow one or more unknown authorities to dynamically authorize a transaction?
Forces: The problem requires to balance the following forces:
-
•
Dynamism. Dynamic binding one or more unknown authorities with a second transaction representing an activity after the first transaction submitted to blockchain.
-
•
Pre-defined authorities. Using only on-chain mechanisms, all the possible authorities are required to be defined beforehand.
Solution: An off-chain secret can be used to enable a dynamic authorization when the participant authorizing a transaction is unknown beforehand. In the context of payment, for example, a smart contract can be used as an escrow. When the sender deposits the money to an escrow smart contract, a hash of a secret (for example, a random string, called pre-image) is submitted with the money as well. Whoever receives the secret off-chain can claim the money from the escrow smart contract by revealing the secret. With this solution, the receiver of the money does not need to be defined beforehand in the escrow contract. This can be generalized to any transaction that needs authorization from a dynamically bound participant. Note that since the secret is revealed, it cannot be reused. One variant is to lock multiple transactions with the same secret – by unlocking one, all of them are unlocked.
Consequences:
Benefits:
-
•
Dynamism. This pattern enables dynamic binding of unknown authorities after the transaction is added into the blockchain.
-
•
Lost key tolerant. No specific private key is required to authorize transactions.
-
•
Routability. This pattern has the useful property that once the secret is revealed, any other transactions secured using the same secret can also be opened. This makes it possible to create multiple transactions that are all locked by the same secret. This property is used by micro-payment channels (Section 5.3) to enable multi-hop transfers where the money hosted by every hop and secured by a same secret can be released after the end receiver claims the money with the secret (i.e. the secret is revealed). The secret can be exchanged through an off-chain channel to every hop.
-
•
Interoperability. There is no need for a special protocol to exchange the secret. The secret can be exchanged in any ways off-chain. It provides a mechanism for other systems to trigger events on blockchain.
Drawbacks:
-
•
One-off secret. The secret used in this pattern is a one-off secret. Verification of the secret is on-chain. Thus, once a secret is embedded in a transaction submitted to the blockchain, the secret is revealed.
-
•
Combination of signature and secret. Because this pattern has the property that once the secret is revealed, any other transactions secured using the same secret can also be opened, sometimes the transaction protected by the secret should also be associated with a public key so that both a correct secret and an appropriate signature with the respective private key are required to authorize the transaction. This is applicable to the situation where a large set of authorities are known beforehand, but not all of them are allowed to authorize a certain activity/transaction. Thus, a hash secret is used to dynamically bind one or multiple authorities from the larger pre-defined set of authorities.
-
•
Lost secret. The sender/initiator of a transaction takes the risk of losing the off-chainsecret. If the secret is lost, the transaction cannot be authorized and being proceeded anymore. In the case of money transfer, the money associated with the transaction would be locked forever if the transaction cannot be authorized properly.
Related patterns:
-
•
Multiple Authorization (Section 6.2). The multiple authorization pattern is used when all the possible authorities are known beforehand. Multiple authorization pattern is an on-chain mechanism.
-
•
Voting (Section 4.3) can be enabled by Dynamic Authorization.
-
•
Dynamic Authorization enables routability for State channel (Section 5.3) in the financial transaction scenarios.
Known uses:
-
•
Raiden network29 is a network of off-chain payment channels on top of Ethereum blockchain network, which enables secure value transfer. The multi-hop transfer mechanism in Raiden Network uses hashlocked transactions to securely router payment through a middleman.
-
•
In the Bitcoin ecosystem, atomic cross-chain trading414141https://en.bitcoin.it/wiki/Atomic_cross-chain_trading allows one crytocurrency (for example, Bitcoin) to be traded for another cryptocurrency (for example, tokens on a Bitcoin sidechain) using a off-chain hash secret.
6.4 Pattern 12: Embedded Permission
Summary: Smart contracts use an embedded permission control to restrict access to the invocation of the functions defined in the smart contracts. Fig. 12 is a graphical representation of the pattern.

Context: All the smart contracts running on blockchain can be accessed and called by all the blockchain participants and other smart contracts by default, because there are no privileged users in blockchain network. In the case of public blockchain, every one with internet access can join the network to access all the information and code stored and running on blockchain.
Problem: A smart contract by default has no owner, meaning that once deployed the author of the smart contract has no special privilege on the smart contract. A permission-less function can be triggered by unauthorized users accidentally. Such a permission-less function becomes vulnerability of blockchain-based application. For example, a permission-less function which is discovered in a smart contract library used by the Parity multi-signature wallet, caused the freezing of about 500K Ethers424242https://paritytech.io/a-postmortem-on-the-parity-multi-sig-library-self-destruct/. 7% smart contract on public Ethereum can be terminated without authority [21].
Forces: The problem requires to balance the following forces:
-
•
Security. The functions defined in the smart contracts should be called only by the authorized participants. Due to the transparency of public blockchains, all the smart contracts are also publicly available to everyone connecting to the Internet. In contrast, in a conventional software system, the internal logic is normally not visible to the end uses. Interaction with the software system is either through a user interface or API, where it is possible to enforce access control policies.
Solution: Adding permission control to every smart contract function to check permissions for every caller that triggers the functions defined in the smart contract based on the blockchain addresses of the caller. This can be done by checking the authorization of the caller before executing the logic of the function: unauthorized calls are rejected and the execution of the function terminated before reaching the core logic of the function.
Consequences:
Benefits:
-
•
Security. Only the participants and smart contracts that are authorized by the smart contract can call the corresponding functions successfully.
-
•
Secure authorization. Authorization is implemented in smart contracts running on blockchain, which leverages the properties provided by blockchain.
Drawbacks:
-
•
Cost. On a public blockchain, extra code that implements the permission control mechanism also has additional monetary cost for deployment and execution.
-
•
Lack of flexibility. Such permissions are defined in the smart contract before its deployment, therefore they are difficult to change. However, permissions may be required to be dynamic. A mechanism is needed to support dynamic granting and removal of permissions.
Related patterns:
Known uses:
-
•
The Mortal contract discussed in the Solidity tutorial434343http://solidity.readthedocs.io/en/develop/contracts.html restricts the permission of invoking the selfdestruct function to the “owner” of the contract – where “owner” is a variable defined in the contract code itself.
-
•
The Restrict access pattern suggested in the Solidity tutorial444444http://solidity.readthedocs.io/en/develop/common-patterns.html uses modifier to restrict who can make modifications to the state of the contract or call the functions of the contract. Modifier is a mechanism that adds a piece of code before the function to check certain conditions.
7 Contract Structural Patterns
This section discusses five smart contracts patterns. Essentially, smart contracts are programs running on blockchain, thus some of the existing design patterns and programming principles for conventional software environments are also applicable to smart contracts. If a public blockchain is used, the structural design of the smart contract has large impact on its deployment and execution cost. The cost of deploying a smart contract depends on the size of the smart contract(s) because the code is stored on blockchain, resulting in a data storage fee that is proportional to the size of the smart contract. Thus, a structural design with more lines of compiled code costs more money. A consortium blockchain does not necessarily have tokens/currency; therefore monetary cost is typically not an issue for a consortium blockchain. However, blockchain size is still a design concern because the total size of the blockchain keeps growing as more blocks are appended to it and no block can ever be detached from it, and every participant stores a full replica of blockchain. Besides, different structural designs of smart contracts may affect performance because more or less transactions may be required.
7.1 Pattern 13: Contract Registry
Summary: Before invoking it, the address of the latest version of a smart contract is located by looking up its name on a contract registry. Fig. 13 is a graphical representation of the pattern.

Context: As any software application, blockchain-based applications need to be upgraded to new versions. To do so, the on-chain functions defined in smart contracts need to be updated to fix bugs as well as to fulfill new requirements.
Problem: Smart contracts deployed on blockchain cannot be upgraded because the code of the smart contracts as a type of data, stored on blockchain is immutable. How to perform upgrades of smart contracts?
Forces: The problem requires to balance the following forces:
-
•
Immutability. Every bit of data, including deployed smart contracts, stored on blockchain is immutable.
-
•
Upgradability. There is a fundamental need to upgrade all but short-lived applications and their smart contracts over time.
-
•
Human-readable contract identifier. The identifier of a smart contract on blockchain platforms, like Ethereum, is hexadecimal address, which is not human-readable.
Solution: An on-chain registry contract is used to maintain a mapping between user-defined symbolic names and the blockchain addresses of the registered contracts. The address of the registry contract needs to be advertised off-chain. The creator of a contract can register the name and the address of the new contract to the registry contract after the new contract being deployed. The invoker of a registered contract retrieves the latest version of the new smart contract from the registry contract. The corresponding functions provided by the registered contract can be upgraded by replacing the address of the old version contract in the registry contract with the address of a new version without breaking the dependency between the upgraded smart contract and other smart contracts that depend on its functions. The address of a contract is stored as a variable in the registry contract. The value of contract variables can be updated. The registry contract can have a permission control module to maintain the writing permission. Note that all the previous values of the variable are still stored on the blockchain.
Consequences:
Benefits:
-
•
Human-readable contract name. The registry contract maintains a mapping between human-readable names and the hexadecimal addresses of the smart contracts. A human readable form of smart contract names is desired, for example, to be exposed to the user interface. A human readable name is also useful for developers.
-
•
Constant contract name. The smart contract associated with a registered name can be updated without changing its name. This way dependencies relying on the name of the smart contract do not get broken.
-
•
Upgradability. The smart contract associated with a registered name could be replaced by a new version without breaking the dependencies based on the human-readable name.
-
•
Version control. Version control can be integrated in the registry contract as well to allow a look-up based on the name and version of a smart contract. Old versions of a smart contract that are no longer needed should be terminated.
Drawbacks:
-
•
Upgradability. Upgradability is still limited if the functions defined in the smart contract are called by other contracts. Although the implementation of the function can be upgraded, the interface (that is function signature) cannot be modified without breaking the link to dependent smart contracts. Similar methods as for API / service interface management need to be implemented, e.g. through versioning and depreciation flags.
-
•
Cost. There is an additional cost to maintain a registry that contains the mapping between the contract names and their addresses. Furthermore, all the inter-contract function calls require a registry look-up to find the latest version of the smart contract to be invoked.
Related patterns:
Known uses:
-
•
ENS454545https://ens.domains is a name service on Ethereum blockchain, which is implemented as smart contracts. ENS maintains a mapping between both smart contracts on-chain and resources off-chain and simple, human-readable names. ENS can be viewed as a contract registry built on Ethereum blockchain, which is accessible to everyone. A blockchain-based application can also maintain a separate registry contract for the application.
-
•
KairosFuture464646https://www.kairosfuture.com/publications/reports/the-land-registry-in-the-block-chain-testbed/ experimented using blockchain smart contract as a replacement for land registry. All the signed contracts are recorded by a registry contract on the blockchain.
-
•
Kaleido474747https://www.kaleido.io/blockchain-blog/smart-contract-management-solution-how-it-works-why-you-need-it proposed a enterprise-level smart contract management solution. The core function of their management solution is the contract registry that is accessable to every participants in Kaleido network.
7.2 Pattern 14: Data Contract
Summary: Store data in a separate smart contract. Fig. 14 is a graphical representation of the pattern.

Context: The need to upgrade a blockchain-based application over time is ultimately necessary, so as the smart contracts used by the application. In general, logic and data change at different times and with different frequencies. There are different ways to store a data on blockchain, as discussed in Off-chain Data Storage pattern (Section 5.2).
Problem: Storing data on blockchain is expensive and there is a limitation on the amount of data and amount of computation a transaction can contain. In the context of upgrading smart contracts, the upgrading transactions might contain a large data storage for copying the data from the old version of the smart contract to the new version of the smart contract. Porting data to a new version might even require multiple transactions, e.g. when the block gas limit on Ethereum prevents an overly complex data migration transaction.
Forces: The problem requires to balance the following forces:
-
•
Coupling. Smart contracts can live forever on blockchain if not being explicitly terminated. If a smart contract is deactivated in this way, the data stored in the smart contract cannot be accessed through the smart contract functions any more – although it can still be accessed with some effort, e.g. for provenance or audit purposes.
-
•
Upgradability. The need to upgrade the application and the smart contracts supporting the application over time is ultimately necessary for many applications.
-
•
Cost. If a public blockchain is used, storing data on blockchain costs money. Thus copying data from an old version of a smart contract to a new version should be avoid or minimized.
Solution: To avoid moving data during upgrades of smart contracts, the data store is isolated from the rest of the code. In the context of blockchain, data could be separately stored in different smart contracts to enable isolation. Depending on the circumstances of the application, how large of a data store it needs and whether the data structure is expected to change often, the data store could use a strict definition or a loosely typed flat store. The more generic and flexible data structure can be used by all the other logic smart contracts and is unlikely to require changes. One example of a generic data structure is a mapping to store SHA-256 key and value pairs.
Consequences:
Benefits:
-
•
Upgradability. By separating data from the rest of the code, the logic of the application is able to be upgraded without affecting the data contract.
-
•
Cost. Since the data is separated from the rest of the code, there is no cost for migrating data when the application is upgraded.
-
•
Generality. If the data can be cleanly separated and generalized, there would be an additional benefit: the generic data contract can be used by all related logic smart contracts.
Drawbacks:
-
•
Cost. If a public blockchain is used, storing a piece of data in a generic data structure costs more money than a strictly defined data structure. For example, as mentioned earlier, a generic data structure maintains a mapping between SHA-256 key and value pairs, but a more strictly defined data structure can be of smaller size, e.g. not requiring the key to be stored. Querying the data is also less straightforward. This is the cost of a generalized solution.
Related patterns:
-
•
Contract registry (Section 7.1) and Data Contract can work together to further improve upgradability of smart contracts.
Known uses:
-
•
Chronobank484848https://chronobank.io/ is a blockchain project that tokenizes labour and provides a market for professionals to trade their labour time with businesses. It uses a smart contract with a generic data structure as the data store used by all the other logic smart contracts.
-
•
Colony494949https://colony.io/, a platform for open organizations running on Ethereum. Similar to Chronobank, Colony has a data contract with a generic data structure.
7.3 Pattern 15: Factory Contract
Summary: An on-chain template contract is used as a factory that generates contract instances from the template. Fig. 15 is a graphical representation of the pattern.

Context: Applications based on blockchain might need to use multiple instances of a standard contract with customization. Each contract instance is created by instantiating a contract template. For example, in a business process management system, each of the business process instances might be represented by a smart contract being generated from a contract template representing the business process model [22]. The template can be stored off-chain in a code repository, or on-chain, within its own smart contract.
Problem: Keeping the contract template off-chain cannot guarantee consistency between different smart contract instances created from the same template because the source code of the template can be independently modified.
Forces: The problem requires to balance the following forces:
-
•
Dependency management. Storing the source code of smart contract off-chain in a code repository introduces the issue of integrating more systems into the blockchain-based application.
-
•
Secure code sharing. The source code smart contract should be stored in a secure storage.
-
•
Deployment. If a public code repository, like Github, is used to store the source code of a smart contract, a component is needed to implement the function of deploying smart contract on blockchain, otherwise, the end users need to understand how to deploy smart contracts.
Solution: Smart contracts are created from a contract factory deployed on blockchain. The factory contract is deployed once from the off-chain source code. The factory may contain the definition of multiple smart contracts. Smart contract instances are generated by passing parameters to the contract factory to instantiate customized smart contract instances. Factory contract is analogous to a Class in an object-oriented programming language. Every transaction that generates a smart contract instance essentially instantiates an object of the factory contract class. This contract instance (the object) will maintain its own properties independently of the other instances but with a structure consistent with its original template.
Consequences:
Benefits:
-
•
Security. Keeping the factory contract on-chain guarantees the consistency of the contract definition. Blockchain provides a secure platform to share code of smart contracts. As opposed to a traditional code repository, changes of code deployed on a smart contract can be strictly limited or prohibited.
-
•
Efficiency. If the contract definition is kept on-chain in a factory contract, smart contract instances are generated by calling a function defined in the factory contract.
Drawbacks:
-
•
Deployment cost. If a public blockchain is used, using factory contract requires extra cost to deploy the factory contract.
-
•
Function call cost. If a public blockchain is used, creating a new smart contract instance requires extra cost to call a function defined in the factory contract.
Related patterns:
-
•
Contract registry (Section 7.1) can be used to store the addresses of all the smart contract instances generated from a factory contract. The factory and instance registry can be implemented in the same contract, although that limits upgradability.
Known uses:
-
•
A tutorial from Ethereum developers505050https://ethereumdev.io/manage-several-contracts-with-factories/ about how to create a contract factory from which smart contract instances can be created.
-
•
Factory pattern has been applied in a real-world blockchain-based health care application [28].
-
•
The business process management system in an academic work [22] uses a contract factory to generate process instances.
7.4 Pattern 16: Incentive Execution
Summary: Reward is provided to the caller of the contract function for invoking the execution. Fig. 16 is a graphical representation of the pattern.

Context: Smart contracts are event-driven programs, which cannot execute autonomously. All the functions defined in a smart contract need to be triggered either by a transaction from external account or another smart contract to execute. Other than the functions that provide regular services to users, some functions need to run asynchronously from regular user interaction, for example, to clean up the expired records, or make dividend payouts etc. Such accessorial functions usually involve a time, after which the function should start.
Problem: Users of a smart contract have no direct benefit from calling the accessorial functions. If a public blockchain is used, executing these functions causes extra monetary cost. Some accessorial functions are expensive to execute. How to make sure the the accessorial functions are invoked?
Forces: The problem requires to balance the following forces:
-
•
Completeness. The regular services provided by a smart contract are supported by some accessorial functions.
-
•
Cost. Execution of accessorial functions causes extra costs from the users.
Solution: Reward the caller of a function defined in a smart contract for invoking the execution, for example, sending back a percentage of payout to the caller to reimburse the (gas) execution cost.
Consequences:
Benefits:
-
•
Completeness. The execution of the accessorial functions helps to complete the regular services provided by the smart contract.
-
•
Cost. The users, who spends extra to execute the accessorial functions, are compensated by the reward associated with the execution.
Drawbacks:
-
•
Execution. Execution cannot be guaranteed even with incentive. Thus, another option is to embed the logic of accessorial functions into other regular functions that users have to call to use the services.
Related patterns:
-
•
Both Security Deposit (Section 7.5) and Incentive Execution provide incentive mechanisms.
Known uses:
-
•
Ethereum alarm clock515151http://www.ethereum-alarm-clock.com/ is a service provided by a smart contract running on Ethereum. It facilitates scheduling function calls for a specified block in the future and provides incentive for users to execute the scheduled function.
7.5 Pattern 17: Security Deposit
Summary: A user put aside a certain amount of money, which will be paid back to the user for her honesty or given to the other parties to compensate them for the dishonesty of the user. Fig. 17 is a graphical representation of the pattern.

Context: In a decentralized environment like blockchain, trust in the blockchain-based application is achieved from the interactions between participants within the network. A blockchain-based application rely on all the users rather than relying on trusted third-party organisations to facilitate transactions.
Problem: The equal rights property of blockchain allows every participant the same ability to access and manipulate the blockchain and the decentralized applications running on blockchain. How can a certain participant proves to others that he/she behaves honestly?
Forces: The problem requires to balance the following forces:
-
•
Security. The security of a decentralized application relies on the behaviour of all the participants of the application.
-
•
Incentive. In a decentralized application, participants can be incentivised to behave honestly.
Solution: Initially, participant is required to put aside amount of tokens, which will be paid back to the participant if she behave honestly, otherwise the deposit is given to the other parties to compensate them for their loss. Such security deposit is recorded on blockchain, which is publicly available to other parties. Security deposit is a way to reduce the risk of participants in the network misbehave by temporarily sacrificing some of her stake.
Consequences:
Benefits:
-
•
Security. The security of the application is obtained through security deposit because the deposit will be paid back to the participant only if the participant behaves honestly.
Drawbacks:
-
•
Access. The security deposit is normally larger than the potential profit the participant gain from her/his dishonesty. If the required deposit is large, it restricts some participants to access the application.
-
•
Liquidity. Similarly as above, the liquidity of the application participants is reduced due to the deposit.
Related patterns:
-
•
Both Incentive Execution (Section 7.4) and Security Deposit provide incentive mechanisms.
Known uses:
-
•
The notion of “deposits” has already been used in Bitcoin’s contract525252https://en.bitcoin.it/wiki/Contract#Example_1:_Providing_a_deposit, where deposit is bought by a party with no reputation as a proof of her trust.
-
•
Ethereum alarm clock51 enables scheduling of transactions for delayed execution in the future. Before the execution window, there is a claim window when the request may be claimed by a participant for execution. To claim a request, the participant is required to put down a deposit. If the claimer fulfils their commitment to execute the request, the deposit is returned to them, otherwise, the deposit is given to someone else that executes the request as an additional reward.
8 User Interaction Patterns
This section illustrates two patterns regarding user interacting with smart contracts.
8.1 Pattern 18: DApp
Summary: Decentralized applications (DApps) are applications running on P2P network rather than a single computer. DApps are blockchain-based web applications that allow users to interact with smart contracts deployed on blockchain. Fig. 18 is a graphical representation of the pattern.

Context: Users interact with smart contracts through sending transactions to invoke the functions defined in smart contracts. In order for the users to understand how to interact with a smart contract, the source code of the smart contract is open source and visible to users. Second, the application binary interface (ABI) of the smart contract is also publicly accessible so that users can send transactions to it.
Problem: Users need a strong technical understanding of blockchain and smart contract to be able to generate transactions calling smart contracts. Such process is error-prone and with a bad user experience [23]. How to call a smart contract in a trustless environment?
Forces: The problem requires to balance the following forces:
-
•
Learning Curve. Users need to understand the functionality of a smart contract before being able to interact with it. To understand the input required and the output produced by a smart contract, users need to read the documentation or the source code of the smart contract.
-
•
Convenience. Manually generating transactions to interact with an smart contract is an error-prone process despite the understanding of the smart contract. Depending on whether many transactions need to be sent, it may be worth to invest into automating the transaction submission process.
-
•
Trust. The user needs to trust the provider of such automated transaction submission process.
Solution: DApp provides a front-end user interface for users to easily interact with smart contracts. The frond end uses the same technology as conventional web applications to render web pages. The difference is that DApps can be hosted on a decentralized storage, like IPFS, and are rendered by DApp browsers, like Ethereum Mist40 or a plug-in to a web application browser, like MetaMask535353https://metamask.io/. Both the smart contract on blockchain and the DApp is deployed on a local node. The transactions calling smart contracts are generated by DApps, and are presented to the users for further verification before being sent to the blockchain.
Consequences:
Benefits:
-
•
Convenience. Users interact with smart contract through a front-end provided by the DApp provider instead of reverse engineering how to submit transactions from the source code of the smart contract. The user experience of using the front-end of a DApp are much better as it requires less technical understanding of the smart contract. Assuming the DApp is correct, it is also less error-prone than manually generating transactions to interact with smart contracts.
Drawbacks:
-
•
Trust. Using DApps imposes trust to the DApp provider because the transactions are generated by the DApp on behalf of the user. However, the impact of the execution is not explicit without understanding the smart contracts underneath, especially if the source code of the contract or ABI is not published.
-
•
Learning Curve. Basic technical knowledge regarding transactions and gas are still required by users to use DApps and verify the transactions generated by the DApps.
Related patterns:
-
•
Semi-DApp (Section 8.2) can be browsed using a conventional web browser without any DApp plugin.
Known uses:
-
•
State of the DApps545454https://www.stateofthedapps.com/ provides a directory of the DApps on Ethereum blockchain. There are 1800+ DApps with different levels of maturity registered to the directory. DappRadar555555https://dappradar.com/ also provides a directory of DApps, not only on Ethereum blockchain but also included DApps deployed on EOS565656https://eos.io/ and TRON575757https://tron.network/index?lng=en.
-
•
Remix585858https://remix.ethereum.org is an open source smart contract compiler that allow user to write and interact with Solidity contracts from the browser.
8.2 Pattern 19: Semi-DApp
Summary: Semi-DApp provider offers a web application, which can be browsed using a conventional web browser without any DApp plugin (like MetaMask). Fig. 19 is a graphical representation of the pattern.

Context: Users interact with smart contracts through sending transactions to invoke the functions defined in smart contracts. In order for the users to interact with a smart contract, the source code of the smart contract is open source and visible to users. Second, the application binary interface (ABI) of the smart contract is also publicly accessible.
Problem: Users need a strong technical understanding of blockchain and smart contract to be able to generate transactions and interact with smart contracts. Such process is error-prone, with a bad user experience [23]. Even with a front-end that assists the user to interact with smart contracts, some basic technical knowledge regarding transactions and gas is still required by users to use DApps and verify the transactions generated by the DApps (Section 8.1). It is not feasible for non-technical user to learn and understand the source code of smart contract to use it.
Forces: The problem requires to balance the following forces:
-
•
Learning Curve. Users need some basic technical knowledge of smart contracts in order to use DApps.
-
•
User Experience. Due to the decentralization nature of DApps, the front-end of most DApps is quite simple, and exposes too many technical details of the underlying smart contract, which not all users are capable to grasp.
Solution: Semi-DApp provider offers a standard web application for users to easily interact with smart contracts. The web application keeps the technical details of the corresponding smart contracts opaque to the users. The website communicates with the backend through RESTful API callsThus, the backend is responsible for interacting with the smart contracts on behalf of the user who is not able to inspect nor validate the transactions being sent to the blockchain. The transaction ID is normally returned to the user for the user to check the transaction on blockchain using blockchain explorer, like EtherScan37.
Consequences:
Benefits:
-
•
Convenience. Users interact with smart contracts through a web application provided by the Semi-DApp provider. The user experience of using the front-end of such a DApp is as same as using the front-end of a conventional web application. This solution offers the maximum convenience and the most gentle learning curve.
Drawbacks:
-
•
Trust. Users need to completely trust the Semi-DApp provider who is responsible for managing their private keys. One example is a Japan-based Bitcoin exchange, Mt. Gox595959https://en.wikipedia.org/wiki/Mt._Gox. Launched in 2010, Mt. Gox used to be the largest Bitcoin exchange in the world, which handles over 70% of all Bitcoin transactions worldwide. In June 2011, Mt. Gox announced that approximately 850,000 Bitcoins (an amount valued at more than $450 million at the time) belonging to customers and the company disappeared, most likely due to a compromised internal computer.
Related patterns:
-
•
DApp (Section 8.1) allows users to interact with smart contracts.
Known uses:
-
•
Cryptocurrency exchanges are common examples of this patterns as they always interact with the blockchain on behalf of the users. Kraken606060https://www.kraken.com/ is a San Francisco-based Bitcoin exchange.
-
•
Binance616161https://www.binance.com/ is a cryptocurrency exchange founded in China.
9 Related Work
To document the reusable solutions for blockchain-based application design, blockchain patterns have been summarized [2, 12, 16, 8, 23, 15]. Some of them are generic and can be applied for general purposes [16, 8, 23]. For example, five patterns are proposed for blockchain-based applications in [8], which focus on what data and computation should be on-chain and what should be kept off-chain. Other documented patterns apply to specific use cases [2, 12]. There are also design patterns for writing smart contracts from both academia and industry626262https://consensys.github.io/smart-contract-best-practices/. The binary code of a smart contract deployed on a public blockchain is publicly accessible, and for many, the code is also open-source. Empirical analysis has been conducted using smart contracts from different public blockchain platforms to identify the common programming patterns [3, 24, 25]. Existing patterns from conventional programming languages have been also applied to smart contract programming, for example, four existing object-oriented software patterns were applied to smart contract programming in the context of a blockchain-based health case application [28].
Compared with the above existing work, our paper covers system-level design patterns about interaction between blockchain and other components within a big software system, data management patterns, security patterns, structural patterns for smart contracts and user interaction patterns. Some structural patterns are new and some are modifications of the existing design patterns. More importantly, we provide use cases from the real world with each of the patterns. There is some overlap between the existing works and our paper. For example the Proxy pattern from [28] is a more generic pattern compared with our Off-chain data storage pattern. The Off-chain signatures pattern from [8] is similar to our State channel pattern. The Authorization pattern from [3] is similar to our Embedded permission pattern. Self-Confirmed transactions pattern from [23] is similar to our DApps pattern and Delegated transactions pattern is similar to our Semi-DApps patter.
10 Conclusions
We view the blockchain as a fundamental building block of large-scale decentralized software systems. For effective use of blockchain to this end, patterns are needed that show how to make good use of the blockchain in the design of systems and applications. In this paper, we propose a pattern collection for blockchain-based applications. Our pattern collection includes four patterns about interaction between blockchain and the external world, four data management patterns, four security patterns, five contract structural patterns and two user interaction patterns. The pattern collection provides an architectural guidance for developers to build applications on blockchain. Some patterns are designed specifically for blockchain-based applications considering the unique properties of blockchain. Others are variants of existing software patterns applied to smart contracts.
Acknowledge
We want to thank Tim Wellhausen, the shepherd for our EuroPLoP2018 patterns paper, and the anonymous reviewers of our paper for their helpful comments.
References
- [1] Ali, M., Nelson, J., Shea, R., Freedman, M.J.: Blockstack: A global naming and storage system secured by blockchains. In: USENIX ATC. pp. 181–194. USENIX Association, Santa Clara, CA (2016)
- [2] Bandara, H.M.N.D., Xu, X., Weber, I.: Patterns for blockchain data migration. In: Proc. 25th European Conf. on Pattern Languages of Programs (EuroPLoP ’20) (2020)
- [3] Bartoletti, M., Pompianu, L.: An empirical analysis of smart contracts: Platforms, applications, and design patterns. In: Financial Cryptography and Data Security. pp. 494–509. Springer International Publishing, Cham (2017)
- [4] Beck, K., Cunningham, W.: Using pattern languages for object oriented programs. In: Conference on Object-Oriented Programming, Systems, Languages, and Applications (OOPSLA). ACM, Orlando, FL, USA (1987)
- [5] Clack, C.D., Bakshi, V.A., Braine, L.: Smart Contract Templates: essential requirements and design options (Dec 2016)
- [6] Clack, C.D., Bakshi, V.A., Braine, L.: Smart Contract Templates: foundations, design landscape and research directions (Aug 2016)
- [7] of Commerce, U.D., of Standards, N.I., Technology:
- [8] Eberhardt, J., Tai, S.: On or off the blockchain? insights on off-chaining computation and data. In: 6th European Conference on Service-Oriented and Cloud Computing (ESOCC2017). pp. 3–15. Springer, Oslo, Norway (2017)
- [9] Fernandez-Buglioni, E.: Security patterns in practice: designing secure architectures using software patterns. John Wiley & Sons (2013)
- [10] Grigg, I.: The ricardian contract. In: The 1st IEEE International Workshop on Electronic Contracting (WEC2004). pp. 25–31. IEEE, San Diego, California (2004)
- [11] Kosba, A., Miller, A., Shi, E., Wen, Z., Papamanthou, C.: Hawk: The blockchain model of cryptography and privacy-preserving smart contracts. In: 37th IEEE Symposium on Security and Privacy (S&P2016). pp. 839–858. IEEE, Fairmont, SAN JOSE, CA (May 2016). https://doi.org/10.1109/SP.2016.55
- [12] Liu, Y., Lu, Q., Paik, H.Y., Xu, X.: Design patterns for blockchain-based self-sovereign identity. In: Proc. 25th European Conf. on Pattern Languages of Programs (EuroPLoP ’20) (2020)
- [13] Lo, S.K., Xu, X., Staples, M., Yao, L.: Reliability analysis for blockchain oracles. Computers & Electrical Engineering 83, 106582 (2020)
- [14] Meszaros, G., et al.: A Pattern Language for Pattern Writing. Pattern languages of program design 3, 529–574 (1998)
- [15] Moreno, J., Fernandez, E.B., Fernandez-Medina, E., Serrano, M.A.: Blockbd: A security pattern to incorporate blockchain in big data ecosystems. In: Proceedings of the 24th European Conference on Pattern Languages of Programs. EuroPLop ’19, Association for Computing Machinery, New York, NY, USA (2019). https://doi.org/10.1145/3361149.3361166, https://doi.org/10.1145/3361149.3361166
- [16] Mühlberger, R., Bachhofner, S., Di Ciccio, C., Weber, I., Wöhrer, M., Zdun, U.: Foundational oracle patterns: Connecting blockchain to the off-chain world. In: Blockchain Forum of the Intl. Conf. on Business Process Management (BPM) (Sep 2020)
- [17] Nakamoto, S.: Bitcoin: A peer-to-peer electronic cash system. https://bitcoin.org/bitcoin.pdf (2008)
- [18] Omohundro, S.: Cryptocurrencies, smart contracts, and artificial intelligence. AI Matters 1(2), 2685334 (Dec 2014). https://doi.org/10.1145/2685328.2685334, http://doi.acm.org/10.1145/2685328.2685334
- [19] Swan, M.: Blockchain: Blueprint for a New Economy. O’Reilly, US (2015)
- [20] UK Government Chief Scientific Adviser: Distributed ledger technology: beyond blockchain. Tech. rep., UK Government (2016)
- [21] Weber, I., Gramoli, V., Staples, M., Ponomarev, A., Holz, R., Tran, A., Rimba, P.: On availability for blockchain-based systems. In: SRDS’17: IEEE International Symposium on Reliable Distributed Systems. pp. 64–73. IEEE, Hong Kong, China (Sep 2017)
- [22] Weber, I., Xu, X., Riveret, R., Governatori, G., Ponomarev, A., Mendling, J.: Untrusted business process monitoring and execution using blockchain. In: BPM. pp. 329–347. Springer, Rio de Janeiro, Brazil (Sep 2016)
- [23] Wessling, F., Gruhn, V.: Engineering software architectures of blockchain-oriented applications. In: 2018 IEEE International Conference on Software Architecture Companion (ICSA-C). pp. 45–46. Seattle, USA (April 2018)
- [24] Wöhrer, M., Zdun, U.: Design patterns for smart contracts in the Ethereum ecosystem. In: 2018 IEEE Int. Conf. on Internet of Things (iThings) and IEEE Green Computing and Communications (GreenCom) and IEEE Cyber, Physical and Social Computing (CPSCom) and IEEE Smart Data (SmartData). pp. 1513–1520 (2018)
- [25] Wöhrer, M., Zdun, U.: Smart contracts: Security patterns in the Ethereum ecosystem and Solidity. In: Intl. Workshop on Blockchain Oriented Software Engineering (IWBOSE). pp. 2–8 (2018)
- [26] Xu, X., Pautasso, C., Zhu, L., Gramoli, V., Ponomarev, A., Tran, A.B., Chen, S.: The blockchain as a software connector. In: 13th Working IEEE/IFIP Conference on Software Architecture (WICSA2016). pp. 182–191. IEEE, Gothenburg, Sweden (2016)
- [27] Xu, X., Weber, I., Staples, M., Zhu, L., Bosch, J., Bass, L., Pautasso, C., Rimba, P.: A taxonomy of blockchain-based systems for architecture design. In: ICSA2017. pp. 243–252. IEEE, Gothenburg, Sweden (Apr 2017)
- [28] Zhang, P., White, J., Schmidt, D.C., Lenz, G.: Design of blockchain-based apps using familiar software patterns with a healthcare focus. In: Proceedings of the 24th Conference on Pattern Languages of Programs. PLoP ’17, The Hillside Group, USA (2017)