Design Patterns for Blockchain-Based Payment Applications
Qinghua Lu, Xiwei Xu, H.M.N. Dilum Bandara, Shiping Chen, Liming Zhu
DDesign Patterns for Blockchain-Based PaymentApplications
Qinghua Lu, Xiwei Xu, H.M.N. Dilum Bandara, Shiping Chen, Liming ZhuData61, CSIRO, AustraliaUniversity of New South Wales, Australia { firstname.lastname } @data61.csiro.auFebruary 22, 2021 Abstract
As the killer application of blockchain technology, blockchain-basedpayments have attracted extensive attention ranging from hobbyists tocorporates to regulatory bodies. Blockchain facilitates fast, secure, andcross-border payments without the need for intermediaries such as banks.Because the blockchain technology is still emerging, systematically organ-ised knowledge providing a holistic and comprehensive view on design-ing payment applications that use blockchain is yet to be established. Ifsuch knowledge could be established in the form of a set of blockchain-specific design patterns, architects could use those patterns in designing apayment application that leverages blockchain. Therefore, in this paper,we first identify a token’s lifecycle and then present 15 design patternsthat cover critical aspects in enabling the state transitions of a token inblockchain-based payment applications. The lifecycle and the annotateddesign patterns provide a payment-focused systematic view of system in-teractions and a guide to effective use of the design patterns.Blockchain, Pattern, Architecture, Payment, Token, Cryptocurrency,Escrow, Channel
Blockchain is an emerging distributed ledger technology that has attracted abroad range of interests from the academia and industry to build the nextgeneration of trustworthy applications. A large number of projects have beenconducted to explore how to re-architect systems, and to build new applicationsand business models using blockchain as a general, decentralised computing andstorage environment through the advent of smart contracts (i.e., programs on ablockchain) [1].Payment is considered the killer application of blockchain technology, whichexecutes monetary transactions for goods or services previously agreed upon by1 a r X i v : . [ c s . S E ] F e b uyer SellerIssuerTokens $$ $ Rules Tokens $$ Product $ X Burnedtokens $ Fiat currency
Figure 1: Overview of token-based payments.all parties involved. The “money” used on a blockchain includes both cryp-tocurrencies and tokens.
Cryptocurrencies are baked into the blockchain plat-forms as the base currency (e.g., Bitcoin and Ether) for transactions and pro-vide incentives for blockchain platform operations (e.g., mining).
Tokens areapplication-tier coins that are created and exchanged using smart contracts onthe blockchain. Tokens may represent cryptocurrencies (e.g., Binance Coin andUniswap) or used as a proxy for fiat currency (e.g., Tether and US Dollar Coin).Fig. 1 illustrates an overview of token-based payments. A token issuer issuesa new token associated with a set of spending rules. One or more tokens areallocated to a buyer . For example, in the context of food stamps the issuer isthe government agency responsible for the program and buyers are the peopleclassified as food insecure. The spending rules may specify eligible kinds offood, their quantities, and sellers. A buyer then purchases food products froma seller using the allocated tokens. A seller could be a supermarket that cashesout multiple tokens from the government agency. However, as different foodstamps may carry different spending rules, it is in the seller’s best interest tovalidate them at the time of payment. This ensures that the seller can convertthe collected tokens to fiat currency for the products it sold. Alternatively, thebuyer may also want to know the authenticity of the product and whether theseller has the authority to sell it. Once redeemed, the issuer needs to destroythe tokens (aka., burn token) to ensure the tokens are not reused (i.e., doublespend).As discussed in the above example, payments are usually conditional, wherethey are made subject to a set of conditions. Payment conditions could becomplicated in many environments, and could range from coupons with a des-ignated product/service and an expiration date to insurance payouts and social2elfare benefits. Further, the conditions need to be specified in advance (usu-ally with the consent of parties involved in the transaction) such that theycan be checked at the time of payment. Thus, in such use cases, the currencyneed to be programmable to specify payment conditions, enable automatic val-idation and enforcement, and support immutable record-keeping of associatedtransactions. These properties are well aligned with the design of tokens re-alised by blockchains (i.e., provides immutable record-keeping and multi-partytransactions) and smart contracts (i.e., provides programmability and automaticenforcement).As the blockchain technology is still emerging, systematically organised knowl-edge providing a holistic and comprehensive view on designing blockchain-basedpayment applications is yet to be established. Therefore, to form such knowl-edge, in this paper, based on a literature review and our project experience, wecollect a set of patterns that cover the critical aspects in the design of blockchain-based payment applications. We identify the lifecycle of a payable token, inwhich the identified design patterns are associated with the state transitionsalong the lifecycle. The lifecycle along with the annotated design patterns, pro-vide a payment-focused systematic view of system interactions and a guide tothe effective usage of the design patterns. In this paper, we focus on blockchain-based payable tokens such as the ones based on ERC-1363 standard that can bespent to purchase products or services. We also consider native cryptocurren-cies, fungible tokens (e.g., ERC-20 ), and non-fungible tokens (e.g., ERC-721 )that are used within smart contracts to attach to a specific buyer (e.g., a vouchergiven to a patient), specify payment conditions, and execute payments.The remainder of this paper is organised as follows: Section 2 discussesrelated work. The overview of payment patterns is introduced in Section 3.Section 4 presents each pattern in details. Section 5 gives concluding remarks. Previous works have collected and adopted design patterns to design blockchain-based applications [2, 3]. Wohrer and Zdun [4] summarised six design patternsto improve the security of smart contracts. OriginChain [5, 6] is a supply chainapplication that adopts data management design patterns and smart contractdesign patterns to improve the system adaptability. uBaaS is a service platformthat encapsulates patterns as services to generate code skeletons to facilitatethe development of blockchain-based applications [7]. Bartoletti and Pompianu[8] performed an empirical study on smart contracts by collecting hundreds ofsmart contracts and classifying them into different categories: token, authori-sation, oracle, randomness, poll, time constraint, termination, math, and forkcheck. Eberhardt and Tai [9] identified five data and computation design pat-terns for blockchain-based applications, including challenge-response, off-chain https://eips.ethereum.org/EIPS/eip-1363 https://eips.ethereum.org/EIPS/eip-20 https://eips.ethereum.org/EIPS/eip-721 A variety of constraints need to be satisfied while building payment applicationson a blockchain. While each application is unique, we can always learn from thecommonly recurring problems and the corresponding reusable design solutions.Those reusable design solutions can be established as a set of design patterns.Those payment patterns are derived from our blockchain project experienceand literature review. Although blockchain-based payments have been studiedin academic literature, design details are mostly available in grey literature, suchas white papers and blogs. Thus, we adopted a Multivocal Literature Review(MLR) [16] as our research methodology to study blockchain-based paymentsand collect related design patterns. The MLR process started with identifyingour research question, which is “What are the effective patterns for designinga blockchain-based payment application”. We used Google Search and GoogleScholar as the source databases. The search keywords include “blockchain”,“payment”, “smart contract”, “token”, “asset”, and their combinations. Wealso used snowballing to expand the pool of source literature. We then filteredthe sources according to the predefined selection criteria, e.g., “payment mustinclude ownership transfer of money”. Finally, we used open and axial codingto analyse the selected sources and derive related patterns iteratively.Table 1 gives an overview of the collected patterns. We classify the patternsinto three categories: token design patterns, seller management patterns, and4 a b l e : O v e r v i e w o f b l o c k c h a i np a y m e n t p a tt e r n s . C a t e go r y N a m e Su mm a r y T o k e n D e s i g n P a tt e r n s T o k e n T e m p l a t e T o k e n s a r e d e s i g n e d i n a c u s t o m i s e d w a y u s i n ga t o ke n t e m p l a t e t h a t c a nb ee x t e nd e d o r i n s t a n t i a t e d . T o k e n R e g i s t r y A t o k e n r e g i s t r y m a i n t a i n s t h e o w n e r s h i p i n f o r m a t i o n o f t o k e n s t h r o u g h a m a pp i n go f t o k e n I D a nd w a ll e t a dd r e ss . P o li c y C o n t r a c t A po l i c y c o n t r a c t s p ec i fi e s t h e p o li c i e s t h a t a t o k e n m u s t s a t i s f y , e . g ., w h e t h e r a t o k e n m u s t b e s p e n t o n t h e p r o du c t o r s e r v i ce ss upp li e db y e li g i b l e s e ll e r s o r h o w m a n y t o k e n s c a nb e s p e n t i n a t r a n s a c t i o n . B u r n e d T o k e n W h e n r e d ee m e d , a s p e n tt o k e n i s m a r k e d a s unu s a b l e / un s p e nd a b l e ( a k a ., b u r n e d ) . S e ll e r M a n a g e m e n t P a tt e r n s S e ll e r R e g i s t r y A s e ll e rr eg i s t r y m a i n t a i n s t h e i n f o r m a t i o n o f e li g i b l e s e ll e r s f r o m w h o m t h e t o k e n c a nb e s p e n tt o pu r c h a s e p r o du c t s o r s e r v i ce s . O w n e r s h i p C h a ll e n g e T o p r o v e t h e o w n e r s h i p o f a n i t e m , a bu y e r s e nd s a n o w n e r s h i p c ha ll e n ge t oa s e ll e r . T h e s e ll e r s i g n s i t w i t h t h e p r i v a t e k e y t h a t o w n s t h e i t e m , a nd t h e bu y e r c a n v e r i f y t h e s i g n a t u r e u s i n g t h e r e s p ec t i v e pub li c k e y . S e ll e r C r e d e n t i a l T h e bu y e r c a n v a li d a t e t h e s e ll e r ’ s bu s i n e ss q u a li fi c a t i o n t h r o u g h s e ll e r c r e d e n t i a l s . P a y m e n t M a n a g e - m e n t P a tt e r n s E s c r o w B e f o r e m a k i n ga t r a n s a c t i o n , t o k e n s a r e t r a n s f e rr e d t oa t h i r d - p a r t y s m a r t c o n t r a c t c a ll e d t h ee s c r o w . T h e e s c r o w h o l d s t h e d e p o s i t e d t o k e n s un t il t h e p a y m e n t c o nd i t i o n s a r e s a t i s fi e d . P a y m e n t C h a nn e l A t w o - w a y p a t h w a y ( a k a ., pa y m e n t c ha nn e l ) i s e s t a b li s h e db e t w ee n t r a n s a c t i n g p a r t i e s t o p e r f o r m t r a n s a c - t i o n s o ff - c h a i n w h il e r ec o r d i n go p e n i n ga ndfin a l s e tt l e m e n tt r a n s a c t i o n s o n t h e b l o c k c h a i n . D i g i t a l - P h y s i c a l P a r i t y A n a u t h e n t i c li n k ag e b e t w ee n a ph y s i c a l p r o du c t a nd i t s d i g i t a l r e p r e s e n t a t i o n ( i. e ., t o k e n ) i s e s t a b li s h e d o n t h e b l o c k c h a i n t o p r o t ec tt h e ph y s i c a l p r o du c t ’ s i n t e g r i t y . S t e a l t h A dd r e ss A s t e a l t hadd r e ss p r o t ec t s t h e p r i v a c y o f t h e p a r t i e s i n v o l v e d i n t h e p a y m e n t b y c r e a t i n gao n e - t i m e a dd r e ss f o r t h e t r a n s a c t i o n . O r a c l e T o e x a m i n e t h e f u l fi l m e n t o f p a y m e n t c o nd i t i o n s , a n o r a c l e i s u s e d t o i n t r o du ce t h e s t a t e o f e x t e r n a l s y s t e m s i n t o t h ec l o s e db l o c k c h a i n e x ec u t i o n e n v i r o n m e n t . M u l t i s i g n a t u r e G i v e n a p oo l o f n a dd r e ss e s t h a t c o u l d a u t h o r i s e a p a y m e n t , g e t a s ub s e t m o f t h e m t oa u t h o r i s e a p a y m e n t b y s i g n i n g t h e r e s p ec t i v e t r a n s a c t i o n ( m ≤ n ) . T o k e nS w a p T o k e n s w a p a ll o w s u s e r s t o t r a d e d i r ec t l y b e t w ee n t w o t y p e s o f t o k e n s a s a n a t o m i c t r a n s a c t i o n . A u t h o r i s e dSp e nd e r A n a u t h o r i s e d t h i r d - p a r t y s p e nd e r i s a ll o w e d t o s p e nd a ce r t a i n a m o un t o f t o k e n s o nb e h a l f o f t h e a pp r o v e r . t a t e S t a t e t r a n s i t i o n P a tt e r n T o k e n t e m p l a t e O r a c l e M u l t i s i gna t u r e E s c r o w C r e a t e d R e l e a s e d A ll o c a t e d V a li d a t e d T r a n s f e rr e d D e s t r o y e d D e p o s i t e d L i f e c y c l e o f a t o k e n S a t i s f i e d T o k e n r e g i s t r y S t e a l t h add r e ss L e g e nd S e ll e r r e g i s t r y I ss u e d P o li c y c o n t r a c t B u r n e d t o k e n O p e n e d R e c o r d e d E s c r o w e d C h a nn e l e d P a y m e n t c hann e l S e ll e r c r e d e n t i a l O w n e r s h i p c ha ll e ng e D i g i t a l - P h y s i c a l P a r i t y P a tt e r n e n a b l e r T o k e n s w ap A u t h o r i s e d s p e nd e r S e tt l e d S t e a l t h add r e ss O r a c l e M u l t i s i gna t u r e Figure 2: Lifecycle of a token with the annotated design patterns.6ayment management patterns. Fig. 2 illustrates the lifecycle of a token andhighlights the patterns associated with state transitions within the lifecycle.The lifecycle starts with the issuance of a token. The token can be designedin a customised way using a token template pattern which specifies necessarydetails (e.g., token name, symbol, number of decimal places, and the total num-ber of tokens supplied) and advanced features (e.g., the minting process, initialdistribution, and token burning process). A policy contract pattern stipulatesthe rules for using a group of tokens, such as how many vouchers can be spentin a transaction and whether the token must be spent on the specified prod-ucts or services supplied by eligible sellers. A seller registry pattern is used tomaintains the information of eligible sellers from whom the token can be spentto purchase products or services.Once issued, the predefined number of tokens are allocated to the buyer’swallet addresses who are on the initial distribution list. The token registry pattern could be used to maintain the token ownership information as a mappingbetween a wallet address and the number of tokens or token identifiers associatewith it. The buyer’s wallet receives the allocated tokens and sends a notificationto the consumer that the tokens are received.Before purchasing a product or service, a consumer’s wallet could use the seller credential pattern to validate the seller’s business qualifications. In cyber-physical systems, an authentic linkage between physical items and their digitalrepresentations can be established on the blockchain through digital-physicalparity pattern. To prove the ownership of a product/item, a buyer could adoptthe ownership challenge pattern, which sends a cryptographic challenge to theseller and the seller signs it with the private key that owns the item. The buyercan verify the signature using the corresponding public key.Further, the oracle pattern can be used to introduce the external state/datainto the blockchain execution environment, which is self-contained. For example,a payment may be subject to an external state confirmed by a human (e.g.,a truck driver confirming the collection of an item) or an IoT device (e.g.,automatically report quality attribute of the item or its ambient conditions)through the oracle.Once the required transaction information is validated, the token(s) canbe transferred to the seller. The escrow pattern can be used for conditionalpayments, which is suitable for high-value, infrequent payments that requirestrong security guarantees. The escrow holds the deposited tokens until thepayment conditions are satisfied.
Multisignature pattern can be applied to signtransactions requiring the approval of multiple parties, e.g., to control the releaseof tokens held by an escrow. Please note that
Stealth address , Oracle , and
Multisignature can be enforced to a transaction with or without an escrow.To deal with frequent, low latency, and low-value payments, a payment chan-nel is designed to perform transactions off-chain with opening and final settle-ment transactions recorded on-chain. The authorised spender pattern is usedto allow a third-party (e.g., a smart contract) to spend a certain amount oftokens on behalf of the approver.
Token swap pattern enables users to tradedirectly between two types of tokens as an atomic swap. The stealth address burned tokens , which means the tokens are no longer us-able.
In this section, we present patterns that shape the architectural elements andtheir interactions in blockchain-based payment applications. Each pattern isdescribed following the extended pattern form in [17], which includes the patternname, summary, problem statement, forces that make the problem difficult tosolve, solution, consequences of applying the solution, and real-world knownuses.
Summary:
Tokens can be designed in a customised way using a token template that can be extended or instantiated.
Context:
Blockchain provides a trustworthy platform to realise tokenisation.In a blockchain application, a token represents a programmable digital unit ofvalue (i.e., assets) recorded on the blockchain for a specific purpose, like buyinga particular good or service. The same application may use different tokens, afood stamp issued for a child is usually different from an adult.
Problem:
A token is usually defined as a data structure embedded in a smartcontract to represent an asset. How can developers design and develop differ-ent types of tokens with a various features and operations defined for differentpurposes?
Forces: • Modularity.
A blockchain application might support different types of tokenswith different rules. • Interoperability and liquidity.
Tokens supported by different applicationsmight need to be exchanged frequently. • Vulnerabilities.
Handling tokens with a high value is risky, as lost tokenscannot be replaced/recovered on the blockchain. Further, vulnerabilities orbugs might be introduced when developing a blockchain-based application.Blockchain is by design an immutable data store. Hence, updating an alreadydeployed smart contracts could be impossible. This makes it difficult to fixbugs by releasing new versions of a smart contract.8 emplate_X Token_XTemplate_Y Token_YTemplate_Z Token_Z
On-ChainOff-Chain $$$
Template_XSource CodeTemplate_YSource CodeTemplate_ZSource Code
InstantiateDeploy
DeployDeploy InstantiateInstantiate
Figure 3: Token template. • Productivity.
Blockchain is an emerging technology with limited tooling anddocumentation. Thus, developers can have a steep learning curve, whichaffects the development productivity of blockchain applications. • Cost.
The use of templates increases the (gas) cost.
Solution:
Blockchain-based payment applications might need to issue differenttypes of tokens with customisation. Therefore, as shown in Fig. 3, a base tokencan be defined as a smart contract template that can be either extended orinstantiated by another smart contract to issue a new token at run time. In thetoken template, the user can define attributes and functions. The attributesusually consist of essential information (e.g., token name, symbol, number ofdecimal places, and type) and advanced features (e.g., minting process, initialdistribution, and burning process). The specified functions enforce rules thatgovern how the tokens are minted and transferred. The template can be storedon-chain as a factory smart contract or off-chain in a code repository. Op-tional properties and functions in the template allow customisation. If that isinsufficient, the template smart contract can be extended by another contractto support customised features. Once developed, the template would changerarely. Thus, it can be thoroughly tested and certified to be free of defects.There can be two types of tokens: cash tokens and voucher tokens.
Cashtokens are fungible tokens that are fully exchangeable with each other and canbe divided into smaller denominations for multiple transactions. In contrast, voucher tokens are non-fungible tokens that are unique and must be spent in9 single transaction regardless of the price of a product or service. Both cashtokens and voucher tokens can be considered as token templates. For example,in the cash token template, users can define the total supply of tokens.
Consequences:
Benefits: • Productivity and security.
A token template can support developing a par-ticular type of token by merely creating an instance of the token template.A well-defined and tested template simplifies blockchain application develop-ment and reduces time, and enhances security and reliability. • Modularity.
A blockchain application might support different types of to-kens with different rules. Use of token templates in the design can improvemodularity. • Interoperability and liquidity.
As the token template can comply with a tokenstandard, it offers high interoperability and liquidity, such as token transferand token swap due to the wide-spread use of the standards. • Simplicity.
Voucher tokens are easier to manage compared to cash tokens asthey typically have a single purpose. • Fungibility.
Cash tokens are more fungible than voucher tokens.Drawbacks: • Cost.
If a public blockchain is used, an extra cost is required to deploythe token template contract on the blockchain and call its token instancecreation function. Further, the generalisation of the template increases thecost of computational and storage complexity of smart contract, increasingthe transaction fees needed to manipulate it. • Productivity.
It takes time to design, develop, and test a token templatecarefully. However, this is a one time process.
Related patterns:
Policy contract , seller registry , token registry , and burnedtoken . Known uses: • ERC-20 and
ERC-721 have emerged as the de-facto standards for imple-menting fungible and non-fungible tokens in Ethereum and sister blockchains,respectively, by instantiating reference implementations such as OpenZeppe-line . • Lorikeet [18] is a model-driven engineering tool that provides templates forthe developers to customise fungible/non-fungible asset data schema and theresulting contracts based on ERC-20 and ERC-721 interface definitions. https://docs.openzeppelin.com/contracts oken Registry On-ChainOff-Chain
Buyer Seller
Request transfer
Product
Confirm transfer
Figure 4: Token Registry. • Token Mint is a tool to create tokens and crowdsale contracts without coding. • Token Launcher creates mintable ERC-20 tokens by setting the desired spec-ification. Summary:
A token registry maintains the ownership information of tokens bymapping the token identifier and wallet address.
Context:
A buyer (i.e., token owner) needs to pay a certain number of tokensto purchase a product or service. The payment application needs to manage alarge number of transacting parties, tokens, and transactions.
Problem:
When a payment is made, the respective number of tokens’ own-ership needs to be swapped from the buyer to the seller. Further, trackinghistorical ownership of tokens is often required to ensure traceability. Thus,it becomes challenging to track a large number of tokens, their owners, andtransactions. How can a large number of transactions be effectively tracked?
Forces: • Dynamism.
The ownership of tokens could change frequently. • Scalability.
A large number of token and their owners need to be mapped. https://tokenmint.io/ https://thetokenlauncher.com/ olution: As shown in Fig. 4, a token registry contract can be used to recordthe ownership information of tokens by mapping token identifier (ID) to thewallet address. Both token ID and wallet address are stored as variables in thetoken registry smart contract. This registry provides the ground-through ontoken ownership, as it could be manipulated only through the smart contractby authorised parties.Writing permission can be added through a permission control module, e.g.,only proceed ownership transfer if the token is in the given state or when thenew owner approves. Those conditions can be checked through a method inthe smart contract receiving tokens. If the conditions are not met, the smartcontract can throw an error rather than receiving the token.Benefits: • Upgradability.
Because the token ownership data are managed separately bythe token registry, rest of the smart contract code can be upgraded withoutchanging the token registry contract. • Cost.
By separating token ownership data from rest of the application code,there is no additional cost for data migration when the application logic isupgraded. • Traceability.
Traceability is enhanced, e.g., how much tokens are owned bywhom at what time is reflected in the registry.Drawbacks: • Cost.
Recording ownership data in smart contract incur an additional cost ifa public blockchain is adopted.
Related patterns:
Token template , burned token , and seller registry . Known uses: • Lorikeet [18] is a model-driven engineering tool that generates asset registrysmart contracts compliant with ERC-20 and ERC-721 standards. • Parity Token Registry enables all the registered token to be automaticallyvisible to all Parity wallet users. • Codefi provides an ownership registry for Universal token investors. Summary: A policy contract specifies the policies that a token must satisfy,e.g., whether a token must be spent on the product or services supplied byeligible sellers or how many tokens can be spent in a transaction. https://github.com/openethereum/token-registry https://github.com/ConsenSys/UniversalToken olicy On-ChainOff-Chain
BuyerSeller
Token
BindTransferReceive
Product $ Issuer
Figure 5: Policy Contract.
Context:
A payment should be settled only when specific business rules orpolicies are satisfied. For example, government support programs or charitabledonations usually indicate limits and constraints regarding products/servicescould be purchased, their quantities, and eligible sellers.
Problem:
Some policies stipulate how to use a particular group of tokenson blockchain-based payment applications. Preconfigured policies need to bechecked by the payment applications before allowing payment to occur.
Forces: • Diversity.
A variety of policies often governs the use of a token. They arechallenging to find and interpret in relation to one another. • Dynamism.
The policies or business rules might be dynamically attached/re-moved to/from tokens.
Solution:
As depicted in Fig. 5, a policy smart contract can be designed tospecify policies that a token must satisfy before use. For example, a policy couldindicate the attached token is spendable only on medicine, and the correspond-ing policy check logic could check whether a given pharmacy is a registered inthe approved seller registry for that medicine. The policy check logic is im-plemented as smart contract functions, which are invoked before the paymentfunction. When all the policies are satisfied, the buyer is allowed to make the13ayment. The mapping of policy contracts can happen at the level of either asingle or group of tokens.In some instances, policies are expected to remain the same until the tokenis redeemed (or at least within a given time window). In other cases, the policiesgoverning the tokens may change with time (e.g., changes in service agreements).Thus, the issuers may want to enforce the latest policy at the time of spending.In general, a policy contract needs to be designed with a generic interface suchthat it can be dynamically attached/detached to/from the token. Benefits: • Dynamism.
Policy contracts can be flexibly attached, updated, or removedfrom a token. • Diversity.
Policy contracts enhance diversity. Issuers can specify a variety ofpolicies in policy contracts for the usage of different tokens. • User Productivity.
Multiple policies and tokens could be automatically checkedwithout needing buyer and seller to interpret them manually.Drawbacks: • Cost.
If a public blockchain is used, an extra cost is required to deploy apolicy contract on blockchain and call its functions at the time of redeeming. • Developer Productivity.
Policies are challenging to codify; hence, it takes timeto design, develop, and test a policy contract carefully. However, this is a onetime process.
Related patterns:
Token template , seller registry , token registry , and burnedtoken . Known uses: • Making Money Smart [12] is a joint pilot project by the Commonwealth Bankof Australia (CBA) and CSIRO’s Data61 that attaches policy contracts toeach pouch of tokens issued to redeem National Disability Insurance Scheme(NDIS) benefits in Australia. The policy defines what healthcare servicescould be used, their quantities, and eligible sellers. • Smart Money [13] is a blockchain-based payment platform jointly developedby Kela (The Social Insurance Institution of Finland) and TietoEVRY in co-operation with Finnish Tax Administration, Financial Supervisory Authorityof Finland, and Borenius Attorneys. Spending rules are defined as constraintsfor smart money tokens, and are verified at the time of a transaction. • CAIPY [19] is a blockchain-based car insurance policy framework. In thedesign of
CAIPY , policy contracts model process fragments defined by the https://commbank.com.au/business/business-insights/making-money-smart.html https://tietoevry.com/en/campaigns/2020/smartmoney--a-conditional-digital-payment-guarantee/ oken Registry On-ChainOff-Chain
IssuerSeller
4. Redeem $ $
1. Request 2. Verify & burn3. Disable
Figure 6: Burned Token.physical insurance policies between customers and insurers. The policy con-tracts in
CAIPY only govern the conditions for claims, not the use of tokensas insurance payments.
Summary:
Once the redeem process is finalised, the spent tokens becomeundependable.
Context:
Once the sellers receive tokens from the buyers, they need to redeemthe tokens for fiat currency (e.g., US Dollars).
Problem:
Once the tokens are redeemed in return for a fiat currency payment,they should not be further usable (i.e., prevent double-spending).
Forces: • Double spending.
A token should be redeemed only once. • Complexity.
There might be a large number of redeemed tokens that need tobe maintained and tracked. • Vulnerability.
Vulnerability might exist if the token registry is not appropri-ately managed, e.g., the private key is stolen.
Solution:
As illustrated in Fig. 6, a seller redeem tokens with the token issuerusing the blockchain-based payment application. Once the redeemed, tokensneed to be permanently removed from circulation. This is achieved by destroyingor deactivating the redeemed token. This process is referred to as token burning and could be achieved in several ways. First, the seller can transfer the tokensto an unusable/invalid address (aka., burn address). Such an address should nothave a corresponding private key that can control the tokens it receives. The15econd way is to delete a token by calling the delete/burn function on the smartcontracts that created it. The third method is to to deploy a smart contractthat immediately self-destructs as soon as it receives a token. On the seller side,burned tokens could be moved to the token owner’s read-only token wallet thatcannot be operated by any party.
Consequences:
Benefits: • Redeem once.
Double spending is alleviated as the token is no longer spend-able or even exist. • Integrity.
The blockchain ensures the integrity of token status.Drawbacks: • Cost.
If a public blockchain is used, extra cost incurs when calling the smartcontract functions to burn the token. • Traceability.
The redeemed tokens cannot be tracked. On the seller side, thiscan be tracked by moving to the read-only wallet.
Related patterns:
Token template and token registry . Known uses: • Smart Money developed by TietoEVRY maintains burned tokens in a sep-arate wallet. • In Making Money Smart project, sellers can redeem smart tokens for pay-ment in Australian Dollars. • Binance burns BNB tokens quarterly until 50% of the total BNB ever issuedis burned. Summary:
A seller registry records the information of eligible sellers fromwhom the token can be spent to purchase products or services.
Context:
Buyers need to make payment using tokens to purchase products orservices or buy tokens in open markets.
Problem:
The token policy restricts sellers that a product or service could bepurchased. How can a buyer know whether a seller is eligible?
Forces: See footnote 10 See footnote 9 https://binance.com/en/bnb eller Registry On-ChainOff-Chain
Issuer
Register
Seller
Express interest
Figure 7: Seller Registry. • Diversity.
There are often a variety of policies for the usage of tokens. Theyare difficult to find and interpret in relation to one another. • Dynamism.
The eligibility policies or business rules might be dynamicallyattached/removed to/from tokens.
Solution:
Fig. 7 is a graphical representation of the pattern. Use a smartcontract registry contract to maintain the information of eligible sellers and theirattributes, e.g., names and wallet addresses. In the seller registry contract, eachseller attribute is stored as a smart contract variable. The seller registry contractcan enable the writing permission by adding a permission control module (e.g.,through modifiers in Solidity language). This ensures the value of contractvariables can only be updated by the permissioned users.The applications can have registry of products/services and even a matrixthat maps products and sellers. These are generalisations of this pattern The token registry design is similar to the seller registry , which can be considered aregistry pattern with multiple uses.Benefits: • Upgradability.
As the seller data are maintained separately from the rest ofblockchain application logic, the payment processing logic could be upgradedwithout affecting the seller registry contract. • Cost.
By separating seller data from rest of the application code, there isno additional cost for data migration when the application logic is upgraded.However, there could be additional cost for looking up the registry whileexecuting a transaction. • Generality and reusability.
The seller registry contract can be used by allrelated business logic contracts.Drawbacks: • Cost.
If a public blockchain is used, storing data in a smart contract introduceextra cost. Further, there could be additional cost for looking up the registrywhile executing a transaction. 17 elated patterns:
Policy contract , token template , token registry , and burnedtoken . Known uses: • Making Money Smart project in Australia uses a seller registry contract tomaintain all the registered seller information. • Stadjerspas Smart Vouchers is a blockchain-based voucher platform thatprovides discounted services to low-income citizens of Groningen. Smartvouchers can be only be redeemed for products or services from the regis-tered providers. • Pension Infrastructure is a blockchain-based pension administration appli-cation which maintains a list of pension fund providers. Summary:
To prove the ownership of an item, a buyer sends an ownershipchallenge to a seller. The seller signs it with the private key that owns the item,and the buyer can verify the signature using the respective public key.
Context:
In a blockchain-based payment application, a buyer needs to paytokens to a seller to purchase an item. However, buyer is concerned whetherthe seller has the ownership of the item to be purchased.
Problem:
As a payment on a blockchain is settled once a transaction is finalised(i.e., included in a block and achieve the desired number of block confirmations),how can the buyer confirms the seller’s ownership of the item before making thepayment?
Forces: • Immutability.
A payment cannot be reversed if item is later found to befraudulent. • Vulnerability.
Digital assets are relatively easier to spoof and double spend.Also, a physical proof of ownership documents might be counterfeit and vul-nerable to attacks. • Cost.
Additional costs are usually involved in preparing a physical documentto prove the ownership of an item.
Solution:
Fig. 8 is a graphical representation of the pattern. First, the applica-tion can generate a random challenge on the buyer’s end and send to the seller.Once received, the seller signs the challenge using the private key that is usedto manage the item to be sold and then sends the signed message back to the See footnote 9 https://stadjerspas.nl/ https://apg.nl/en/publication/apg-and-pggm-develop-a-blockchain-application-for-pension-administration/ eller Registry On-ChainOff-Chain
BuyerSeller
String checkString
Figure 8: Ownership Challenge.buyer. The buyer verifies the signature with the seller’s public key registered asthe owner of the item. This proves that the seller has authority to manage theitem to be sold.Usually, the challenge is specified as a random string to prevent replay at-tacks. Alternatively, the seller can update the item’s status using its privatekey, e.g., changing the status of an item from “selling” to “ready to be sold tobuyer X”. However, as such strings expose sensitive information, it could leadsto privacy issues or invite front running . Consequences:
Benefits: • Vulnerability.
While the blockchain ensures uniqueness of the item by pre-venting double spending, proof of ownership ensures seller’s ownership of itwithout requiring a physical proof of ownership. • Simplicity.
The ownership of an item can be automatically proved betweenthe buyer’s and seller’s applications. • Robustness.
The proof of ownership established through an ownership chal-lenge string is robust to attacks compared to the possibilities, such as fakephysical proof of ownership documents. • Cost.
If the ownership challenge is handled off-chain, there is no cost togenerate the ownership challenge and verify it.Drawbacks: https://belavadi.github.io/smart-contract-best-practices/ Connectivity.
Either handled on-chain or off-chain, the ownership challengerequire network connectivity. • Cost.
There’s a cost if the challenge is generated and checked on-chain.
Related patterns:
Token registry
Known uses: • SPKAC is a command that processes Netscape signed public key andchallenge (SPKAC) files for signature verification. • X.509 PKI provides a security infrastructure that includes steps of challengestring encryption and decryption for identity verification. • One-Time Password for Information Handling Resource is granted throughverifying the digital signature on a challenge string. Summary:
The buyer can validate the seller’s business qualification throughseller credentials.
Context:
In blockchain-based payment applications, different policies stipulaterules for the usage of tokens.
Problem:
A token includes specific policies that limits the conditions underwhich a token can be spend/redeemed, such as eligible products or services andtheir sellers. Therefore, how can the buyer verify the proof of eligibility of thesellers before transferring a token to buy a product or use a service?
Forces: • Immutability.
A payment cannot be reversed if a token is later found to beineligible to spend for the chosen product, service, or its seller. • Privacy.
The disclosed eligibility information should contain minimum datanecessary to identify relevant aspects of oneself without revealing extra infor-mation. • Authentication.
Authenticity of proof of eligibility documents must be en-sured as the proof documents might be counterfeit.
Solution:
Fig. 9 illustrates how a seller credential is registered and verified.First, the seller applies for a credential from the token issuer. Once approved,the credential is stored in the seller’s wallet and maintained by the credentialregistry. Third, a token is designed by attaching a set of constraints that defines https://openssl.org/docs/man1.0.2/man1/spkac.html https://itu.int/rec/T-REC-X.509 https://patents.google.com/patent/US9053305 ssuerSeller $ Buyer
RegisterIssue
On-ChainOff-Chain
Send credentialcredential
Verify
Figure 9: Seller Credential.the requested credential type(s). Fourth, when a token requires a specific cre-dential from the seller before spending, the seller can present the credential tothe token owner (i.e., buyer) as a proof of eligibility through the respective shar-ing functionality provided by the seller wallet. Finally, the buyer then validatesthe credential from the credential registry.The credential registry could be implemented similar to the seller registry .Specific use cases also require credential of the buyer to be validated by theseller. For example, the seller may want to validate the buyer’s age or whetherthe buyer has the right to spend the given token. In such cases, the pattern canbe applied by interchanging the role of seller and buyer.
Consequences:
Benefits: • Immutability.
As the seller’s credential are verified before initiating the pay-ment, need for payment reversal does not arise. • Authenticity.
Authenticity of credentials can be guaranteed by digital signa-tures. • Reusability.
The seller credential can be used for all related tokens associatedwith the same constraint policy. • Cost.
No cost is involved in sharing the credential to different buyers.21rawbacks: • Upgradability.
The credential details cannot be updated once it is issued to aseller.
Related patterns: distributed oracle , policy contract, seller registry, tokentemplate, token registry Known uses: • Smart money developed by TietoEVRY defines spending rules for tokens.Credentials are created and issued to the registered merchants. Credentialsneed to be checked before making the payment. • Sovrin provides a blockchain-based self-sovereign identity infrastructure toissue credentials. • uPort Serto provides a blockchain-based credential management platformto achieve self-sovereign identity. Summary:
Before making a transaction, tokens are transferred to a third-partysmart contract called the escrow . The escrow holds the deposited tokens untilthe payment conditions are satisfied.
Context:
The parties involved in the transaction need to ensure both theagreed product/service is delivered and payment is made. One party should notbe able to default the transaction at the expense of the other party.
Problem:
How to ensure the buyer gets the desired product/service whileensuring the seller gets the payment?
Forces: • Trust.
It is hard for the parties involved in a transaction to completelytrust a third party with their private information and funds. • Efficiency.
It is time-consuming to establish a trust account and regulatethe funds in a centralised payment system. • Cost.
Centralised payment systems often charge expensive fees for trustaccount services. • Security.
Because funds are controlled from a single point, there is apossibility of funds being stolen or mistakes being made. • Volume.
Buyers and sellers may be engaged in a large number of transac-tions. 22 scrow
On-ChainOff-Chain
Buyer Seller $
1. DepositTokens
Product
4. Release Tokens 3. Check Conditions2. Deliver
Figure 10: Escrow.
Solution:
As seen in Fig. 10, a smart contract can play the role of an escrowthat holds the fund until the payment conditions are fulfilled. First, specify thesettlement procedure and conditions as a smart contract. The security of escrowfunctionality implemented by the smart contract can be ensured as the smartcontract code is immutable once it is deployed on the blockchain. This givesthe parties involved in the transaction confidence that they will not be cheatedduring the trading. Second, the buyer transfers the token(s) to the escrowsmart contract. Third, when release conditions are met by providing the desiredproduct/server, the respective event is informed to the escrow smart contract.Finally, the escrow then validates the pre-defined conditions and releases thetokens to the seller. If the respective event is not informed to the escrow withinthe stipulated time or the event indicates that the product/service was notdelivered as per the agreed terms, then the tokens are sent back to the buyer.If the payment conditions depend only on on-chain data, then a deligated callcan be made to the escrow contract to inform the delivery of product/service. Ifthe payment conditions depend on external data like the shipment of a product,then an oracle can be used to provide desired data to the escrow.
Consequences:
Benefits: • Trust.
An escrow smart contract reduces the risk of fraud and mistakesby acting as a neutral party. • Transparency.
Operations happening in the system are transparent. See footnote 10 https://sovrin.org https://serto.id Efficiency.
Blockchain eliminates the need for third-parties, which in turnhelps to reduce cost in a transactions and enhance service efficiency.Drawbacks: • Privacy.
As all blockchain transactions are transparent, escrow transac-tions can potentially leak sensitive business information, e.g., the rate ofdisputes with customers. • Cost.
Transaction fees need to be paid to deploy and execute escrow smartcontracts on public blockchains.
Related patterns:
Token registry , oracle , multisignature , and stealth address . Known uses: • Kleros Escrow is a blockchain based trustless dispute resolution platformwhich provides escrow services for cross-chain asset swaps. • Counos is a blockchain platform based in Switzerland, which offers fi-nancial and payment services includingmultisignature-based escrow for cryptocurrencies. • IBC Group is a blockchain financial services company that offers smartcontract based cryptocurrency escrow services charging 1% fee in fiat cur-rency. Summary:
A two-way pathway (aka., payment channel) is established betweentransacting parties to perform transactions off-chain while recording openingand final settlement transactions on the blockchain.
Context:
A set of low-value payments are to be made frequently, e.g., a smallpayment paid every time a WiFi service is used.
Problem:
If a public blockchain is used, micro-payments are too expensive tomake as the transaction fee might be higher than the monetary value withinthe transaction. Also, it takes time to achieve finality on a blockchain. There-fore, how can frequent payments be processed without waiting a long time andincurring high transaction fees?
Forces: • Latency.
It might take long time to commit a transaction on blockchainalthough users usually expect payment to be settled instantaneously. • Cost.
If a public blockchain is used, storing data on-chain costs transactionfee, which might be higher than the monetary value of the payment.24 n-ChainOff-Chain
BuyerSeller
3. Settlement
Payment Channel
1. Initial deposit1. Initial deposit
2. Subsequent transactions
Figure 11: Payment Channel.
Solution:
As depicted in Fig. 11, a two-way pathway (aka., payment channel )can be established between two parties to handle frequently occurring transac-tions. First, an initial deposit is made from one or both parties and locked upas a security in a smart contract on the blockchain. Then the payment chan-nel records the digitally signed intermediate transactions off-chain. When thesettlement is to be made, each party’s closing balance is informed to the smartcontract. Finally, the smart contract adjusts the balance of transacting partieson the blockchain.Recorded intermediate transactions may also be sent to the smart contractas proof if there is any dispute. Settlement on the blockchain can also be doneperiodically depending on the agreement between the involved two parties.
Consequences:
Benefits: • Performance.
The off-chain micro-payment transactions can be settledinstantaneously without waiting for finality on blockchain. • Throughput.
A much higher throughput can be achieved by off-chainpayment channels. • Privacy.
Intermediate transactions processed by payment channels arenot publicly available. https://kleros.io/en/escrow https://counos.io https://ibcgroup.io Cost.
If a public blockchain is used, only the final settlement transactionincur transaction fee cost.Drawbacks: • Data Integrity.
The data integrity of the intermediate state of paymentchannels cannot be ensured because micro-payment transactions are notstored on-chain. • Lack of Liquidity.
To establish a payment channel, tokens from one orboth involved parties of the channel needs to be deposited in a smartcontract during the lifecycle of the payment channel.
Related patterns:
Token registry . Known uses: • Bitcoin Lightning Network adopts an off-chain protocol to enable micro-payments. It only broadcasts the final version of the funding transactionto settle the payment in Bitcoin network. • Ethereum Raiden Network uses a network of off-chain payment channelsthat enables secure money transfer. • Ethereum State Channel provides a channel protocol that supports ex-changing state for general-purpose blockchain applications. Summary:
An authentic linkage between a physical product and its digital rep-resentation (i.e., token) is established on the blockchain to protect the integrityof the physical product.
Context:
Fraud, including both product fraud andcurrency/token fraud, has an adverse impact in trading. Lack of transparencyis considered as a major factor leading to fraud. Blockchain is introduced toenable transparency and visibility of supply chain as every participant withinthe blockchain network can access all the historical records on blockchain.
Problem:
Blockchain can only guarantee the integrity of the digital repre-sentation of a physical item (i.e., product or token/currency), not the physicalattributes of a physical item. How can a buyer verify the connection betweenthe physical item and its digital representation?
Forces: • Vulnerability.
Existing tagging technologies (e.g., QR codes or barcodes) arevulnerable to attacks. For example, a counterfeit item can be easily attachedwith an authentic tag. https://blockstream.com/lightning/ https://raiden.network/ http://jeffcoleman.ca/state-channels/ n-ChainOff-Chain Product
Physical attributes
Product RegistryPhysical Token
Physical attributes
Token Registry $ Figure 12: Digital Physical Parity. • Diversity.
The characteristics of an item is usually diverse and rich, which isdifficult to capture.
Solution:
As illustrated in Fig. 12, a physical item’s integrity can be verifiedby connecting the physical item with its digital representation. The physicalattributes of an item (e.g., chemical composition, geo-location, and visual fea-tures) can be extracted via various techniques, such as genomics analysis, iso-tope analysis, and machine learning. The captured attributes can be digitallyrecorded on the blockchain to ensure immutability and transparency. An inven-tive mechanism could be applied to encourage active participants to contributeto assessing the claimed physical attributes.
Consequences:
Benefits: • Originality.
The transactions on blockchain enables the buyers or other stake-holders to assess the authenticity and trace the orginality of the item. • Robustness.
The linkage established between a physical item and its digitalrepresentation through physical attribute extraction is robust to attacks. • Integrity.
The integrity of the physical item is guaranteed by both the collec-tion and storage of the physical attributes.Drawbacks: • Cost.
It is often costly and time-consuming to capture the physical charac-teristics of an item and provide test results, e.g., through isotope analysis orAI-based visual feature detection. • Integrity.
The integrity of the physical item might be screwed when theattribute extraction technique is compromised. For example, the isotope testresult might be manipulated by a dishonest lab operator.27 elated patterns: distributed oracle , redundant device , policy contract Known uses: • AI-based Digital-Physical Parity [20] is a solution that uses machine learningmodels to distinguish between grass-fed and grain-fed beef. Blockchain isadopted to store the respective dataset registry and model registry. • Stable Isotope Ratio Analysis [21] is used on muscles of cows to assess beefauthenticity. • Ripe blockchain partners with Neogen to provide a DNA based blockchainplatform to ensure quality and orginality of food. Summary:
Use a one-time address (aka., stealth address) for the transactionto protect the the privacy of the parties involved in the payment.
Context:
Sellers and buyers are engaged in multiple transactions and are con-cerned about their privacy. A blockchain transaction is pseudonymous, i.e.,while buyer’s or seller’s address is linked to an entity, the entity is unknown tothe public.
Problem:
Transacting entities are only identified by their addresses on theblockchain. However, as the transaction details are visible to anyone on theblockchain network, by analysing the transaction graph, flow of tokens, andother external information, third parties could correlate the transactions andobserve buyers’ and sellers’ behaviour and identify the entity behind an address.How can transacting parties protect their privacy when engaging in a largenumber of transactions?
Forces: • Privacy.
It is possible to correlate transactions and reveal the real-worldidentity by linking transactions with other data (e.g., IP address). • Volume.
Buyers and sellers may engage in a large number of transactions. • Traceability.
With the use of blockchain, transacting parties and regulatorsexpect to track the flow of tokens. • Auxiliary information.
Depending on the use case, buyers and sellers’ infor-mation may be available on-chain (e.g., seller registry ) or off-chain (e.g., tradereports and census data). ripe.io https://neogen.com/ tealth address On-ChainOff-Chain
Buyer
Seller
CreateShare key/secret/address
Figure 13: Stealth Address.
Solution:
Fig. 13 is a graphical representation of the pattern. First, the sender(i.e., buyer) creates a one-time address for each transaction on behalf of the re-cipient such that different transactions sent to the same recipient are unlinkable.The new address used for a transaction is called the stealth address .The new account could be shared with the corresponding party using severaltechniques. In the simplest form, the seller could create a new account andinform it to the buyer off-chain, e.g., an invoice can contain the new address.Another option is to share a key/secret between the two parties that can be usedto generate a new account for each transaction. For example, a one-time secretcan be shared between the parties to use as the seed to create a private/publickey pair of a new account. Then the hash of that key can be used to createthe new account. This could be extended to a hash chain, where each roundof hashing produces a datum that can be used as the seed to create a newprivate/public key pair.
Consequences:
Benefits: • Privacy.
As a new address is used for each transaction, it is difficult to corre-late and trace transactions on the blockchain. This enhances the protectionof the real-world identity of the recipient.Drawbacks: • Traceability.
As new addresses are created based on an off-chain logic/secret,it is difficult to track transactions targeted to the same physical recipient.Such lack of tracability could be leveraged to to engage in illegal activities.29
Volume.
The recipient of payments will find it difficult to link, reconcile, re-deem, and manage transactions as each transactions is linked to a differentaddress. Moreover, transactions may still contain additional details such aproduct/service types and quantities, when aggregated, could reveal trans-acting parties behaviour and identity. Furthermore, if the recipient wantsto later aggregate tokens without revealing its identity, it has to use tokenmixing services, which incur additional costs.
Related patterns: token registry and escrow . Known uses: • Basic Stealth Address Protocol (BSAP) was developed in 2011, whichadopts the Elliptic Curve Diffie-Hellman (ECDH) protocol in the design todeal with Bitcoin transactions. • Improved Stealth Address Protocol (ISAP) is a upgraded version of BSAPwith an additional key creation feature. The recipient is the only entity thatcan compute the private key for the temporary address to receive Bitcoin. • To address the issue of overuse of private spending key,
Dual-Key StealthAddress Protocol (DKSAP) is designed for a wallet solution ShadowSend uses two pairs of keys, a scan key pair and a spend key pair, to providedecentralised anonymous currency. Summary:
To examine the fulfilment of payment conditions, an oracle is usedto introduce the state of external systems into the closed blockchain executionenvironment.
Context:
The payment is conditional on physical properties of a product/ser-vice or completion of a real-world action, e.g., quality attributes of a product orshipment of a product. Typically such data are provided or certified by thirdparties.
Problem:
The state of external systems is not directly accessible to smartcontracts, as blockchain’s execution environment is self-contained. Further, boththe transacting parties need to agree on the state of a product and its attributes.How to fetch external data/data into a smart contract to decide on a paymentcondition?
Forces: • Connectivity. blockchain-based payment applications might require exter-nal state data, e.g., temperature of a container. However, blockchain is https://lists.linuxfoundation.org/pipermail/bitcoin-dev/2014-January/004020.html https://bytecoin.org/old/whitepaper.pdf https://github.com/shadowproject n-ChainOff-Chain Other Components
Smart Contract
OracleOracle
Oracle
Figure 14: Oracle.a self-contained execution environment. Smart contracts in blockchain-based payment applications cannot read the state data of the externaldevices or systems. • Trust.
Both the transacting parties need to agree on the state of a prod-uct and its attributes. When such data are provided by a third-party,the third-party needs to be trustable to transacting parties including anyregulators. • Availability.
The external dependent devices or systems may change oreven disappear.
Solution:
As seen in Fig. 14, use a third-party hosted smart contract to pro-vide data to the blockchain from external servers, websites, and IoT devices.These elements call functions on the smart contract to record the data on theblockchain using their private key attesting the data origin. The system consist-ing of the smart contract and external elements are referred to as an oracle . Thepayment application can then make a deligated call to oracle smart contract toaccess the external data.There are two types of oracles: centralised and decentralised oracles. A cen-tralised oracle introduces a single trusted third-party into the system, whichmight become a single point of failure. Alternatively, a decentralised oracle isdesigned based on multiple servers and multiple independent data sources, over-coming the single point of failure. A decentralised oracle can use multisignature to reach a consensus on the state data to be injected into the smart contract.Similarly, at the hardware level, deploying redundant IoT devices is considereda solution to deal with adversary IoT devices that produce malicious data. Across-check can be done for the data collected by different IoT devices.
Consequences:
Benefits: 31
Connectivity.
The smart contracts of blockchain-based payment applica-tions can access external states through the oracle. • Trust.
A decentralised oracle increases the trust as it relies on trust onmajority of third-parties. • Availability
A decentralised oracle can remove the risk of a single point offailure and increase availability.Drawbacks: • Trust.
A centralised oracle is a third-party integrated into the system,which needs to be trusted by all the stakeholders involved in payment. • Data Integrity.
Validators can only check the digital signature of the ora-cle, but cannot check the correctness or originality of the injected externaldata. • Availability
A centralised oracle is a trusted third party, whose behaviormay lead to the risk of a single point of failure. • Cost.
There is a cost in injecting data into oracle smart contract and toget/look-up data from the oracle. Further, the cost of injecting data fromexternal world increases with the number of oracles being used. • Time.
It might take longer time for the decentralised oracle to reach aconsensus over the final state data to be injected.
Related patterns: redundant device , multisignature . Known uses: • Oracle in Bitcoin is a server outside the Bitcoin blockchain, whichcan evaluate user-defined condition expressions for payment based on theexternal state data. • Provable is an oracle provider, which utilises trusted hardware to directlycollect data from the external environment, which can be used to checkpayment conditions. • Orisi is an oracle framework for Bitcoin smart contracts, which enablesthe transaction participants to select a set of oracles and apply multisig-nature. https://en.bitcoin.it/wiki/Contract\ https://provable.xyz/ http://orisi.org/ mart Contract On-ChainOff-Chain
Authority N
M-of-N ......
Authority M Authority 1
Figure 15: Multisignature.
Summary:
Given a pool of n addresses that could authorise a payment, get asubset m of them to authorise a payment by signing the respective transaction( m ≤ n ). Context:
A transaction need to be authorised by multiple parties (i.e., blockchainaddresses), e.g., release tokens held by an escrow.
Problem:
Addresses that are authorised to approve a payment might not bedecided when the smart contracts are deployed on the blockchain. How cana transaction be approved, even if some of the authorised addresses are notavailable or unreachable when issuing the transaction?
Forces: • Dynamism.
The transaction authorities might not be decided when thesmart contracts are deployed on blockchain. Ever if decided, their ad-dresses need to be changed as the payment application evolves, e.g., addi-tion of a new authority or revocation of an authority. • Tolerance of lost key.
Losing a private key on blockchain means permanentloss of control over a blockchain account and associated smart contractsas blockchain does not provide any key recovery mechanism.
Solution:
As depicted in Fig. 15, to enable flexible binding of authorities for apayment transaction, a multisignature mechanism can be designed to require m n private keys to authorise a transaction, in which m is the threshold ofauthorisation. Users can pre-define a group of blockchain addresses which canauthorise a payment transaction and set the minimal number of authorisationsto approve a payment transaction. The users need to select a smart contractthey write, and the respective payment function that needs the multisignaturemechanism. Consequences:
Benefits: • Dynamism.
Multisignature allows flexible binding of authorities for ap-proving a transaction. • Tolerance of lost keys.
The risk of losing control over smart contracts isreduced as one participant can have more than one blockchain address incase a private key is lost.Drawbacks: • Risk of losing keys.
There is still risk of losing control over smart contractswhen m private keys among the n private keys are lost. • Cost.
If a public blockchain is adopted, storing multiple addresses orupdating the list of addresses costs money.
Related patterns: escrow . Known uses: • MultiSignature is offered by Bitcoin blockchain network to sign on trans-actions. • Multisignature wallet is provided in the Ethereum Mist DApp browser to approve transactions. Summary:
Token swap allows users to trade directly between two types oftokens as an atomic transaction.
Context:
In blockchain-based payment applications, there might be differenttypes of tokens supported.
Problem:
How can users buy and sell tokens for other types of tokens withoutthe risk of other-party not transferring their token?
Forces: • Liquidity.
Users might need to convert tokens to other types of tokens forbetter liquidity. https://en.bitcoin.it/wiki/Multisignature https://github.com/ethereum/mist oken_X Registry On-ChainOff-Chain
User A
User B $ Token_Y Registry $ HTLC $
1. Initiatetrade2. Accept trade
3. Update ownership4. Claim tokens 3. Update ownership4. Claim tokens
Figure 16: Token Swap. • Atomicity.
Token swap is expected to be atomic exchange of tokens basedon an amount agreed by both parties of the transaction.
Solution:
Fig. 16 illustrate the steps involved in swapping two tokens. Atoken swap is an agreement between two parties that swap different types oftokens (say token A and token B). In a token swap, one party will pay a certainamount of token A to the other party and receive the agreed amount of tokenB in return. The token swap process can be managed using a Hashed TimelockContract (HTLC). First, a HTLC smart contract is deployed to the blockchainthat could validate an off-chain secret. Second, the agreed amounts of tokensare deposited to the specified smart contract. Third, the off-chain secret is sentto the HTLC contract using a transaction to claim on of the tokens. Finally,as this transaction reveals the secret, the other party can also claim its tokensusing the same secret.The token swap process is more complicated when token swaps are acrossblockchains. A pair of intermediate HTLCs are needed for the involved blockchains.The ownerships of tokens are updated once the agreed amounts of tokens aretransferred to the respective HTLCs.
Consequences:
Benefits: • Liquidity.
The users can use the owned tokens to buy more popular typesof tokens to increase liquidity. • Data Integrity.
The data integrity of the swapped tokens can ensured sincethe token swap process and respective transactions are stored on-chain.35
Atomicity.
The atomicity of token swap is guaranteed by smart contracts. • Cost.
As the token swap process can be managed by smart contracts,there is no third party service fee incurred. • Interoperability.
Interoperability is increased through cross-chain tokenswap.Drawbacks: • Privacy.
Token swap transactions are publicly available. • Cost.
There might be additional cost due to the exchanged rate. Also, ifa public blockchain is used, updating token ownership causes extra cost. • Lack of flexibility. If a party does not withdraw tokens out in time, thedeposited tokens will be locked for a certain period of time.
Related patterns: token registry , escrow . Known uses: • Metamask supports token swap feature to compare and swap tokensdirectly within the wallet and browsers. • Kaileido offers a simple way to securely swap tokens using Hashed Time-lock Contracts. • AirSwap supports atomic token swap with guaranteed price. Summary:
An authorised third-party spender is allowed to spend a certainamount of tokens owned by the approver.
Context:
In blockchain applications, buyers need to transfer tokens to sellersin order to buy goods or services.
Problems:
How can a buyer delegate a third-party to pay on behalf of them?
Forces: • Vulnerability.
The approve process needs to be secure in case there is adishonest delegate. • Complexity.
It is usually complex to delegate a third party to pay onbehalf of token owners. https://metamask.io/ oken Registry On-ChainOff-Chain
User_A
User_B $$ Approve(User_A, amount)
Figure 17: Authorised Spender.
Solution:
As seen in Fig. 17, a token owner can approve a third-party useror a smart contract to transfer a certain amount of tokens on their behalf. Anapprove step can be designed to allow the spenders to use a certain amount oftokens. For example, an approve function can be added to the token templatecontract with spender address and amount as parameters.
Consequences:
Benefits: • Flexibility.
Buyers can find a delegate to pay on their behalf with presetamount. • Simplicity.
The buyers do not have to send two transactions. • Security.
The tokens are transferred securely according to the conditionspredefined in smart contracts.Drawbacks: • Cost.
If a public blockchain is used, additional cost is incurred to call theapproval function. • Security.
There might be a bug in the smart contract that results in un-expected transfers (e.g., wrong address or amount). If the smart contractis hacked, the attacker could potentially steal all of the users’ tokens.
Related patterns: token template . Known uses: Both
ERC-20 and ERC-721 use an Approve function to enable athird party or a smart contract to transfer a certain amount of tokens. • Ethex supports custom allowance for token trading. • Saturn Network offers approve feature that allows users to submit atransaction to approve Saturn Network trade their tokens on their behalf. To systematically organise knowledge on designing payment applications us-ing blockchain, we collected 15 design patterns that cover critical aspects ofblockchain-based payment applications. We identify the lifecycle of a token,in which the state transitions are associated with the collected patterns. Thelifecycle along with the annotated design patterns, provide a payment-focusedsystematic view of system interactions and a guide to the effective usage of thedesign patterns in software architecture design. We will extend our decisionmodel to select blockchain-based patterns to include payment patterns in thefuture.
References [1] A. Bratanova et al. , 2018, pp. 1–20.[3] Y. Liu, Q. Lu, X. Xu, L. Zhu, and H. Yao, “Applying design patterns insmart contracts,” in
Blockchain – ICBC 2018 , S. Chen, H. Wang, and L.-J.Zhang, Eds. Cham: Springer International Publishing, 2018, pp. 92–106.[4] M. Wohrer and U. Zdun, “Smart contracts: Security patterns in theEthereum ecosystem and Solidity,” in . IEEE, 2018, pp. 2–8.[5] Q. Lu and X. Xu, “Adaptable blockchain-based systems: A case study forproduct traceability,”
IEEE Software , vol. 34, no. 6, pp. 21–27, November2017. https://eips.ethereum.org/EIPS/eip-20 https://eips.ethereum.org/EIPS/eip-721 https://ethex.market Future Generation Computer Systems , vol. 92, pp. 399–406, 2019.[7] Q. Lu, X. Xu, Y. Liu, I. Weber, L. Zhu, and W. Zhang, “ubaas: A unifiedblockchain as a service platform,”
Future Generation Computer Systems ,vol. 101, pp. 564–575, 2019.[8] M. Bartoletti and L. Pompianu, “An empirical analysis of smart contracts:Platforms, applications, and design patterns,” in
Int. Conf. on FinancialCryptography and Data Security . Springer, 2017, pp. 494–509.[9] J. Eberhardt and S. Tai, “On or off the blockchain? Insights on off-chainingcomputation and data,” in
European Conf. on Service-Oriented and CloudComputing . Springer, 2017, pp. 3–15.[10] P. Zhang, J. White, D. C. Schmidt, and G. Lenz, “Applying softwarepatterns to address interoperability in blockchain-based healthcare apps,” arXiv preprint arXiv:1706.03700 , 2017.[11] X. Xu, H. M. N. D. Bandara, Q. Lu, I. Weber, L. Bass, and L. Zhu, “Adecision model for choosing patterns in blockchain-based applications,” in
Financial Cryptography and Data Security , A. Kiayias, Ed. Cham:Springer International Publishing, 2017, pp. 321–339.[15] Y. Liu, Q. Lu, H.-Y. Paik, and X. Xu, “Design patterns for blockchain-based self-sovereign identity,” in , 2020.[16] V. Garousi, M. Felderer, and M. V. M¨antyl¨a, “Guidelines for includinggrey literature and conducting multivocal literature reviews in softwareengineering,”
Information and Software Technology , vol. 106, pp. 101 –121, 2019.[17] D. J. Meszaros and J. Doble, “A pattern language for pattern writing,” in
Proc. Intl. Conf. on Pattern Languages of Program Design , Oct. 1997.3918] Q. Lu et al. , “Integrated model-driven engineering of blockchain applica-tions for business processes and asset management,”
Software: Practiceand Experience , pp. 1–21, 2020.[19] L. Bader, J. C. B¨urger, R. Matzutt, and K. Wehrle, “Smart contract-basedcar insurance policies,” in ,2018, pp. 1–7.[20] S. K. Lo et al. , “Digital-physical parity for food fraud detection,” in
Blockchain – ICBC 2019 . Springer International Publishing, 2019, pp.65–79.[21] M. T. Osorio, A. P. Moloney, O. Schmidt, and F. J. Monahan, “Beef au-thentication and retrospective dietary verification using stable isotope ratioanalysis of bovine muscle and tail hair,”