UsingErlang inBlockchainDevelopment
UlfWigerÆternity
CodeBEAMSTO,Stockholm1Jun2018
Stopalltheclocks,cutoffthetelephone,Preventthedog frombarkingwiththejuicybone.Silencethepianosand,withmuffleddrum,Bringoutthecoffin.Letthemourners come.
What'stheBestLanguageforPoetry?
Ja nog är det svårt när droppar faller.Skälvande av ängslan tungt de hänger,klamrar sig vid kvisten, sväller, glider –tyngden drar dem neråt, hur de klänger.
ExpressingComplexIdeas
• Languagesareshapedbycultureandexperience• Thelanguageshapestheexpressionofcomplexideas• Universalgrammar(Chomsky2000)
TranslatingComplexIdeas
Furu ike yakawazu tobikomumizu no oto
Old pond — frogs jumped in — sound of water.
A lonely pond in age-old stillness sleeps . . .Apart, unstirred by sound or motion . . . tillSuddenly into it a lithe frog leaps.
Into the ancient pondA frog jumpsWater’s sound!
Theoldpond,Afrogjumps in:Plop!
http://www.bopsecrets.org/gateway/passages/basho-frog.htm
OpinionatedProgrammingLanguagesInstruction-level
Math-oriented
Everything'sanobject
Concurrent/functional
TheModernDivide
• PerformancevsProductivity• High-Levellanguages—slowerbutsome10xmoreproductive
• Erlang,Python,Scala,Haskell,Clojure,...• Low-Level—detailed,lowoverhead
• C/C++,linkable• Java,etc.non-linkable
• Performanceincomplexsystemsisadifferentbeast• HLlanguages maywellbefasteronsometasks,e.g.
• Complexmemorymanagement• Complexconcurrency
TheModernDivide(2)
• Concurrency• Strongconcurrencybydesign
• Erlang,Clojure,Haskell,GO(Rust?)...• Concurrencyasanafterthought
• C/C++,Python,(Java),...
• Fault-tolerance• Bydesign
• Erlang,Akka,CloudHaskell...• DIY
• Mostoftherest
WhatAboutBlockchains?
• Fewpartsareperformancecritical(today)• MainlyProofofWork,hashing,signatures• TreatasanexternalserviceorBIFs(potentiallyspecifichardware)
• Lotsofnetworking• Movingtarget• Algorithms/featuresstillevolving
HowDoesErlang Help?
• Looselycoupledcomponents• Simplifiesparalleldevelopment• Simplifiesreuse• Flexibleevolution
• ConcurrencyDoneRight• Protocolaspectsisolatedfromprogramlogic• Easytochange/evolveprotocols• Networkingscalabilitynotabigconcern• (we'renotusingDistributedErlang)• Complexstatemachinesupport(morelater)
HowDoesErlang Help?(2)
• FunctionalProgramming• Simplifiestesting• Code,oncecorrect,tendstostay correct• Reducessurprisingside-effects• Powerfulforblockchain statemanagement
• Carrier-ClassProductMentality• Stellarbackwardcompatibility• Rock-solidVM• No"dependencyhell"• Basically'attack-proof' networkingsupport
Challenges?
• Fewotherblockchain projectsuseErlang• Feweropportunitiesfordirectreuse• Thenagain,re-writing/portingaidsunderstanding;-)
• Doesn'trunoniOSorAndroid• Notnecessarilymuchofadisadvantage
StatechannelsinErlang
• Purpose:Establish"off-chain"channelsforfastandcheaptransactions• On-chainactivityonlywhenopeningandclosingchannel• Fundslockedintothechannelcanbetransferredinco-signedtransactions"forfree"• "Trustbutverify"off-chain,Mutualcloseordisputeresolutionon-chain
Ónen i-Estel Edain.Ú-chebin Estel anim
• Designdecision: SCdaemonwithasimplifiedWebSocket API• Complicatesthestatemachine• HopefullysimplifiesclientAppdesign
{Transfer,From,To,Amt}
{sign,NewStateTx}
{signed, SignedTx}
{update,SignedTx}{sign, SignedTx}
{signed, CoSignedTx}
{update_ack,CoSignedTx}{info, CoSignedTx}
Awaiting_signature
Awaiting_update_ack Awaiting_signature
Transitionstates!
AvoidDeathbyAccidentalComplexity
• https://www.infoq.com/presentations/Death-by-Accidental-Complexity(2010talk,basedonStructuredNetworkProgramming EUC2005)
• Mustavoidhavingtohandleallpossibleorderingsofincomingmessages• Otherwise,complexityexplosionintransitionstates
StateMachineprogramminginErlang
• Old-school:textbookErlang• Simpleandbeautiful• Noautomaticsupportforsystems(OTP)functionality• plain_fsm – acludgyway of getting both
• Oldbehavior:gen_fsm• SupportsOTPfunctionality• Doesn'thandleFSMcomplexity(noselectivereceive)
• Newbehavior:gen_statem• SupportsOTPfunctionality• Supportsselective receive
Erlang paysoff—FSMprogramminginpractice• Asmanyprocessesaslogicallyconvenient• Separateconcerns• Linkedtogetherforfailurehandling
noisesession(gen_server)
noisesession(gen_server)
SCfsm(gen_statem)
SCfsm(gen_statem)
WShandler(cowboycallback)
WShandler(cowboycallback)
Chainwatcher(gen_server)
Chainwatcher(gen_server)
Transitionstatehandlingingen_statem
Validevents,butshouldnotbehandledhere
Pattern-matchassertingthatwegottheeventwewerewaitingfor
Invalidevents(fornow)handledbydefault
Insummary
• Notalwayseasytosaywhy alanguageisinitiallychosen• Languages(esp.opinionated ones)shapeyourthinking• Erlang wellsuitedtoblockchain development• Brilliantforstatechannelprogramming!
• Thegen_statembehaviorisanexcellentadditiontoOTP
Æternity epochDependencies
• OTPcomponentsused• Mnesia (DBMS)• ssl,inets,asn1(comms)• runtime_tools (tracing)
• Æternity coreapps• Coresvcs,mining,chain,txs,...• HTTP-,Websocket API,Gossip• SmartContracts,AEVM• NamingService• Oracles
• Externalcomponents• Cuckoocycle(C++,ownwrapper)• RocksDb (mnesia backend)• Exometer (metrics)• Cowboy(webserver)• Jsx,yamerl,base58,msgpack• Jesse(JSON-Schemavalidation)• IDNA• enacl,sha3• gproc,jobs,lager,poolboy,...
BuildandTest
• Rebar3forbuild(worksso-so)• EUnit,CommonTestfortestautomation• Dialyzertypeanalysis• Quviq QuickCheckmodels
• Python-basedacceptancetestsuite