40,81 €
A practical blockchain handbook designed to take you through implementing and re-engineering banking and financial solutions and workflows using eight step-by-step projects
Key Features
Book Description
Blockchain technology will continue to play an integral role in the banking and finance sector in the coming years. It will enable enterprises to build transparent and secure business processes. Experts estimate annual savings of up to 20 billion dollars from this technology. This book will help you build financial apps using blockchain, guiding you through enhancing popular products and services in the banking and finance sector.
The book starts by explaining the essential concepts of blockchain, and the impact of blockchain technology on the BFSI sector. Next, you'll delve into re-designing existing banking processes and building new financial apps using blockchain. To accomplish this, you'll work through eight blockchain projects. By demonstrating the entire process, the book helps you understand everything from setting up the environment and building frontend portals to system integration and testing apps. You will gain hands-on experience with the Ethereum, Hyperledger Fabric, and Stellar to develop private and public decentralized apps. Finally, you'll learn how to use ancillary platforms and frameworks such as IPFS, Truffle OpenZeppelin, and MetaMask.
By the end of this blockchain book, you'll have an in-depth understanding of how to leverage distributed ledgers and smart contracts for financial use cases.
What you will learn
Who this book is for
This book is for blockchain and Dapps developers, or anyone looking for a guide to building innovative and highly secure solutions in the fintech domain using real-world use cases. Developers working in financial enterprises and banks, and solution architects looking to build brand new process flows using blockchain technology will also find the book useful. Experience with Solidity programming and prior knowledge of finance and trade are required to get the most out of this book.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 524
Veröffentlichungsjahr: 2020
Copyright © 2020 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Sunith ShettyAcquisition Editor:Aniruddha PatilContent Development Editor:Nazia ShaikhSenior Editors: Jack Cummings and Sofi RogersTechnical Editor: Utkarsha S. KadamCopy Editor: Safis EditingProject Coordinator:Aishwarya MohanProofreader: Safis EditingIndexer:Tejal Daruwale SoniProduction Designer:Alishon Mendonsa
First published: January 2020
Production reference: 1310120
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-83882-909-4
www.packt.com
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Ishan Roy leads the blockchain initiative at the Centre of Excellence for Emerging Technologies (CEET) at the Tamil Nadu e-Governance Agency (TNeGA). He is currently working on the Tamil Nadu Blockchain Backbone project. His work with blockchain began in 2016, with the blockchain team at ICICI Bank. This team carried out the first blockchain remittance in India. Since then, he has worked as the head of products at HashCash Consultants, where he built blockchain-enabled financial solutions for global clients. He has also mentored students and industry veterans as a blockchain trainer with Edureka. He is extremely passionate about technology and loves to keep himself abreast of new developments in the field through the community.
Narendranath Reddy is an experienced full-stack blockchain engineer and Hyperledger Fabric expert with a track record of helping enterprises to build production-ready, blockchain-backed applications. He is an experienced innovator and creative thinker. He has won four hackathons on blockchain and is a keynote speaker, regularly speaking about blockchain and distributed ledgers. He is currently working as a blockchain software engineer at Consensys, Dubai, and previously worked as a blockchain developer at Blockgemini, Dubai, and as a software developer at UST Global, Trivandrum, and Madrid, Spain.Samanyu Chopra is a developer, entrepreneur, and blockchain supporter with broad experience in conceptualizing, developing, and producing computer and mobile software. He has been programming since the age of 11. He is proficient in programming languages such as JavaScript, Scala, C#, C++, and Swift. He has a wide range of experience in developing computers and mobiles. He has been a supporter of Bitcoin and blockchain since its early days and has been part of wide-ranging decentralized projects for a long time. You can connect with him via Linkedin.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Blockchain Development for Finance Projects
About Packt
Why subscribe?
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Section 1: Blockchain Payments and Remittances
Blockchain in Financial Services
Present-day banking and finance systems
Understanding blockchain technology
Blockchains for financial services
How to approach implementing a blockchain solution
Implementation strategies 
Popular distributed ledger platforms for financial applications
Ethereum 
Hyperledger Fabric
Stellar
Summary
Building a Blockchain Wallet for Fungible and Non-Fungible Assets
Technical requirements
Understanding ERC20 and ERC721 smart contract standards
Writing the smart contract code 
Creating the ERC20 Token contract
Creating the ERC721 Token contract
Migrating the smart contract code using Truffle
Creating the token wallet frontend using ReactJS
Setting up the React app
Adding token interfaces to our app
App components
Container.js
App.js
Running our app
Connecting to the main Ethereum network
Summary
Designing a Payment Gateway for Online Merchants
Technical requirements
Defining our blockchain payment ecosystem
Generating dynamic merchant addresses using HD wallets
Creating an e-commerce website and payment gateway
Shoes.js
Container.js
Writing the App.js file and declaring the methods 
newPayment()
PaymentWait()
MMaskTransfer()
startTimer()
tick()
bCheck() – running a persistent balance check 
Using the componentDidMount() method to map the Shoes array
render()
Running the gateway app
Creating an API for generating dynamic payment addresses
Building the merchant HD wallet 
App.js
Constructor()
componentDidMount()
render()
getAccountTransactions()
Running the payment ecosystem
Summary
Corporate Remittances and Settlement
Technical requirements
Understanding the blockchain corporate remittance application and network layout
Setting up the Hyperledger Fabric Bankchain network
Creating the crypto-config file
Creating the configtx file
Creating the docker-compose files
Launching the network
Creating blockchain identities for the banks
Creating the admin user
Creating a utility to enroll the admin user
Changes for Bank B
Running the utility
Creating the bank users
Creating a utility to register users
Changes for the Bank B utility
Running the utilities
Building the corporate remittance contract
Writing the corporate remittance contract
Deploying the corprem smart contract
Setting up the IPFS network
Downloading the binary and installing IPFS
Initializing the IPFS nodes
Generating a key file for the network
Configuring the nodes
Bootstrapping the nodes
Starting the nodes and testing the network
Setting up the bank databases
Installing postgresql 
Creating the bank databases
Creating the database relations
Inserting test customer data into the customers table
Building the bank backend servers 
Creating the app environment
Writing the backend server code
Creating an endpoint to fetch customer data
Creating an endpoint to post payment requests
Creating a service to get transaction details
Writing a method to publish documents to the IPFS network
Writing a method to submit transactions to the blockchain network
Writing a method to update the customer's balance
Writing a method to add transactions to the database
Changes for backend server for Bank B
Building the transaction listeners for the banks
Creating the app environment
Writing the transaction listener code
Writing the transaction listener method
Writing a method to fetch compliance documents from IPFS
Changes for transaction listener for Bank B
Creating the corporate remittance app frontend in React
Creating the React project environment
Building the container component
Building the AppLogin component
Building the Transfer component
Building the ViewTransactions component
Writing the methods in the App.js file
Writing the constructor 
Writing a method for setting the user account
Writing methods to toggle between app components
Writing methods to handle input fields
Writing a method to submit payment requests
Writing a method to fetch customer transactions
Writing a method to set the current user balance
Running the corporate remittance app
Summary
Enabling Cross-Border Remittances with Real-Time KYC/AML Verification
Technical requirements
Designing a workflow for blockchain cross-border remittance
Understanding how a payment request works
Setting up a test network
Creating user accounts
Writing the createAccount utility
Running the createAccount utility
Creating the USD asset
Creating a new asset object
Extending trustlines to receive accounts
Writing the utility
Running the utility
Funding the user accounts with USD
Writing the utilities
Running the utities
Setting up the bank domains 
Updating the hosts file
Issuing the self-signed certificates for the domains
Setting up the http server and stellar.toml file
Setting up the bank's internal databases
Setting up the federation servers
Setting up the compliance server
Setting up the bridge server
Setting up the callbacks server
Building the bank portal
Building the bank portal backend 
Building the bank portal frontend 
Creating the React project environment
Mapping the USD asset 
Writing the App.js file
Running the remittance platform
Summary 
Section 2: Blockchain Workflows Using Smart Contracts
Building a Letter of Credit Workflow Module Using Smart Contracts
Technical requirements
Understanding smart contracts and blockchain-based workflows
Scope of an LC workflow project
Setting up the LC workflow
Creating a USD token for accounting
Deploying a USD token for accounting
Creating an LC Master smart contract
Writing the contract
Creating an LC smart contract
Deploying the LC Master smart contract
Creating the LC module React app
Creating the React project environment
Setting up the contract interfaces
Building the React components
Creating the BankLogin.js component
Creating the BankTabCreate.js component
Creating the SellerTabSettle.js component
Creating the SellerTabView.js component
Creating the Container.js component
Writing the app methods and creating the App.js file
Writing the constructor() method
Using the componentDidMount method
Building the session setters
Writing the createLC method
Writing the viewLC method
Writing the viewSingleLC method
Writing the settleLC method
Running the LC module
Summary
Section 3: Securing Digital Documents and Files Using Blockchain
Building a Tamper-Proof Document Storage System
Technical requirements
Tamper-proof document storage using blockchain 
Setting up the Hyperledger Fabric network 
Bringing the first network sample online
Creating the admin and user identities
Writing and deploying the DocsApp chaincode 
Writing the DocsApp smart contract 
Deploying the DocsApp smart contract
Building the backend services
Writing the backend server
Building a method for listing files in a directory
Building a method to write a file hash to the blockchain
Building a method to write the MTH and the FTH to the blockchain
Building a method to read MTH and FTH from the blockchain
Building a function to compare the current hash signature of a file with the hash recorded in the blockchain
Writing a backend service for securing a directory by recording hashes in the blockchain
Writing a service to verify the last modified time and the file tree structure
Writing a service to inspect and identify tampered files
Creating a React frontend for the app
Creating the React project environment
Building the container component
Building the PathMapper component
Building the FolderBlock component
Building the FolderBlockChkStatus component
Writing the app methods 
Creating a method to set the timer interval
Creating a method to write the hashes to the blockchain
Creating a method to check for a mismatch between the last modified time and the file tree structure
Writing a method to check whether any files have been added or removed from the directory
Writing a method for identifying tampered files from the list of files
Running the tamper-proof application
Summary
Section 4: Decentralized Trading Exchanges Using Blockchain
Building a Decentralized Trading Exchange
Technical requirements
Decentralized trading exchanges
Basic components of a trading exchange 
Scope of the decentralized exchange project
Issuing the trading assets
Writing the contracts
Compiling the contracts 
Orderbook smart contract
Writing the contract
Migrating all the contracts to the blockchain 
Building the exchange app
Building the app 
Creating the React project environment
Setting up the contract interfaces
Writing the App.js file
Displaying the orderbook
Watching orderbook events
Initiating a buy order 
Initiating a sell order
Setting the user asset balances
Running the exchange app
Summary
Developing a Currency Trading Exchange for Market Making
Technical requirements
Introducing the distributed currency trading exchange
Building the private test Stellar network
Creating the user accounts
Writing the CreateAccount utility
Running the CreateAccount utility
Creating trading currency assets
Creating a new asset object
Extending trustlines to receiving accounts
Writing the utility
Running the utility
Transferring the assets from the issuing account
Writing the utilities
Running the utilities
Building the currency trading exchange
Creating the React project environment
Setting up the asset interfaces
Writing the App.js file
Setting the default user account
Setting the account balance
Displaying the orderbook
Displaying successful trades to the user
Buying and selling assets
Setting the active trading asset pair
Running the currency exchange
Summary
Looking into the Future
Summarizing our journey
Extending concepts to other applications
The road ahead – some additional blockchain concepts
Conclusion
Appendix: Application Checklist
Application checklist 
Design checklist  
Development checklist  
Testing checklist
Deployment checklist
Other Books You May Enjoy
Leave a review - let other readers know what you think
Blockchain technology will play a disruptive role in banking, finance services, and insurance (BFSI) in the coming years. Experts estimate annual savings of up to 20 billion dollars from this technology. This book will help you build fully fledged financial applications using blockchain, enabling you and your enterprise to build transparent and secure business processes.
This book will walk you through reimagining some of the most popular products and services of BFSI. The book starts with common blockchain concepts and the impact of blockchain technology in the BFSI sector. Next, we look at re-designing existing banking processes and building new financial applications using blockchain. This will be accomplished through eight detailed blockchain projects. You'll be guided through the entire process, from environment setup to building the frontend portals/dashboards along with the system integration and testing aspects for the applications. You will gain hands-on experience with Ethereum, Hyperledger Fabric, and Stellar. You will learn how to use ancillary platforms such as IPFS, the Truffle Suite, QpenZeppelin, and MetaMask to build applications as well.
By the end of the book, you will have an in-depth understanding of how to leverage distributed ledgers and smart contracts for financial use cases.
This book is for blockchain/DApp developers and start-ups who are looking for a one-stop guide to building innovative and highly secure solutions in the FinTech domain using real-world use cases. It is also suitable for developers working in financial enterprises and banks and for solution architects looking to build brand-new process flows using blockchain technology. Working experience with Solidity and prior knowledge of finance/trade is required to get the most out of the book.
Chapter 1, Blockchain in Financial Services, introduces you to enterprise blockchain solutions for the BFSI sector. It briefly discusses the opportunities for implementing blockchain in the domain and the challenges that you might face when introducing the concept of blockchain in your organization. There is a discussion of the various most common implementation strategies, including coverage of the architecture models that are relevant for each strategy. Brief walk-throughs are given of Ethereum, Stellar, and Hyperledger Fabric and their relevant use cases for the domain.
Chapter 2, Building a Blockchain Wallet for Fungible and Non-Fungible Assets, looks at the blockchain wallet, which is the most integral part of any enterprise blockchain application. It can take many shapes and forms, such as a payment wallet, a digital identity card, a land title portfolio, or a stock portfolio. This chapter focuses on creating a blockchain wallet suited for multiple enterprise applications. You will learn how to create and deploy a smart contract wallet for fungible (ERC20), and non-fungible assets (ERC721). You will also learn how to implement theWeb3jslibrary as part of your blockchain application. The end goal is to create a fully functional peer-to-peer wallet using HTML, Node.js, and Solidity that is suitable for use cases beyond payment.
Chapter 3, Designing a Payment Gateway for Online Merchants, focuses on creating a merchant solution for online retailers. The solution will enable users to accept payments on a blockchain network akin to the leading fiat payment networks today. Special focus is given to push/pull payments, reconciliation, payment confirmation, and settlement on a blockchain platform. The technologies used are HTML, Node.js, and Solidity.
Chapter 4, Corporate Remittances and Settlement, focuses on the Hyperledger Fabric platform and its application in financial systems. You are given a walk-through on configuring the plug-and-play modules that make up the Hyperledger Fabric ecosystem. You will then be taught how to leverage them to create a permissioned blockchain network that can be used for B2B payments.
Chapter 5, Enabling Cross-Border Remittances with Real-Time KYC/AML Verification, focuses on creating a multi-currency cross-border remittance network using Stellar. Special focus is given to real-time document exchange, KYC/AML verification, Nostro account visibility, and integration with legacy banking systems.
Chapter 6, Building a Letter of Credit Workflow Module Using Smart Contracts, looks at smart contracts, which provide us with a foundation to build faster and efficient enterprise workflows. This is possible through automation and an immutable ledger accessible to all the stakeholders. This chapter looks at using Solidity smart contracts to build a more efficient letter of credit workflow. This knowledge can then be leveraged to design similar financial products, such as bank guarantees and smart contract-based insurance products
Chapter 7, Building a Tamper-Proof Record-Keeping and Document Management System, introduces you to the Hyperledger Fabric framework. You will be deploying your own chaincode and using it to build an immutable record management system. This system employs the power of the SHA256 algorithm and blockchain consensus to ensure that all records are tamperproof and can be reverted to their original state in the case of a cyber attack.
Chapter 8, Building a Decentralized Trading Exchange on Blockchain, explores decentralized exchanges, which aim to bring more transparency to the trading of assets and commodities. They eliminate the middleman and can thus ensure faster settlements. They also help control fraudulent practices such as price manipulation. This project looks at creating a price-time priority matching engine using Solidity smart contracts. This matching engine can then operate on a decentralized orderbook that can accept orders from all the participants on the network.
Chapter 9, Developing a Currency Trading Exchange for Market Making, looks at leveraging the market maker module of the Stellar platform to create a currency swap exchange. This currency swap exchange operates in real time and can be used either as an asset trading platform or to provide liquidity for cross-currency cross-border remittances.
Chapter 10, Looking into the Future, provides a short summary of the skills you will have acquired in your journey through the book. It also talks briefly about how we see blockchain technology evolving and the new concepts on the horizon that you might want to look at.
Chapter 11, Appendix: Application Checklist, This chapter provides step-by-step instructions for setting up an Ethereum, Stellar, and Hyperledger Fabric development and production environment. This is a pre-requisite for the aforementioned projects. This chapter also focuses on enterprise security and scalability essentials for implementing a blockchain application in a live production scenario. A basic checklist is provided with respect to design, development, testing, and deployment.
The following is what you will need to get the most out of this book:
Elementary to moderate knowledge of Ethereum and Solidity
Elementary knowledge of Hyperledger Fabric and Stellar
Moderate knowledge of JavaScript and Node.js
Elementary knowledge of ReactJS
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Blockchain-Development-for-Finance-Projects. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781838829094_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
Blockchain was first used for transferring and establishing the provenance of assets between individuals and organizations without depending on a middleman. This makes payments and remittances the oldest and most mature application of blockchain technology. Today, the technology has evolved to support a number of enterprise use cases revolving around payments and remittances, including retail payments, cross-border remittances, and corporate remittances. Several banks and financial enterprises around the world have recognized the disruptive nature of this technology in payments and are actively experimenting with workflows and applications that will form a core component of their IT infrastructure in the near future.
In the next five chapters, we will look at four such applications. We'll start by introducing blockchain in financial services and will then proceed toward building a wallet for transferring and storing assets. Next, we'll build a blockchain-enabled payment gateway for an e-commerce website. Lastly, we'll look at how we can leverage blockchain to cut out the inefficiencies and delays in corporate remittances and retail cross-border remittances.
This section comprises the following chapters:
Chapter 1
,
Blockchain in Financial Services
Chapter 2
,
Building a Blockchain Wallet for Fungible and
Non-Fungible
Assets
Chapter 3
,
Designing a Payment Gateway for Online Merchants
Chapter 4
,
Corporate Remittances and Settlement
Chapter 5
,
Enabling Cross-Border Remittances with Real-Time KYC/AML Verification
Blockchain technology is expected to revolutionalize how our industries and enterprises operate. Experts estimate that it will business process flows and enable organizations to build products and services that are more secure, transparent, fraud-resistant, and cost-efficient. Banking and financial enterprises and start-ups have been the first to experiment with and adopt this disruptive technology. Reports and surveys suggest that, within the next decade, these organizations will go through rapid stages of innovation to establish blockchain as the Backbone for their day-to-day operations and the services they offer to their customers. In this book, we'll be looking at some prominent applications of this technology for the banking and finance industry through projects. Each project is implemented using a popular distributed ledger platform.
By the end of the book, you will have a better understanding of how to leverage blockchain technology to build applications for financial use cases. You will also have sufficient knowledge of building blockchain solutions using the Ethereum, Hyperledger Fabric, and Stellar distributed ledger platforms.
In this chapter, we'll be looking at the current state of financial systems and how blockchain can make a difference. We'll also try to understand how to approach implementing such a solution and some of the popular blockchain platforms we can consider for developing a financial application. The topics covered are as follows:
Present-day banking and finance systems
Understanding the blockchain technology
Blockchain for financial services
How to approach implementing a blockchain solution
The popular distributed ledger platforms for financial applications
The global banking and financial system plays a huge role in the life of the modern human being. It moves more than a trillion dollars around the world in a day, and more than a billion people are directly or indirectly served by it every day. It is the backbone of global trade finance and it enables enterprises, from start-ups to conglomerates, to run their businesses smoothly in any part of the world. The technology that makes this ecosystem tick has evolved in leaps and bounds in the last two decades, especially with the advent of the internet.
However, owing to compliance restrictions, reliance on legacy systems, and a conservative outlook on technology, most banking IT systems today are yet to adapt to advancements in technology and are unable to keep up with the nefarious means employed by malicious individuals. As a results close to half of banking customers have been expose to frauds and cyber crimes while dealing with payment gateways, stock exchanges, money transfer agencies, and so on.
Add to this the fact that the system has added layer after layer of middlemen and intermediaries owing to the limitations of conventional IT systems. This, in turn, has resulted in high fees and delays for the customers, not to mention a massive amount of paperwork arising from complex workflows. It also exposes the customer to the possibility of financial fraud and corruption. Lastly, the system in many cases is highly exclusive and denies basic access to financial products and services to a number of people around the world.
Generally, bankers have resisted sweeping changes to the current way the underlying technology works as they do not want to upset the apple cart and want to ensure that businesses that rely on them are able to continue working smoothly without any change in their user experience. However, the inefficiencies and faults in the system mean that such changes are the need of the hour. Disruptive innovation that can make the customer's experience even better is required to ensure that the system keeps chugging along and customers are able to operate their businesses without being slowed down or stopped by the technology on which their businesses are built. Enter blockchain.
Blockchain technology has numerous features and advantages that enable us to re think and re-engineer how modern financial services operate and serve the end customer. It enables us to design modern workflows minimizing middlemen, maximizing security, enabling transparency, and promoting high levels of interoperability between different players of the financial ecosystem.
Blockchain technology was invented to be the backbone for Bitcoin, the popular cryptocurrency. It is a distributed ledger spread across a permissioned or permissionless network. The participants of this network are referred to as nodes. Each node contains a copy of the ledger. To update the ledger, the participants in the network will propose a transaction or a set of transactions that should be added next to the ledger. Once the participants in the network come to an agreement on the next set of transactions, they will add the transactions to their local copy of the ledger. This way, the sanctity and uniformity of the ledger across the nodes are maintained.
Data is added in "blocks" of transactions. Each block contains the hash value of the header of the previous block. (A hash function generates a unique output of fixed length for an input data of any length.) This ensures that the sequential order of the blocks is maintained in the ledger. Each block header has a set of parameters, including a Merkle root hash of the transactions in the block. If any transaction data is tampered, it results in the Merkle root of the block being altered. This causes a mismatch in the hash of the header of the block and the hash of the header of the block stored in the following block, effectively 'breaking the chain'. This will result in the local copy of the ledger being broken and the node being thrown out of sync with the other copies of the distributed ledger disabling it from adding any further transactions to the ledger.
Transactions submitted to the network are signed using a private key or a secret key that is held by the network participant and the public key is included in the transaction as part of the transaction. This means that the other participants on the network can validate the identity of the transaction submitter.
The multiple copies of the ledger and the hash-chain ensure that any data written to the ledger is immutable. If there is a mismatch between the local copy of the ledger held by a node and the copy of the ledger held by the other network participants (nodes), the node is disengaged from the network and cannot broadcast new transactions. This ensures that the sanctity of the ledger is maintained. To further maintain the uniformity of the ledger, blockchain allows network participants only to append new data to the ledger and does not allow participants to remove or modify existing data in the ledger. As such, any transaction data written to the blockchain is preserved and cannot be modified.
Since the ledger is universal, there needs to exist a mechanism to ensure that transactions are added in the same order across all copies of the ledger. This is typically achieved through a consensus mechanism. A consensus mechanism is basically a set of steps that ensures that transactions are written in the same order across the nodes. Additionally, it ensures that the transactions in all the copies of the ledger are the same.
Consensus can be achieved through various means. Traditional public permissionless blockchains, such as those running cryptocurrencies such as Bitcoin or Ethereum 1.0, rely on the solving of a cryptographic puzzle to pick the network participant who gets to write the next set of transactions to the ledger. This network participant is called a miner. After successfully solving the cryptographic puzzle, the miner will create a "block" of what they believe the next transactions in the ledger should be. They then add this block with the transactions and their solution to the puzzle to their local copy of the ledger and broadcast this block to all the other nodes in the network. The other nodes will validate the authenticity of this block before updating it to their local ledger. The difficulty of the cryptographic puzzle is set such that only one network participant can solve the puzzle in a fixed window of time. After the puzzle is solved, a new cryptographic puzzle is generated and the next miner needs to solve this puzzle.
Permissioned blockchains follow a slightly different approach. Permissioned blockchains are blockchains where we know all the network participants and the participants cannot connect to the network without prior permission of the participants. Since the identity of all the network participants is known, these blockchains follow a slightly more relaxed approach to consensus. They might use a simple queuing mechanism to order the transactions. Some may also follow a round-robin approach. A round-robin approach is one where each network participant is allowed to submit and write its own block to the ledger. This continues until every participant has had a chance to submit a block, and then the process is repeated.
In recent times, the term Distributed Ledger Technology (DLT) has been interchangeably used with the term blockchain. All Blockchains are DLTs but not all DLTs are Blockchains. In common parlance, the term DLT is generally used to refer to a platform that does not use 'blocks' or 'chains'. Instead they add data in singular transactions. These platforms are being actively used to build financial applications. Most of these platforms use a variation of the Practical Byzantine Fault Tolerance (PBFT) mechanism to achieve a transactional-level consensus between the various copies of the ledger. As they are PBFT-based, several of them suffer from the same limitations as PBFT. They are able to solve this problem using intelligent network design or by making modifications to the traditional PBFT algorithm. A good example is the Stellar platform, which follows the Federated Byzantine Agreement (FBA) consensus model and restricts the Validation Nodes on its public network. DLT platforms are preferred over blockchains in certain use cases because they often permit higher transactions per second. This makes them suitable for payment networks, trading exchanges, and so on.
Lastly, let's look at the concept of smart contracts. Smart contracts are computer protocols that enable the execution of condition-based business flows. The authenticity of conditions and the execution of the terms of the contract can be satisfactorily verified by all the parties who are affected by the execution of the contract without trusting a third party.
This is possible by writing and deploying such business flows to a distributed ledger and by leveraging blockchain technology. Let's say Alice wants to sell a car and Bob wants to buy it. But Alice wants to ensure that Bob gets possession of the car only when she gets paid. In such a case, Alice and Bob can write a smart contract. Bob can transfer the funds he needs to pay Alice to the smart contract's account. Alice can transfer a secret password that will unlock a digital copy of the documents of the car to the smart contract. The smart contract will ensure that Bob gets access to the password and Alice gets her payment without them depending on a third-party middleman. If the deal does not go through, the contract can also return the assets to the original owners.
This is better than traditional means because a human intermediary can be influenced by Alice or Bob. They might also have to pay some fees to the intermediary. Additionally, there might be a delay in executing the deal owing to a backlog of requests or an inefficient intermediator. If the third-party turns out to be fraudulent, they could even run away with the money and possession of the car! Since in a distributed system the smart contract code is deployed on a blockchain network, it cannot be altered by Alice or Bob or a malicious individual due to the immutable nature of the blockchain. This ensures that the deal will always go through with a limited risk of fraud.
There are many advantages offered by blockchain technology that make it suitable for application in financial services. The technology can help us overcome numerous shortcomings and inefficiencies of present day Banking and Financial systems. The following are some of these areas:
Reconciliation
: Reconciliation is an expensive and time-consuming affair across almost all financial products and services. The d
elayed visibility of transactions or information across organizations leads to delayed settlement for the end customer. Cross-border and domestic
payments, trade settlement, trade finance, and letter-of-credit settlement are examples of some workflows that are more time-consuming and expensive due to the effort spent on reconciling data between organizations.
Blockchains can help eliminate or reduce reconciliation costs and time. Transactions and information can be posted to a shared ledger. All parties that are participants of the shared ledger get instant visibility of the transaction or information. Since the ledger is immutable, data once added cannot be removed. Additionally, the immutability of the ledger also provides us with an audit trail for all asset transfers and transactions that have been successfully executed.
Information sharing
: Currently, banks carry out the KYC(Know Your Customer) process for all new customers. This is a laborious and time-consuming affair for the customer. Additionally, if the customer has accounts across different banks, their KYC information could be different at each bank. Add to this the fact that many banks and financial institutions today use extremely inefficient and insecure workflows for sharing KYC and AML(Anti-Money Laundering) data between them. Given this, it becomes imperative to design a system that can securely share customer KYC and AML data between transacting parties. This concept can be extended to sharing other confidential information as well. It can also enable us to create a unique KYC identity for the customer that can be updated annually or quarterly.
Automated workflows
:
Owing to the distributed nature of blockchain networks, it is easier to script workflows that span organizations. Traditionally, such workflows would involve human operators at each organization analyzing and validating data and information before initiating the next steps.
Smart contracts can allow us to automate or semi-automate such workflows. This reduces dependency on manual intervention. Additionally, we could use an "oracle" for off-chain information or inputs required to automate a blockchain workflow. An oracle is a
third-party service that provides external data/off-chain data to the blockchain
.
Secure document sharing
: Blockchain can enable secure document sharing between organizations. A hash signature of the document can be stored on the shared ledger. This signature will allow us to verify the integrity of the document after successfully receiving the document and in the future. Additionally, we can tag these hash signatures to transactions so they can be referred for audit purposes in the future. A good application of this concept could be storing hash signatures of the Purchase Order and Invoice for Corporate Remittances and tagging them to the settlement transaction.
Decentralized systems
: Blockchains can be used to build decentralized trading exchanges or marketplaces. This can help bring down the intermediary cost, bring in more transparent workflows, and reduce reliance on a central authority. It also reduces the settlement time for the end customers.
Inclusive finance
: Owing to public-private key encryption and a distributed ledger at its heart, it is extremely easy, cost-efficient, and secure to maintain customer accounts and transactions using blockchains. This can help us to design, build, and extend cost-effective financial services to the unbanked, refugees, and the less privileged at a fraction of the expense.
The following is a list of potential banking and finance use cases where blockchain can have a sizeable impact:
Cross-border remittance
Domestic payments
Back office reconciliation
Inter- and intra-organizational information sharing
Trade finance
KYC/AML
Secure IPOs(Initial Public Offer)
Asset tracking
The following is a list of discussion points and activities that IT practitioners should consider and carry out before implementing blockchain technology within their organization:
Identify business requirements that require provenance, audit ability, or distributed workflows.
Recognize whether potential use cases can be executed with centralized databases or digital signatures without relying on a blockchain. (One example of a use case that requires blockchain could be an inter-organizational use case where no central organization or regulator exists to take ownership of the database.)
Envisage the end benefits of implementing blockchain technology.
Identify legacy workflows and modules that will need to be replaced or augmented.
Analyze whether the end benefits from replacing the legacy workflow outweigh the costs.
Identify new workflows and modules that will need to be built for use cases.
Analyze whether the end benefits from implementing the solution outweigh the total cost of executing and implementing the project.
Identify stakeholders and participants of the blockchain system.
Agree on a governance framework for operating the network and build in accountability from the participants.
Agree on an implementation strategy and identify integration with legacy systems, if any.
Choose a blockchain platform based on your requirements.
Identify essential enterprise tools that need to be built to successfully operate the blockchain solution. These include modules such as an identity service, security and access control policies, network directory, and so on.
Organizations should only proceed once they have successfully considered all the preceding points and have the answers to all of them.
There are different implementation strategies that organizations can look at to implement a blockchain network. These are as follows:
All stakeholders own and maintain a node on the blockchain network. This node can be on-premises or on a cloud platform.
A cloud-hosted blockchain network is operated by a trusted service provider. Organizations can view data and information and submit transactions based on access control. This is known as
Blockchain as a Service
(
BaaS
).
Accessing a public permissionless blockchain to record data so that it cannot be tampered with. A good example is storing the hash signature of a document to the public Bitcoin or Ethereum network. The transaction ID and the document is then shared with other stakeholders who need to validate the authenticity of the document in the future.
Organizations can choose to put either complete data and information on the blockchain or can just the hash of the data, document, or information on the blockchain.
The first case is applicable when the stakeholders need to share data in real-time between different stakeholders and ensure that the information shared is immutable and cannot be modified once it has been published to the shared ledger.
The second case is applicable when the stakeholders only need a blockchain to establish the provenance of documents, data, files, or any other assets. The actual data or asset is not shared through a blockchain. In such a case, we only publish a unique attribute of the asset to the blockchain. For documents, files, and information, this can be a hash of the file or document content. For assets such as gold, it could be the carat value.
The blockchain industry today is inundated with distributed ledger frameworks and platforms that can be used to implement solutions. For this book, I've selected three popular platforms that are being used by developers and architects to implement financial solutions. These platforms are as follows:
Ethereum
Hyperledger Fabric
Stellar
These platforms have been used extensively for implementing blockchain projects globally. As with any framework, there are trade-offs when you settle on one for designing your solution. Let's look at these platforms.
Ethereum is probably the second most popular blockchain platform in the world. It was conceptualized by Vitalik Buterin. The technology stack is open source and is maintained by the Ethereum Foundation. Its native asset is ether. Users can also issue their own assets on the network. These assets are popularly known as tokens.
Ethereum was the first blockchain platform to implement smart contracts. Smart contracts are written using the Solidity language. Contracts are compiled and deployed to the blockchain in bytecode format. This bytecode is then broadcast to all the nodes in the network. Each node implements the Ethereum Virtual Machine (EVM), which is a runtime environment for Ethereum smart contracts. The popularity of Solidity has led other blockchain platforms to include it as an optional framework for writing and deploying smart contracts.
Ethereum implements a world state that keeps track of all user accounts and smart contract accounts. It uses the EthHash Proof-of-Work consensus mechanism to maintain ledger integrity. Owing to its popularity, its open source nature, the flexibility of the Solidity language, and how old the platform is, Ethereum has developed a huge online community that constantly contributes to the project and the ecosystem. This has helped the platform mature and add new features over time. One of the best examples is probably the Ethereum Request for Comment (ERC) initiative, which proposes standards for contract development. Two of the most popular ERC standards are ERC20 and ERC721, which propose standards for creating fungible and non-fungible tokens respectively.
There is also an entire ecosystem of applications, tools, and utilities that can be used with the Ethereum platform. These are called DApps, short for Distributed Apps. One of the most popular DApps is Metamask. Metamask is an Ethereum wallet that can be used to submit and receive transactions to and from an Ethereum blockchain network. We'll be using it extensively in our projects.
Hyperledger Fabric is a project incubated by the Linux Foundation under the Hyperledger umbrella of projects. Hyperledger is used to refer to a collection of open source enterprise blockchain projects, tools, and utilities. The Hyperledger initiative's main purpose is to enable the collaborative development of enterprise blockchain. It has seen major contributions from IBM, Intel, SAP Ariba, and other global enterprises.
Fabric is one of the oldest and most mature projects under Hyperledger. It is intended to be a platform for developing blockchain solutions with a modular architecture. It allows different platform features such as consensus mechanisms, certificate authorities, and identity services to be available as plug-and-play features. To achieve this, it implements containerization, making it suitable for modern enterprise IT systems. Unlike other blockchain platforms, it does not implement native assets, accounts, or an unspent transaction model, making it suitable for a plethora of applications.
Hyperledger Fabric implements chaincodes, which are similar to smart contracts. One of the most important features it implements is a concept called channels, which are essentially private ledgers with a fixed number of participant nodes. Only authorized nodes and organizations can access a channel. Nodes can be members of multiple channels, and chaincodes, policies, and certificate authorities can be used across multiple channels.
Hyperledger Fabric takes a unique approach to consensus. It runs a stand-alone orderer peer. The orderer peer gathers transactions and transmits new blocks of transactions to the network peers. The orderer leverages an ordering mechanism based on Kafka or Raft to order transactions and create blocks.
To submit transactions, peers first send a proposed transaction to a select few peers in the network, known as endorsement peers. These peers are determined during channel creation. If the transaction does not violate the endorsement peer's internal state, it "endorses" the transaction and sends it back to the node that sent the proposal. The initiating node then gathers these responses and broadcasts these with the endorsements to the orderer. It also sends a read and write set that has the initial and final values of the state after the transaction has been executed.
The orderer will collect these transactions and generate a new block. Fabric allows users to modify block size and block generation time. The newly created blocks are then sent back to the peer nodes by the orderer. The peer nodes will first add the block to their private copy of the ledger. Next, they will check the transactions inside the block to ensure that the read and write set is in line with the value in their local state database. After this check, they will update their local state database with the new values resulting from the transaction.
The Stellar platform is a decentralized protocol that was primarily designed for enabling fast, low-cost, cross-border payments. It is an open source project developed and maintained by the Stellar Foundation. The platform was conceived by Jed McCaleb, who is also the co-founder of Ripple.
Stellar implements transaction-level consensus using FBA, the modified version of PBFT, mentioned earlier. Its native asset is called the lumen (XLM). Owing to its focus on payments, the Stellar platform provides additional modules that work in conjunction with the core software to enable users to build customer-friendly apps that meet compliance and regulatory norms for payments.
Stellar's most interesting feature is probably that it implements a decentralized orderbook as part of its core technology stack. This feature allows you to carry out cross-asset transactions. This way, a customer can initiate a transaction in USD and terminate it in GBP. Since Stellar allows you to issue your own assets, the possible use cases where this feature can be used are endless. You can also use the orderbook to build a trading exchange by submitting buy and sell offers using the Stellar SDK. You can virtually build an entire application around this feature. Many decentralized exchanges have actually done this.
Globally, Stellar has been used by IBM to build the World Wire network to enable cross-border payments. It has also been used by a number of remittance providers across the world who have found the technology stack suitable for building payment applications.
I hope this chapter gave you insight into how blockchains will impact the financial services sector, how enterprises are adopting this technology, and what to consider when trying to implement a blockchain solution. It should also have helped you understand how to implement blockchain projects within an enterprise.
We started the chapter by looking at the present-day banking and finance industry and by understanding blockchain technology. Next, we went through the areas where we believe blockchain can make a difference in this industry. We also looked at how organizations need to approach implementing blockchain technology and what the different implementation models they can consider are. Lastly, we looked at some of the popular blockchain platforms of the day. We'll be using these to implement the projects that will follow in the coming chapters.
In the following chapters, we'll be developing blockchain projects suited for various financial applications. Each of these projects looks at leveraging blockchain technology to deliver a financial solution that is more secure, efficient, and transparent than the traditional alternative. In the next chapter, we'll be looking at leveraging a blockchain platform to design a wallet that can store fungible as well as non-fungible tokens.
The blockchain wallet forms the most integral part of any enterprise blockchain application. It is the customer interface of the blockchain application. It can take many shapes and forms, depending on the use case being implemented. It could be a payment wallet, a digital identity card, a land title portfolio, or an assets portfolio.
This chapter focuses on creating blockchain wallets suited for financial applications. Our wallet will be managing assets that are issued on the blockchain. These assets will be issued using pre-defined smart contract standards. For this, we will look at the ERC20 and ERC721 smart contract standards. We will learn to write, migrate, and deploy our own smart contract codes using Truffle. We will also learn to create a token wallet frontend using ReactJS, and finally, we will run the app. We will also look at how to connect the wallet to the main Ethereum network.
The following topics will be covered in this chapter:
Technical requirements
Understanding ERC20 and ERC721 smart contract standards
Writing the smart contract code
Migrating the smart contract code using Truffle
Creating the token wallet frontend using ReactJS
Running our app
Connecting to the main Ethereum network
The code files of this chapter are available at the following link:
https://github.com/PacktPublishing/Blockchain-Development-for-Finance-Projects/tree/master/Chapter%202/Chapter%202
We'll be using the following to develop our project:
Ganache Private Blockchain Server—
https://trufflesuite.com/ganache/
Trufflesuite—
https://github.com/trufflesuite/truffle
MetaMask plugin for Chrome/Firefox/Safari—
https://metamask.io/
I'm using Ubuntu 18.04.2 LTS for running the preceding applications and deploying my blockchain. This project assumes that you are working on a Unix operating system. Additionally, this project assumes you have Node.js and npm installed. I'm using Node version 13.0.1 and npm version 6.12.0.
Lastly, we'll be using the OpenZeppelin library of smart contracts to write our contracts. To use this library, create a project folder in your Truffle workspace. Let's call it tokenwallet. Create a package.json file in the project folder and update it with the following values:
{
"dependencies": { "babel-register": "^6.23.0", "babel-polyfill": "^6.26.0", "babel-preset-es2015": "^6.18.0" }, "devDependencies": {
"openzeppelin-solidity": "^2.2.0"
}
}
Run npm install to install the OpenZeppelin library and Babel for your Truffle workspace.
To understand ERC20 and ERC721 contract standards, first, let's look at the concept of fungibility. Fungibility is used to describe the property of an asset where individual units do not hold a special value and can be replaced with another unit of the asset. A good example of this a 10 dollar bill. If you have a 10 dollar bill and I have a 10 dollar bill, they both hold the same value, which is 10 dollars. The bill would not have a higher or lower value depending on who is the owner of the bill. The bills can replace each other very easily. Hence, a 10 dollar bill is a fungible asset. All currency is essentially fungible in nature.
Now, take the case of a different kind of asset. If both of us owned a 400-square foot apartment and yours was in New York City and mine in New Delhi, the monetary value of both the apartments would be different because of the average price of a property per square foot being much higher in New York. In this case, the apartment is an example of a non-fungible asset—essentially, an asset that cannot be replaced by a random asset from the same group. The asset has some additional properties attached to it that make it "special."
In the world of finance, we use both fungible and non-fungible assets and goods extensively. Currency, loyalty tokens, food coupons, gift cards, commodities, and so on are fungible in nature, wherein one can replace the other. Real estate, people, pre-owned automobiles, artworks, and so on are non-fungible in nature, where each unit has some distinguishing features that make it irreplaceable.
The Ethereum community has devised numerous smart contract standards suited for different use cases. These are meant to be starting points for developers and introduce uniformity among developers coding for the public Ethereum blockchain. For fungible tokens, the most popular contract standard is ERC20. ERC20 tokens have been implemented in multiple use cases such as payment tokens, loyalty coins, gift cards, and so on but their most popular implementation by far is as Initial Crypto Offering (ICO) tokens. ERC20 contracts are easy to understand, build, and deploy and, owing to this, it is often this first contract standard that developers work with.
ERC 721 is the token standard used to build smart contracts that issue Non-Fungible Tokens (NFTs
