DebajaniMohanty
R3CordaforArchitectsandDevelopers
WithCaseStudiesinFinance,Insurance,Healthcare,Travel,
Telecom,andAgriculture
DebajaniMohanty
Noida,UttarPradesh,India
Anysourcecodeorothersupplementarymaterialreferencedbytheauthorinthisbookis
availabletoreadersonGitHubviathebook’sproductpage,locatedatwww.apress.com/9781-4842-4531-6.Formoredetailedinformation,pleasevisithttp://www.apress.com/sourcecode.
ISBN978-1-4842-4531-6
e-ISBN978-1-4842-4529-3
/>©DebajaniMohanty2019
ApressStandard
Trademarkednames,logos,andimagesmayappearinthisbook.Ratherthanuseatrademark
symbolwitheveryoccurrenceofatrademarkedname,logo,orimageweusethenames,
logos,andimagesonlyinaneditorialfashionandtothebenefitofthetrademarkowner,with
nointentionofinfringementofthetrademark.Theuseinthispublicationoftradenames,
trademarks,servicemarks,andsimilarterms,eveniftheyarenotidentifiedassuch,isnotto
betakenasanexpressionofopinionastowhetherornottheyaresubjecttoproprietary
rights.
Whiletheadviceandinformationinthisbookarebelievedtobetrueandaccurateatthedate
ofpublication,neithertheauthorsnortheeditorsnorthepublishercanacceptanylegal
responsibilityforanyerrorsoromissionsthatmaybemade.Thepublishermakesno
warranty,expressorimplied,withrespecttothematerialcontainedherein.
DistributedtothebooktradeworldwidebySpringerScience+BusinessMediaNewYork,233
SpringStreet,6thFloor,NewYork,NY10013.Phone1-800-SPRINGER,fax(201)348-4505,email,orvisitwww.springeronline.com.ApressMedia,LLCisa
CaliforniaLLCandthesolemember(owner)isSpringerScience+BusinessMediaFinanceInc
(SSBMFinanceInc).SSBMFinanceIncisaDelawarecorporation.
Introduction
R3CordaforArchitectsandDevelopersisintendedtobethestandardbookonR3Corda,the
industry-leadingdistributedledgertechnology(DLT).ThebookexplorestheentireCorda
ecosystemstepbystepwithadequatetheory,labs,andliveusecases.
Today,R3CordahasemergedastheDLTplatformofchoicefortheinsurancedomainas
wellasmanybanksandregtechorganizations.ThemainissuelearningR3Cordaisthelackof
trainersandthescarcityofsamplecodesinawell-acceptedlanguagesuchasJava,sincemost
ofitsexistingexamplesarewritteninKotlin.R3CordaforArchitectsandDeveloperswillfill
thatvacuumbyprovidingcontentssuitabletoallstakeholdersconsolidatedinoneplace.In
thisreadingjourney,thereaderwillbeintroducedchapterbychaptertoBlockchainconcepts,
DLT,R3Cordaarchitecture,andsmartcontractprogramminginJavawithampleexamples,
guidingthereaderthroughtestinganddeploymentoftheentireecosystem.Inlaterchapters,
readerswillbeintroducedtovariousbusinessproblemsinhealthcare,agriculture,andafew
otherdomainsandhowCordacansolvetheseissuesthroughitsuniqueandefficientDLT
offering.ThebookalsoprovidessamplecodesofsomeusefulProofofConcepts(PoCs)that
willbemostbeneficialtobusinessleadersandarchitectsintheirCordajourneyfromconcept
toexecution.Thebusinessscenariosandsolutionsareprovidedwithflowcharts,diagrams,
andsamplecodesthatstakeholderscanreferto,furtherenhanceaspertheirrespective
businessneeds,anddeployinliveprojects.
Thebookwillbeveryusefulforreadersofeverybackground,whethertheyareeagerto
developdecentralizedapplicationsinR3Corda,orwishtolearnitsarchitecture,orevenare
interestedinexploringdifferentusecasesthatcanbeimplementedusingthistechnology
acrossbusinessverticals.Bytheendofthebook,readerswillhaveenoughinformationabout
howthecorrectusageofR3Cordacancreatevaluefortheirbusinessprocessesby
eliminatingmiddlemancostsandbringingintransparencyforcreationofdeduplicated,
fraud-proofdatastorageforsmootherexecutionofbusiness.Thebestandmostuniquepart
ofthebookisthatalltheexamplesarewritteninJava.
Readership(who’sthetargetaudience?):
ThebookwillappealtothenovicewhowishestolearnR3Cordafromscratchand
continuethejourneyuntilheorsheknowsthewholeecosystemandisabletodeploycodein
production.Atthesametime,itwillbeofinteresttoanexistingBlockchaindeveloperor
architect,toknowtheR3CordabestpracticesandliveusecaseswhereR3Cordacandoits
wondersbybringingtransparencytoprocesses,cuttingmiddlemancosts,reducingtimeof
operation,andfinallyeliminatingfraudandduplicationofdata.
Acknowledgments
Thisbookispossiblebecauseofthecombinedeffortofmany;myworkissosmallitcauses
onlyripplesinamassiveocean.Itakethisopportunitytooffermygratitudetothefollowing
peopleforalwaysbeingtherewithmewhenIwasinneed:mygrandmotherMrs.RenukaDas,
motherMrs.NirupamaMohanty,fatherDr.N.K.Mohanty,husbandDr.RajulRastogi,and
uncleDr.N.R.Das.IamalsogratefultoPremNaraindas,DXCTechnologyfortakinghis
valuabletimetoreviewthisbookontime.
Lastbutnotleast,thankstoCoordinatingEditorAditeeMirashi,AcquisitionsEditor
CelestinSureshJohnatApress;forallthehelpwhileworkingonthebook.
TableofContents
Chapter1:BartertoBlockchain
HistoryofMoney
BarterSystem
MetalCurrency
PaperMoney
Banks
IssuewithCentralizedAuthorityinBanking
2008FinancialCrisis:APathbreaker
BitcoinWasBorn
BitcoinWhitePaper
WhyBitcoinTooktheMarketbyStorm
IntroductiontoBlockchain
BusinessProblem
FullyDistributedModel
FullyCentralizedModel
DLT,theDecentralizedPeer-to-PeerModel
BenefitsofBlockchain
DLTvs.Blockchain
Similarities
Differences
BlockchainBusinessValue
BlockchainInternals
DifferentTypesofBlocks
BlockHeader
MerkleTree
DealingwithDoubleSpending
BlockchainHashing
PublicandPrivateKeys
HowBitcoinWorks
Transactions
PossibleAttacksonBitcoinNetwork
DoubleSpending
DDoSAttack
Sybilor51%Attack
EclipseAttack
MitMAttack
Consensus
ForkinBlockchain
SoftFork
HardFork
TypesofVisibilitiesinBlockchainNetworks
PublicBlockchain
PrivateBlockchain
ConsortiumorFederatedBlockchain
HybridBlockchain
Ethereum,theFirstPlayer
LimitationsofEthereum
LeadingBlockchainandDLTProtocols
Quorum
Ripple
HyperledgerFabric
R3Corda
MultiChain
Symbiont
OpenChain
Cardano
IOTA
EOS
HashGraph
Quiz
Answers
Reference
Chapter2:CordaArchitecture
TheDoorman,NetworkService
TheCordaLedger
Identity
State
Contracts
RicardianContract
Transaction
Flow
Consensus
Notary
TimeWindow
Oracles
GDPR,theBlockchainKiller!
Corda’sCompliancewithGDPR
Corda’sDifferentiators,aRecap
NoGlobalSharingandNoCentralDatabase
NoGlobalBroadcast
BlockchainFeaturesandYetNoBlockchain
Real-TimeSynchronousTransactions
GDPRComplaint
Quiz
Answers
References
Chapter3:Installation,Development,Deployment,Unit,andFunctionalTesting
States
LinearState
OwnableState
QueryableState
SchedulableState
Contract
RicardianContract
requireThat
Commands
TimeWindows
Attachment
LedgerTransaction
Flow
FlowLogic
InitiatingFlow
InitiatedBy
StartableByRPC
FinalityFlow
TransactionBuilder
ProgressTracker
Vault
Oracles
ProjectSetup
TDDinCorda:UnitTestingandMore
CordaAPIforUnitTesting
ProjectImportTest
UnitTestingofState
UnitTestingofContract
UnitTestingofFlow
DeployandRun
VaultQuery
ExposingRESTEndpointsforIntegrationwithUI
FunctionalTesting
Troubleshooting
UseCases
Quiz
Answers
Reference
Chapter4:GovernmentandRealEstate
Solution
R3CordaAdvantages
LiveImplementation
References
Chapter5:FinanceDomain—Real-Timee-Auction;TradeFinanceandLetterofCredit
Real-Timee-Auction
Solution
Advantages
LiveUseCases
TradeFinanceandLetterofCredit
Solution
Advantages
LiveImplementations
References
Chapter6:InsuranceDomain—CarInsurance
Solution
Advantages
LiveImplementations
References
Chapter7:Healthcare—CordaandEthereumHybridUseCase
Solution
Attachment
Advantages
LiveImplementations
References
Chapter8:TravelDomain:ReplacingGDSwithNext-GenerationTravelPlatform
Solution
Advantages
LiveImplementations
Reference
Chapter9:TelecomDomain:FraudManagement
Solution
Advantages
LiveImplementations
References
Chapter10:SupplyChaininAgriculture
Solution
Advantages
LiveImplementations
References
Chapter11:SupplyChain—GoldTokenization
Solution
Advantages
LiveImplementations
References
Chapter12:TheLatestfromCorda:Cordite,CordaEnterprise,andSettler
CordaEnterpriseCryptoToken—Cordite
CordaEnterprise
GlobalPaymentsonCordawithSettler
LiveImplementationsofRemittance
Conclusion
References
Index
AbouttheAuthorandAbouttheTechnicalReviewer
AbouttheAuthor
DebajaniMohanty
,authoroftheAmazonbestsellersBlockChain:FromConceptto
Execution(BPBPublications,2018),EthereumforArchitectsand
Developers(Apress,2019),andnowR3CordaforArchitectsand
Developers,isaSolutionArchitectwithcloseto18yearsof
experienceintheindustry.Herbookshavebeentranslatedinto
GermanandChinese.Debajaniisakeynotespeakerat
PhiladelphiaPACT,NASSCOM,IIM,WomenWhoCode,Unicom,
Amity,IndiaInternationalCentre,andmanysimilarnational
andinternationaltechevents.SheisHonoraryFacultywith
AmityUniversity,consultant,andanadvisorandmentorto
numerousreputedorganizationsinIndiaandabroad.Debajani
isalsoawomanactivistandwriterfelicitatedbyNobel
laureateKailashSatyarthiforheroutstandingcontributionsto
womanempowermentinIndia.
FollowheronTwitter: />FollowheronLinkedIn: />
AbouttheTechnicalReviewer
PremNaraindas
isahands-onandhighlyexperiencedtechnologyexecutive
withover17yearsofsuccessful,enterprise-level
accomplishmentswithapassiontodrivecustomer
engagementstosuccessfuloutcomesfromstarttofinish.
Throughthecourseofhiscareer,Premhasled
transformationalinitiativesforclientsinareassuchas
applicationdevelopmentandmaintenance,businessprocess
outsourcing,engineeringservices,R&D,innovation,and
infrastructure.Premhasoverthreeyearsofexperiencewith
EnterpriseBlockchain,hasbeenresponsiblefordeliveringover
20ProofsofConcept,andhassuccessfullyenvisagedandled
productionimplementationofoneoftheworld’sfirstEnterpriseBlockchainapplications.In
hiscurrentrole,PremisGlobalBlockchainOfferingDirectoratDXCtechnology.Thisroleis
partoftheDXCGlobalBlockchainPractice,inwhichPremisresponsibleforunderstanding
theEnterpriseBlockchainmarketdemandsandtrendsandforworkingwithclients,sales
teams,delivery,andconsultantstomakethestrategyrelevanttoDXC’sclientbaseandto
createBlockchainofferingsandsolutionswithvaluesuperiortothatofferedbythe
competition.HeisalsoresponsibleforunderstatingthemarketdynamicstodriveDXC’s
Blockchainproduct,platformdevelopment,andgo-to-marketstrategies.
©DebajaniMohanty2019
DebajaniMohanty,R3CordaforArchitectsandDevelopers
/>
1.BartertoBlockchain
DebajaniMohanty1
(1) Noida,UttarPradesh,India
Inchildhood,Iheardmanystoriesfrommylegendarygrandfatherabouthowcertainpeople
createdimmenseamountofwealthinashorttime,ofcourseinanhonestway,andthenmore
importantlyhowtheykeptitallsafe.Whilemostlittlegirlsofmyagewerefascinatedby
fairytalestories,Ifoundwealthcreationideasmuchmorealluringandameanstobea
powerfulsomeonesomedaylaterinlife.WithtimeIcametoknowIwasnottheonlyonein
thisgame.Peopleinallagesandalltimeshaveceaselesslythoughtoverthispuzzleof
“creatingwealth,”“securingit,”and“tradingorinvestingforlargerreturns.”Beitgold,spices,
cattle,slaves,land,oroil,wealthhasmanydifferentformsandthereareinherentflawswhen
itcomestotradinginwealth.Inthischapter,let’sdiscusssomeofthedifferentformsof
moneyandfigureouthowthisjourneyfinallyculminatedinBitcoinandBlockchain,oneofthe
biggesttechnicalinventionsofthe21stcentury.
HistoryofMoney
Haveyoueverwonderedwhyweneedtosecureourvaluables,andifsowastherealwaysa
needtodoso?Well,perhapsnot.Morethantenthousandyearsback,humanbeingslivedin
caves.Theywerehunterswholivedontheirdailyearnings,whetheranimalorfruitor
equivalent,andtherewasnoneedtostoreorkeepsuchperishableitemssafeforalongtime.
Thatwasthetimewhentheystartedlivingingroupsincavestostayprotectedfromanimal
attacksandothernaturalcalamities.Slowly,theygaineddifferentskillssuchascooking,
makingweapons,andsewingclothes.Graduallytheylearnedcultivationanddomesticationof
certainanimals.Soonpeoplestartedaclassificationanddivisionoflaboronthebasisof
specializationofskills,sothataparticulargroupofpeoplegoodatacertainskillwouldwork
inthatparticularskillareaonly.However,thatledtoaproblem:forexamplelet’ssayafarmer
whocultivatedriceproducedmorericethanhisfamilycouldconsumeandatthesametime
neededmilkforhisfamily.Wherewouldthisfarmerbeabletogetit?Sotheneedtotrade
tookaconcreteshape.Some9,000to10,000yearsback,peoplestartedtrading,andthe
mechanismiscalled“thebartersystem.”Thisisaverypopularmechanismtoexchange
productsandservicesandpeopleeventodaydoitineverycountryintheworld.
BarterSystem
Thebartersystem,themostprimevalformoftrading,waseasyandsimple.Peopleusedto
gatheringroupsonaparticulardayandexchangeitemsforsomethingelsethatwouldbe
usefulforthem.Mostlyitwasanexchangeofproductsandservices,whichhappenseven
todayinmanycommunitiesandcountriesacrosstheworld.Thebartersystemgainedwide
popularitybecauseofitssimplewayofexchangingproductsandservices.However,the
doublecoincidenceofwantswasalwaysaproblem.Forexample,theremightnotbeanexact
requirementmatchofcommoditiesbetweenparties.Divisibilitytoowasanotherconcern.
Let’sconsideranexample;onecowissellingfortenchickens.However,whatifsomeone
wantstopurchaseonlyonechicken.Alsocommoditiesweremostlyperishableitemsand
couldnotbestoredaspermanentwealth.Sotherewasaneedforauniversallyapproved
tokenthatcouldbeusedasanexchangeitemforpaymentandwouldaddresstheoriginal
issuesinherentinthe“bartersystem”ofthattime:divisibility,perishability,exchangeability,
storage,andsoon.
MetalCurrency
Sosomepeoplewhohadunderstoodthelimitationsofthebartersystemstartedthinkingof
analternatepaymentmediumandthatisthetimewhenmetalcurrencywasintroduced.At
differenttimeperiods,differenttypesofcurrencieswereinexecution:forexample,grains,
seashells,leathermoney,andsoon.Finallymetalcurrencieswereintroducedbetween700BC
and600BC.Inordertomakethecurrencyuniversal,thesemetalcurrenciesneededapproval
orstampbykingsandrulers.Initially,onlythosemetalsthatweredurable,divisible,portable,
limitedinsupply,andnonperishablewereselected.Also,it’sveryimportantthatintermsof
weightandvalue,thepriceofmetalwasthepriceofmoneysothatevenifsomeoneused
regularsilverorgoldtocreatefakecurrenciesitwouldnotaffectthemonetaryvaluation
system.Theissuewithmetalcurrencieswasthattheywereheavyanddifficulttotransportin
largerquantities.Also,theutilityofmetalswaswastedbyconvertingthemtocurrency.
PaperMoney
Timeandneedagainpromptedcertainsmartpeopletocraftanothercurrencywhichwould
belighterandeasierforstorageandwouldhavenointrinsicvaluesothatmetalsandusable
itemscanbesavedforutility.Hencepapermoneywasintroducedsomewherearound800–
900AD.However,theissuewithpapermoneywasthatitcouldbequicklyreproducedinan
illegalway,andalsothatitcouldbemisusedbyblack-marketersandmoney-hoarders.The
mostdangerouspart,however,wasthatitcarriednoinherentvalue.
Banks
Overthelastfewthousandyears,bankshaveevolvedtoagreatextent;howevermodern
banksmostlyhavethesameoperationsascenturiesback:creditanddebit.Bankswilltake
themoneythatusersdeposit,investitelsewhere,getsomeprofits,andreturnbackthe
principalwithinteresttotheusers.Also,afterpapermoneywasintroduced,banksplayeda
centralroleinguaranteeingthevalueofmoney.Theemblemthatkingsandrulersonce
enforcedtoconvertametaltoacurrencynowadaysisdonebythebanks.
Withtime,banksmushroomedeverywhere,andgraduallyeverycountryappointeda
centralbanktoregulatefunctionsofbanksandactasthecentralizedauthoritytocarryout
monetarypolicy,taxation,andeconomicdevelopmentofthecountry.Thefollowingaresome
examplesofcentralbanks:
ReserveBankofIndia,India
FederalReserveSystem,USA
BankofEngland,UK
IssuewithCentralizedAuthorityinBanking
Sinceourschooldays,ourtextbookshavetaughtusaboutmonetarypoliciesandclaimedthat
banksarethesafestplacetosaveourhard-earnedmoney.Let’sfindouttheextenttowhich
that’strue.Ifyouperusethehistoryofbanking,youcanfindaplethoraoffinancialcrises:
creditcrisisin1772,theGreatDepressionbeginningin1929,andthebankingcrisisin2008,
amongothers.Duringsuchacrisis,thereisasuddenpanicinthemarketfollowedbyalong
listofinvestorswhowishtowithdrawtheirinvestmentsfrombanksalmostimmediately.But
banksmightnotalwayshaveareserveofcashastheyhaveinvesteditelsewhere;hencethey
arenotinapositiontohandlepayingbackalldepositsquicklyifthereisasuddenhikein
demand.Undersuchinstances,theydeclarebankruptcy.
Itisinterestingtonotethatsuchfinancialcrisesaremostlyhumancreatedandmightnot
havemuchtodowiththeinherentpriceofcommodities.Forexample,ifasellerwishestosell
apropertyinthemarket,thenthecashamountthattheywouldgetwouldbedifferentat
differentpointsoftimedependinguponthemarketconditions.However,iftheywantto
exchangeitwithanycommodity,forexampleapropertyownerinSanFranciscowishesto
exchangetheirhousewithanotheroneinNewYork,theexchangeratemightnotvaryunless
thereisagainamismatchbetweendemandandsupply.Hence,duringmanyfinancialcrisesin
history,it’sobservedthattheage-oldbartersystemhascomebackintothemainstream.
2008FinancialCrisis:APathbreaker
Amongallthesehistoricalfinancialcrises,themostrecentone,whichmostofushave
observedinourlifetimes,wasintheyear2008.Whocanforgetitsimpact:somuch
unemployment,propertymeltdownandillhealth?Ifonetracesdownwhatwentwrong,it’s
prettysimpleanditcouldhavebeencompletelyavoided.
Inthe2007–2008timeperiod,bankshadstartedtogiveoutriskyloanstopeopleeven
withbadcredithistorytoattractnewcustomersmostlyoutofgreedforapossiblehigher
interestrate.Ultimately,thatmoneycouldnotbepaidbackforobviousreasons.Manybanks
collapsedandfiledforbankruptcy.TheAmericangovernmenttriedtosavesomefinancial
institutionsfromcrisisbybailingthemout.However,moneyofferedbythegovernmentto
thebankswasalsothepeople’smoney,whichhadbeenpaidintaxes.Theactionsofthe
Americangovernmentledtocustomerdissatisfactionacrosstheentirecountry.Sincethe
globaleconomyisinterconnectedandmostbanksworkinbrotherhood,theeventsthattook
placeintheUnitedStatesalsoaffectedtheworld,bringingtheworld’seconomytoastandstill.
BitcoinWasBorn
Asinearlierphasesintheevolutionofmoney,afterthe2008financialcrisissome
intellectualsstarteddoubtingcentralizedsystemsasbanksandfinancialorganizations.Why?
Banksmightnotbeactuallyatrustedthirdpartyforsecuringallthemoney.
Bankschargeahugefeefortheirservices,especiallyforinternationalremittances.
Theytakeconsiderabletimeforclearingtransactionsininterbankandintercountry
transactions.
It’squiteamusingthatwhileinmostcountriesintheworld,democracyisprevalentin
termsofchoosingleadership,whenitcomestomoneywestillliveinautocracyasthemoney
ishandledbybanks,acentralizedthirdparty,ratherthanlyinginthehandsofthepeople.
Indocumentedhumanhistoryoverthepastthousandyears,wehavewitnessedmany
demonetizations,whereanexistingcurrencyisinvalidated,followedbyremonetization,in
whichaformofpaymentisrestoredaslegaltender.Currencieswereamererepresentationof
exchangemediaandyetcarriednovaluewithoutthebackingofkings,emperors,orruling
governments.
Cryptocurrencyisonesuchcurrency:itsdistributionandexchangethoughisentirely
confinedtothedigitalworld.Contrarytothebeliefofmany,Bitcoinisnotthefirst
cryptocurrency.DigiCashin1992,CyberCashin1994,E-Goldin1996,WebMoneyin1998,
LibertyReservein2006,andPerfectMoneyin2007wereallcryptoordigitalcurrencies,
someofwhicharestillinusebycommunities.HoweverBitcoinwasrevolutionaryasitcame
upwithanew,previouslyunseenconcept:decentralization.
Note Whileallthesecurrenciesarereferredtoascryptocurrency,theregularcurrencies
suchasUSD,GBP,INR,andsoonarestillknownasfiatcurrenciesorfiatcash.
BitcoinWhitePaper
It’shardtobelievethelegendarycryptocurrencyBitcoinisonlyadecadeoldandonlyababy
intheworldofmoneyandyetcouldbringinsuchhighvaluetothemonetarysystem.In
October2008,SatoshiNakamoto’snine-pageBitcoinwhitepaperappearedonthemarket,
andnottoomanypaidattention.However,injustunderadecade’stime,thistechnology
provedtobethemostdisruptivesincetheinventionoftheInternetitself.Thiswhitepaper
specified
InstructionsonhowtoruntheBitcoinnetwork.
WhyandhowtransactionsarehashedandsavedtoMerkleroot(shouldbeexplainedlater
inthisChapter).
Hownetworkhandlesanticipatoryattacks.
HowtoestablishaProof-of-Work(PoW)systemtodeterhackers(shouldbeexplainedlater
inthisChapter).
Howitispracticallyimpossibleforhackerstochangetransactions.
Howtoprohibitdoublespendinginadecentralizedwaynotinvolvingacentralizedthird
partysuchasbanks(shouldbeexplainedlaterinthisChapter).
WhyBitcoinTooktheMarketbyStorm
Asdiscussed,overthelastthreeorfourdecades,manypeoplehavetriedtheirhandsatdigital
orelectroniccurrenciesbutfailedduetotechnicalorregulatoryissues.Sowhatvaluedid
Bitcoinbringthatmadetheworldgocrazyoverit?
Thefollowingareafewofitsbenefits:
Immunitytofraud
Lowtransactionfees
Settlementinminutes
Universallyacceptable,wellmostly
Overtheyears,thepriceofBitcoinhasgoneonarollercoasterride.Whilemanycountries
suchastheUnitedStates,Canada,andAustralia,aswellastheEuropeanUnionandsoon,
havegladlyandopenlyembracedBitcoin,therearefewwhostillhavetheirinhibitions.Iam
hopefulthatinourlifetimesadaywillarrivewhenfiatcurrencieswillbeentirelyreplacedby
theirdigitalandcryptocounterparts.
ThemostbeautifulpartofBitcoin,however,isitsunderlyingmechanismtostoredata
thatisimmutableandimmunetofraud,andtousecryptologyinasecurewayforsharingdata
acrossparties.ThisrevolutionarynewtechnologyiscalledBlockchain.Inotherwords,
Bitcoinispeer-to-peerelectroniccashthatismorevaluablethanlegacysystemsduetothe
autonomousmonetarybenefitsthatitbringsinadecentralizedmanner.Blockchainisthe
technologyofstoringrecordsordataasblockssimilartolinkedliststhatusecryptographic
hashingalgorithmsandMerkletrees.WewillcovermoreonthisChapter.
Inthelastdecade,investmentinBlockchainhasincreasedexponentially.Accordingtoa
newresearchreport,“Blockchain-as-a-ServiceMarketbyComponent(ToolsandServices),
BusinessApplication(SupplyChainManagement,SmartContracts,IdentityManagement,
Payments,andGRCManagement),OrganizationSize,Industry,andRegion-GlobalForecastto
2023,”publishedbyMarketsandMarkets,themarketisexpectedtogrowfromUSD623.0
millionin2018toUSD15,455millionby2023,atacompoundannualgrowthrate(CAGR)of
90.1%duringtheforecastperiod.
IntroductiontoBlockchain
Beforewegoanyfurther,hereareafewfeaturestobroadlydefineBlockchain:
It’sadistributedledgerorregisteroverapublicorprivatenetwork.
Everynodeinthenetworkcarriesanexactreplicaoftheledger.
Dataonthisledgerissecurebecauseit’sencryptedusingprivate-keycryptography,which
canbedecryptedonlywithitsmatchingpublickey.
Thereisnosinglepointoffailureandnodowntime.
Datacanbeaddedwitheveryone’soragroup’sconsensusratherthanacentralized
authority.Hence,it’scalleddecentralizedintermsofconsensus.
DatainBlockchainisimmutable(i.e.,oncestoredcan’tbealtered).
Eachrecordinthedatabaseisknownasablock;eachblockpointstoapreviousblockinthe
chain.
EachnewblockconsistsofagroupoftransactionsthatisaddedtotheendofaBlockchain.
Smartcontractscanrunonthisledger,triggeringprogramstorunautomaticallywhena
specificconditionismet.
Blockchainisadistributeddecentralizedledger(ordatabase)wheredatacanbeaddedin
append-onlymodeinasecureway.Thisledgercanbeusedbypartiesandorganizationsthat
donottrusteachotherforcomplexbusinesstransactionsandcanbetreatedasasingle
sourceoftruthforallparticipatingparties,aseachwillshareareplicaoftheglobaldata,just
likeothers.
Justlikeartificialintelligence,IoT,virtualreality,andsoon,Blockchainisanemerging
technology,andbeingonlyadecadeold,it’salmosttheyoungestofalltheothersimilar
technologies.Pleasenotethatresearchinartificialintelligencegotinitiatedbackin1950s–
1960s,andnowweareseeingitsusageintherealworld.However,inthecaseofBlockchain,
adoptionishappeningwithmanifoldspeed.
InordertoknowBlockchain,wehavetoknowhowBitcoinorEthereumoranyother
similarpublicBlockchainnetworkworks.Butfirst,let’sfindoutthebusinessproblemthat
Blockchaincanaddress.
BusinessProblem
BeforelearningBlockchainordistributedledgertechnology(DLT)indetail,onemaywonder
whythemarketissofascinatedregardingBlockchain.IfBlockchainisastoringmechanism,
manysuchmechanismshaveexistedinindustryfordecades.
TheansweristhatBlockchainisnotusefultostoredataforanindividual,butisusefulfor
multipleparties,especiallythosewhodonottrusteachotherandyetwishtosharedatafor
somebusinesstransaction.
So,let’sfindoutaboutthedifferentmechanismsusedinthecurrentmarkettoallow
enterprisesasbanks,financialorganizations,andglobaldistributedsystems(GDS)intravel
orsupplychainsystemstocommunicatewitheachother.Considerthreeindependent
organizationstryingtodosomebusinesstogetherforanyvertical.Beforetheircollaboration,
theyhadtheirindividualdataintheirrespectivesilos.Nowthattheyhavecometogether,
whatarethepossiblewaystosharedata?Mostorganizationssharedataintwodifferent
ways:fullydistributedmodelorfullycentralizedmodel.However,nowwehaveathirdmodel
toexplore:DLT,thedecentralizedpeer-to-peermodel,orBlockchain.Let’sdiscussthemin
detail.
FullyDistributedModel
MostofourcurrentprojectsmustbealignedwiththismodelasspecifiedinFigure1-1,where
eachofthethreeorganizationsmaintaintheirowndataandcommunicatethroughsomeweb
serviceormessagingprotocol.Therecouldbemanyproblemsinsuchaprocess,andsolet’s
lookatafewofthem:
Mostofthedatawouldberedundant,witheachorganizationcarryingitsownversion.
Dataacrossorganizationsmightnotbeinsyncduetolatencyissues.
Processeswouldbewasteful;reconciliationswouldbecomplexandexpensive.
Figure1-1 Threeorganizationsworkingindistributedmodeofsharingdata
FullyCentralizedModel
Wehavealreadyfoundissueswithadistributedsystem,sonowhowcanwemovetoa
completelysharedmodelthatwouldbesecureandneutralforalltheseorganizations?As
showninFigure1-2,organizationsachievethismostlybydelegatingthisresponsibilitytoa
thirdpartythatwouldworkasacommonplatformforallpartiestostoreandsharedata.
Let’sexploreissueshere.
Thisisanexpensiveway,asthirdpartieswillchargeforsuchaservice.
Theymayhaveaconflictofinterestwiththeindividualorganization.Oneormoreofthe
partiesmaynotagreeonthedataforsomereason.
Therecouldbelegalissuesleadingtodataregulation.
Figure1-2 Threeorganizationsworkingincentralizedmodeofsharingdata
Sowhatcouldbeamodelwherepartiescansharedatainthemostefficientwaysothat
thefollowingconditionsaremet?
Dataatsyncacrossallthenetwork
Noorminimalredundancy
Fewerexpensesduetoreconciliationsandthelike
Easyauditing
ThenewmechanismthatcomestomindisaDLT.
DLT,theDecentralizedPeer-to-PeerModel
AsshowninFigure1-3,DLTisamechanismthatworksinapeer-to-peerfashionthatis
differentfromthetwopreviousmodels.UsingDLT,wecandevelopapplicationsand
platformswhereownershipissharedacrossthenetworkofcollaboratingcompanies,
completelyeliminatingtheneedforathirdpartiestooperatetheapplicationsonyourbehalf.
Mutualprocessesanddataaresharedastamperproofsinglesourcesoftruththatentirely
removetheneedfortraditionalintegration,datatranslation,duplication,andredundancy.
DatasynchronizationandconsensusareprovidedbytheDLTplatform.Applicationsare
builtonceincollaborationandusedbymanyparties.
Figure1-3 Threeorganizationsworkinginpeer-to-peermodeofsharingdata
Nowthatyoubroadlyknowthethreemodels,justseehownodesrepresentingpartiescan
bepictoriallyrepresented.Figure1-4isapictorialcomparisonbetweencentralized
client/serverandpeer-to-peermodels.
Figure1-4 Client/servervs.peer-to-peermodel
Nowlet’sseehowthesetwopatternscanbefurthermodifiedbybringingahigher
intensityofdecentralizationtotheoverallnetworkinFigure1-5.
Figure1-5 Client/servermodelinmoreandmoredecentralizedmode
InFigure1-6,observehowpeer-to-peernetworksworkwhenthereisnocentralserver.
Figure1-6 Peer-to-peermodelinmoreandmoredecentralizedmode
OK,nowthatyouareconvincedaboutwhyweneedDLT,let’salsodiscussthebenefitsof
BlockchainandhowBlockchainisdifferentfromandsimilartoDLT.
BenefitsofBlockchain
OnemaywonderifBlockchainisanothertypeofdatabaseandwhywecreateditinthefirst
place.PleasenotethatBlockchainwasintroducedtousthroughBitcoin,acryptocurrency,
anditwasconceptualizedtoaddresstheneedsofdigitalcurrencyinawaythatatraditional
databasecannot.
ThedatainaBlockchainledgercan’tbealtered.
It’sahighlysecureddatabasethatusespublicandprivatekeysfortransactions.
Thedatabaseispubliclyavailableforeveryonetovalidateandaddtransactions.
Beingdecentralized,thereisnodowntimeinBlockchainandhencetransactionscanbe
addedanytimeandfromanywhere.
Itcouldbepublicorprivateaspertheindividual’sororganization’sbusinessneedsand
henceisflexible.
Ledgerisopentoauditinganytime.
DLTvs.Blockchain
BlockchainisaspecialusecaseofDLT.OnceyouexploremoreonBlockchain,comebackto
thissectionandreaditagaintofigureoutwheretheyaresimilarandwheretheydiffer.
Similarities
Bothusepublic/private-keycryptography
Bothusehashing
Bothusepeer-to-peermodelforcommunication
Differences
Blockchainusesnativecurrency,whichisamandate;DLTdoesnot
Blockchainisdistributed(i.e.,alldatacanbevisibletoallnodes);DLTisnot
Blockchainispermission-less;DLTisnot
BlockchainworkswithPoW(thoughsoonEthereumwillbecomingoutwithProofofStake
[PoS]);DLTdoesnot
BlockchainBusinessValue
Theyear2018wasamassiveyearforBlockchain.FromProofofConcepts(PoCs)topilots,
slowlyandyetsteadilyorganizationsstartedadvancingtheirBlockchainjourneytoward
production.Oraclesees10%ofglobalGDPstoredinBlockchainby2027,andDeloittepredicts
thatby2025,~10%ofglobalGDPwillbestoredinBlockchain.Aspertheresearchinstitute
IDC,worldwideBlockchainspendingwillgrow81.2%to$9.7billionin2021.Many
organizationsandcorporationsarepayingdoublethestandardsalarytoprofessionalswho
arehandsonwithBlockchaintechnology,andthetrendisjustbeginning.Reportssaythatin
manycountries,includingIndia,only1in400ITprofessionalsarehandsonwiththe
technology,whichleaveshugeroomfortrainingandplacement.
BlockchainInternals
Nowlet’sseehowdataisaddedtoaBlockchainledger.Considerabook,asrepresentedin
Figure1-7,thathas100pages,withapagenumberatthetopofeachpage.Ifonepageistorn
outfromthebook,thereaderwouldeasilytraceitout.ThesameistrueforaBlockchain
store.
Figure1-7 IndexinginBlockchain
BlockchainTransactionandBlocks
Asthenamesuggests,Blockchainisachainofblockswhereeachblockpointstoaprevious
block.
Eachblockconsistsof
Ablockheader
Oneormoretransactionsintheblock
IfwecompareBlockchaindatastoretoabook,theneachblockrepresentsapageinthe
bookandtransactionsquotedintheindividualblockaresynonymoustolinesonapageinthe
book.
ThefirstblockinaBlockchainledgerasshowninFigure1-8isknownasagenesisblock.
Umersoruncleblocksarethedetachedblocksnotchosenforinclusionintheconsensus
Blockchain.However,miners(tobeexplainedvalidatorsoftransaction)canalsodiscover
smallernumbersoftokens.