developer guide - bitcoin
DESCRIPTION
aTRANSCRIPT
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 1/55
Bitcoin Developer Guide
FinddetailedinformationabouttheBitcoinprotocolandrelatedspecifications.
Searchtheglossary,RPCs,andmore
TheDeveloperGuideaimstoprovidetheinformationyouneedtounderstandBitcoinandstartbuildingBitcoinbasedapplications,butitisnotaspecification.Tomakethebestuseofthisdocumentation,youmaywanttoinstallthecurrentversionofBitcoinCore,eitherfromsourceorfromaprecompiledexecutable.
QuestionsaboutBitcoindevelopmentarebestaskedinoneoftheBitcoindevelopmentcommunities.ErrorsorsuggestionsrelatedtodocumentationonBitcoin.orgcanbesubmittedasanissueorpostedtothebitcoindocumentationmailinglist.
Inthefollowingdocumentation,somestringshavebeenshortenedorwrapped:[]indicatesextradatawasremoved,andlinesendinginasinglebackslash\arecontinuedbelow.Ifyouhoveryourmouseoveraparagraph,crossreferencelinkswillbeshowninblue.Ifyouhoveroveracrossreferencelink,abriefdefinitionofthetermwillbedisplayedinatooltip.
TheblockchainprovidesBitcoinspublicledger,anorderedandtimestampedrecordoftransactions.Thissystemisusedtoprotectagainstdoublespendingandmodificationofprevioustransactionrecords.
EachfullnodeintheBitcoinnetworkindependentlystoresablockchaincontainingonlyblocksvalidatedbythatnode.Whenseveralnodesallhavethesameblocksintheirblockchain,theyareconsideredtobeinconsensus.Thevalidationrulesthesenodesfollowtomaintainconsensusarecalledconsensusrules.ThissectiondescribesmanyoftheconsensusrulesusedbyBitcoinCore.
Simplified Bitcoin Block Chain
Block 1Header
Block 2Header
Block 3Header
Block 1Transactions
Merkle Root
Block 2Transactions
Hash Of PreviousBlock Header
Hash Of PreviousBlock Header
Merkle Root
Block 3Transactions
Hash Of PreviousBlock Header
Merkle Root
Theillustrationaboveshowsasimplifiedversionofablockchain.Ablockofoneormorenewtransactionsiscollectedintothetransactiondatapartofablock.Copiesofeachtransactionarehashed,andthehashesarethenpaired,hashed,pairedagain,andhashedagainuntilasinglehashremains,themerklerootofamerkletree.
Themerklerootisstoredintheblockheader.Eachblockalsostoresthehashofthepreviousblocksheader,chainingtheblockstogether.Thisensuresatransactioncannotbemodifiedwithoutmodifyingtheblockthatrecordsitandallfollowingblocks.
Block Chain
BlockChainOverview
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 2/55
Transactionsarealsochainedtogether.Bitcoinwalletsoftwaregivestheimpressionthatsatoshisaresentfromandtowallets,butbitcoinsreallymovefromtransactiontotransaction.Eachtransactionspendsthesatoshispreviouslyreceivedinoneormoreearliertransactions,sotheinputofonetransactionistheoutputofaprevioustransaction.
Triple-Entry Bookkeeping (Transaction-To-Transaction Payments) As Used By Bitcoin
Transaction 0(TX 0)
TX 1
TX 2
TX 3
TX 4
TX 5
TX 6
input0
output0
input040k
output1 input050k
output0 input030k
output0 input020k
output1
input0
20k
output020k Unspent TXOutput (UTXO)
output0input0
10k
output0
input110k
output010k
UTXO
100,000(100k)
satoshis
Asingletransactioncancreatemultipleoutputs,aswouldbethecasewhensendingtomultipleaddresses,buteachoutputofaparticulartransactioncanonlybeusedasaninputonceintheblockchain.Anysubsequentreferenceisaforbiddendoublespendanattempttospendthesamesatoshistwice.
Outputsaretiedtotransactionidentifiers(TXIDs),whicharethehashesofsignedtransactions.
Becauseeachoutputofaparticulartransactioncanonlybespentonce,theoutputsofalltransactionsincludedintheblockchaincanbecategorizedaseitherUnspentTransactionOutputs(UTXOs)orspenttransactionoutputs.Forapaymenttobevalid,itmustonlyuseUTXOsasinputs.
Ignoringcoinbasetransactions(describedlater),ifthevalueofatransactionsoutputsexceeditsinputs,thetransactionwillberejectedbutiftheinputsexceedthevalueoftheoutputs,anydifferenceinvaluemaybeclaimedasatransactionfeebytheBitcoinminerwhocreatestheblockcontainingthattransaction.Forexample,intheillustrationabove,eachtransactionspends10,000satoshisfewerthanitreceivesfromitscombinedinputs,effectivelypayinga10,000satoshitransactionfee.
Theblockchainiscollaborativelymaintainedbyanonymouspeersonthenetwork,soBitcoinrequiresthateachblockproveasignificantamountofworkwasinvestedinitscreationtoensurethatuntrustworthypeerswhowanttomodifypastblockshavetoworkharderthanhonestpeerswhoonlywanttoaddnewblockstotheblockchain.
Chainingblockstogethermakesitimpossibletomodifytransactionsincludedinanyblockwithoutmodifyingallfollowingblocks.Asaresult,thecosttomodifyaparticularblockincreaseswitheverynewblockaddedtotheblockchain,magnifyingtheeffectoftheproofofwork.
TheproofofworkusedinBitcointakesadvantageoftheapparentlyrandomnatureofcryptographichashes.Agoodcryptographichashalgorithmconvertsarbitrarydataintoaseeminglyrandomnumber.Ifthedataismodifiedinanywayandthehashrerun,a
ProofOfWork
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 3/55
newseeminglyrandomnumberisproduced,sothereisnowaytomodifythedatatomakethehashnumberpredictable.
Toproveyoudidsomeextraworktocreateablock,youmustcreateahashoftheblockheaderwhichdoesnotexceedacertainvalue.Forexample,ifthemaximumpossiblehashvalueis2 1,youcanprovethatyoutrieduptotwocombinationsbyproducingahashvaluelessthan2 .
Intheexamplegivenabove,youwillproduceasuccessfulhashonaverageeveryothertry.Youcanevenestimatetheprobabilitythatagivenhashattemptwillgenerateanumberbelowthetargetthreshold.Bitcoinassumesalinearprobabilitythattheloweritmakesthetargetthreshold,themorehashattempts(onaverage)willneedtobetried.
Newblockswillonlybeaddedtotheblockchainiftheirhashisatleastaschallengingasadifficultyvalueexpectedbytheconsensusprotocol.Every2,016blocks,thenetworkusestimestampsstoredineachblockheadertocalculatethenumberofsecondselapsedbetweengenerationofthefirstandlastofthoselast2,016blocks.Theidealvalueis1,209,600seconds(twoweeks).
Ifittookfewerthantwoweekstogeneratethe2,016blocks,theexpecteddifficultyvalueisincreasedproportionally(byasmuchas300%)sothatthenext2,016blocksshouldtakeexactlytwoweekstogenerateifhashesarecheckedatthesamerate.
Ifittookmorethantwoweekstogeneratetheblocks,theexpecteddifficultyvalueisdecreasedproportionally(byasmuchas75%)forthesamereason.
(Note:anoffbyoneerrorintheBitcoinCoreimplementationcausesthedifficultytobeupdatedevery2,016blocksusingtimestampsfromonly2,015blocks,creatingaslightskew.)
Becauseeachblockheadermusthashtoavaluebelowthetargetthreshold,andbecauseeachblockislinkedtotheblockthatprecededit,itrequires(onaverage)asmuchhashingpowertopropagateamodifiedblockastheentireBitcoinnetworkexpendedbetweenthetimetheoriginalblockwascreatedandthepresenttime.Onlyifyouacquiredamajorityofthenetworkshashingpowercouldyoureliablyexecutesucha51percentattackagainsttransactionhistory(although,itshouldbenoted,thatevenlessthan50%ofthehashingpowerstillhasagoodchanceofperformingsuchattacks).
Theblockheaderprovidesseveraleasytomodifyfields,suchasadedicatednoncefield,soobtainingnewhashesdoesntrequirewaitingfornewtransactions.Also,onlythe80byteblockheaderishashedforproofofwork,soincludingalargevolumeoftransactiondatainablockdoesnotslowdownhashingwithextraI/O,andaddingadditionaltransactiondataonlyrequirestherecalculationoftheancestorhashesinthemerkletree.
AnyBitcoinminerwhosuccessfullyhashesablockheadertoavaluebelowthetargetthresholdcanaddtheentireblocktotheblockchain(assumingtheblockisotherwisevalid).TheseblocksarecommonlyaddressedbytheirblockheightthenumberofblocksbetweenthemandthefirstBitcoinblock(block0,mostcommonlyknownasthegenesisblock).Forexample,block2016iswheredifficultycouldhavefirstbeenadjusted.
Rare Extended Forking
Normal Occasional Forking
block0 block1Header Hash
block2
block2
block3 block4 block5 block6
block3 block4 block5
block2 block5
block1 block2 block4 block5block0 Header Hash block3 block6
Multipleblockscanallhavethesameblockheight,asiscommonwhentwoormoreminerseachproduceablockatroughlythe
256
255
BlockHeightAndForking
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 4/55
sametime.Thiscreatesanapparentforkintheblockchain,asshownintheillustrationabove.
Whenminersproducesimultaneousblocksattheendoftheblockchain,eachnodeindividuallychooseswhichblocktoaccept.Intheabsenceofotherconsiderations,discussedbelow,nodesusuallyusethefirstblocktheysee.
Eventuallyaminerproducesanotherblockwhichattachestoonlyoneofthecompetingsimultaneouslyminedblocks.Thismakesthatsideoftheforkstrongerthantheotherside.Assumingaforkonlycontainsvalidblocks,normalpeersalwaysfollowthethemostdifficultchaintorecreateandthrowawaystaleblocksbelongingtoshorterforks.(Staleblocksarealsosometimescalledorphansororphanblocks,butthosetermsarealsousedfortrueorphanblockswithoutaknownparentblock.)
Longtermforksarepossibleifdifferentminersworkatcrosspurposes,suchassomeminersdiligentlyworkingtoextendtheblockchainatthesametimeotherminersareattemptinga51percentattacktorevisetransactionhistory.
Sincemultipleblockscanhavethesameheightduringablockchainfork,blockheightshouldnotbeusedasagloballyuniqueidentifier.Instead,blocksareusuallyreferencedbythehashoftheirheader(oftenwiththebyteorderreversed,andinhexadecimal).
Everyblockmustincludeoneormoretransactions.Thefirstoneofthesetransactionsmustbeacoinbasetransaction,alsocalledagenerationtransaction,whichshouldcollectandspendtheblockreward(comprisedofablocksubsidyandanytransactionfeespaidbytransactionsincludedinthisblock).
TheUTXOofacoinbasetransactionhasthespecialconditionthatitcannotbespent(usedasaninput)foratleast100blocks.Thistemporarilypreventsaminerfromspendingthetransactionfeesandblockrewardfromablockthatmaylaterbedeterminedtobestale(andthereforethecoinbasetransactiondestroyed)afterablockchainfork.
Blocksarenotrequiredtoincludeanynoncoinbasetransactions,butminersalmostalwaysdoincludeadditionaltransactionsinordertocollecttheirtransactionfees.
Alltransactions,includingthecoinbasetransaction,areencodedintoblocksinbinaryrawtransactionformat.
Therawtransactionformatishashedtocreatethetransactionidentifier(txid).Fromthesetxids,themerkletreeisconstructedbypairingeachtxidwithoneothertxidandthenhashingthemtogether.Ifthereareanoddnumberoftxids,thetxidwithoutapartnerishashedwithacopyofitself.
Theresultinghashesthemselvesareeachpairedwithoneotherhashandhashedtogether.Anyhashwithoutapartnerishashedwithitself.Theprocessrepeatsuntilonlyonehashremains,themerkleroot.
Forexample,iftransactionsweremerelyjoined(nothashed),afivetransactionmerkletreewouldlooklikethefollowingtextdiagram:
ABCDEEEE .......Merkle root / \ ABCD EEEE / \ / AB CD EE .......E is paired with itself/ \ / \ /A B C D E .........Transactions
AsdiscussedintheSimplifiedPaymentVerification(SPV)subsection,themerkletreeallowsclientstoverifyforthemselvesthatatransactionwasincludedinablockbyobtainingthemerklerootfromablockheaderandalistoftheintermediatehashesfromafullpeer.Thefullpeerdoesnotneedtobetrusted:itisexpensivetofakeblockheadersandtheintermediatehashescannotbefakedortheverificationwillfail.
TransactionData
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 5/55
Forexample,toverifytransactionDwasaddedtotheblock,anSPVclientonlyneedsacopyoftheC,AB,andEEEEhashesinadditiontothemerkleroottheclientdoesntneedtoknowanythingaboutanyoftheothertransactions.Ifthefivetransactionsinthisblockwereallatthemaximumsize,downloadingtheentireblockwouldrequireover500,000bytesbutdownloadingthreehashesplustheblockheaderrequiresonly140bytes.
Note:Ifidenticaltxidsarefoundwithinthesameblock,thereisapossibilitythatthemerkletreemaycollidewithablockwithsomeorallduplicatesremovedduetohowunbalancedmerkletreesareimplemented(duplicatingthelonehash).Sinceitisimpracticaltohaveseparatetransactionswithidenticaltxids,thisdoesnotimposeaburdenonhonestsoftware,butmustbecheckediftheinvalidstatusofablockistobecachedotherwise,avalidblockwiththeduplicateseliminatedcouldhavethesamemerklerootandblockhash,butberejectedbythecachedinvalidoutcome,resultinginsecuritybugssuchasCVE20122459.
Tomaintainconsensus,allfullnodesvalidateblocksusingthesameconsensusrules.However,sometimestheconsensusrulesarechangedtointroducenewfeaturesorpreventnetworkabuse.Whenthenewrulesareimplemented,therewilllikelybeaperiodoftimewhennonupgradednodesfollowtheoldrulesandupgradednodesfollowthenewrules,creatingtwopossiblewaysconsensuscanbreak:
1. Ablockfollowingthenewconsensusrulesisacceptedbyupgradednodesbutrejectedbynonupgradednodes.Forexample,anewtransactionfeatureisusedwithinablock:upgradednodesunderstandthefeatureandacceptit,butnonupgradednodesrejectitbecauseitviolatestheoldrules.
2. Ablockviolatingthenewconsensusrulesisrejectedbyupgradednodesbutacceptedbynonupgradednodes.Forexample,anabusivetransactionfeatureisusedwithinablock:upgradednodesrejectitbecauseitviolatesthenewrules,butnonupgradednodesacceptitbecauseitfollowstheoldrules.
Inthefirstcase,rejectionbynonupgradednodes,miningsoftwarewhichgetsblockchaindatafromthosenonupgradednodesrefusestobuildonthesamechainasminingsoftwaregettingdatafromupgradednodes.Thiscreatespermanentlydivergentchainsonefornonupgradednodesandoneforupgradednodescalledahardfork.
A Hard Fork: Non-Upgraded Nodes Reject The New Rules, Diverging The Chain
BlocksFrom
UpgradedNodes
BlocksFrom Non-Upgraded
Nodes
FollowsOld
Rules
FollowsOld
Rules
FollowsOld
Rules
FollowsNewRules
FollowsOld
Rules
FollowsNewRules
FollowsNewRules
FollowsNewRules
Inthesecondcase,rejectionbyupgradednodes,itspossibletokeeptheblockchainfrompermanentlydivergingifupgradednodescontrolamajorityofthehashrate.Thatsbecause,inthiscase,nonupgradednodeswillacceptasvalidallthesameblocksasupgradednodes,sotheupgradednodescanbuildastrongerchainthatthenonupgradednodeswillacceptasthebestvalidblockchain.Thisiscalledasoftfork.
A Soft Fork: Blocks Violating New Rules Are Made Stale By The Upgraded Mining Majority
BlocksFrom
UpgradedNodes
BlocksFrom Non-Upgraded
Nodes
FollowsOld
Rules
FollowsOld
Rules
Follows Old RulesBut ViolatesNew Rules
FollowsOld & New
Rules
FollowsOld
Rules
FollowsOld & New
Rules
ConsensusRuleChanges
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 6/55
Althoughaforkisanactualdivergenceinblockchains,changestotheconsensusrulesareoftendescribedbytheirpotentialtocreateeitherahardorsoftfork.Forexample,increasingtheblocksizeabove1MBrequiresahardfork.Inthisexample,anactualblockchainforkisnotrequiredbutitisapossibleoutcome.
Resources:BIP16,BIP30,andBIP34wereimplementedaschangeswhichmighthaveleadtosoftforks.BIP50describesbothanaccidentalhardfork,resolvedbytemporarydowngradingthecapabilitiesofupgradednodes,andanintentionalhardforkwhenthetemporarydowngradewasremoved.AdocumentfromGavinAndresenoutlineshowfuturerulechangesmaybeimplemented.
Nonupgradednodesmayuseanddistributeincorrectinformationduringbothtypesofforks,creatingseveralsituationswhichcouldleadtofinancialloss.Inparticular,nonupgradednodesmayrelayandaccepttransactionsthatareconsideredinvalidbyupgradednodesandsowillneverbecomepartoftheuniversallyrecognizedbestblockchain.Nonupgradednodesmayalsorefusetorelayblocksortransactionswhichhavealreadybeenaddedtothebestblockchain,orsoonwillbe,andsoprovideincompleteinformation.
BitcoinCoreincludescodethatdetectsahardforkbylookingatblockchainproofofwork.Ifanonupgradednodereceivesblockchainheadersdemonstratingatleastsixblocksmoreproofofworkthanthebestchainitconsidersvalid,thenodereportsanerrorinthe getinfoRPCresultsandrunsthe -alertnotifycommandifset.Thiswarnstheoperatorthatthenonupgradednodecantswitchtowhatislikelythebestblockchain.
Fullnodescanalsocheckblockandtransactionversionnumbers.Iftheblockortransactionversionnumbersseeninseveralrecentblocksarehigherthantheversionnumbersthenodeuses,itcanassumeitdoesntusethecurrentconsensusrules.BitcoinCore0.10.0reportsthissituationthroughthe getinfoRPCand -alertnotifycommandifset.
Ineithercase,blockandtransactiondatashouldnotberelieduponifitcomesfromanodethatapparentlyisntusingthecurrentconsensusrules.
SPVclientswhichconnecttofullnodescandetectalikelyhardforkbyconnectingtoseveralfullnodesandensuringthattheyreallonthesamechainwiththesameblockheight,plusorminusseveralblockstoaccountfortransmissiondelaysandstaleblocks.Iftheresadivergence,theclientcandisconnectfromnodeswithweakerchains.
SPVclientsshouldalsomonitorforblockandtransactionversionnumberincreasestoensuretheyprocessreceivedtransactionsandcreatenewtransactionsusingthecurrentconsensusrules.
Transactionsletusersspendsatoshis.Eachtransactionisconstructedoutofseveralpartswhichenablebothsimpledirectpaymentsandcomplextransactions.Thissectionwilldescribeeachpartanddemonstratehowtousethemtogethertobuildcompletetransactions.
Tokeepthingssimple,thissectionpretendscoinbasetransactionsdonotexist.CoinbasetransactionscanonlybecreatedbyBitcoinminersandtheyreanexceptiontomanyoftheruleslistedbelow.Insteadofpointingoutthecoinbaseexceptiontoeachrule,weinviteyoutoreadaboutcoinbasetransactionsintheblockchainsectionofthisguide.
DetectingForks
Transactions
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 7/55
Locktime
Locktime
Outputs
Inputs Outputs
InputsVersion
Version
The Main Parts OfTransaction 0
Each input spends a previous output
Each output waits as an Unspent TX Output (UTXO) until a later input spends it
The Main Parts OfTransaction 1
ThefigureaboveshowsthemainpartsofaBitcointransaction.Eachtransactionhasatleastoneinputandoneoutput.Eachinputspendsthesatoshispaidtoapreviousoutput.EachoutputthenwaitsasanUnspentTransactionOutput(UTXO)untilalaterinputspendsit.WhenyourBitcoinwallettellsyouthatyouhavea10,000satoshibalance,itreallymeansthatyouhave10,000satoshiswaitinginoneormoreUTXOs.
EachtransactionisprefixedbyafourbytetransactionversionnumberwhichtellsBitcoinpeersandminerswhichsetofrulestousetovalidateit.Thisletsdeveloperscreatenewrulesforfuturetransactionswithoutinvalidatingprevioustransactions.
Overview Of Transaction Spending
Example Output Paying A Pubkey Script
Example Input Spending The Example Output
Transaction1
Transaction0
TransactionIdentifier
Not Shown:Version, Outputs,
Locktime
Not Shown:Version, Inputs,
LocktimePubkeyScript
SignatureScript
Amount(satoshis)
Output 0(Implied)
OutputIndex
SequenceNumber
Anoutputhasanimpliedindexnumberbasedonitslocationinthetransactionthefirstoutputisoutputzero.Theoutputalsohasanamountinsatoshiswhichitpaystoaconditionalpubkeyscript.Anyonewhocansatisfytheconditionsofthatpubkeyscriptcanspenduptotheamountofsatoshispaidtoit.
Aninputusesatransactionidentifier(txid)andanoutputindexnumber(oftencalledvoutforoutputvector)toidentifyaparticularoutputtobespent.Italsohasasignaturescriptwhichallowsittoprovidedataparametersthatsatisfytheconditionalsinthepubkeyscript.(Thesequencenumberandlocktimearerelatedandwillbecoveredtogetherinalatersubsection.)
ThefiguresbelowhelpillustratehowthesefeaturesareusedbyshowingtheworkflowAliceusestosendBobatransactionandwhichBoblaterusestospendthattransaction.BothAliceandBobwillusethemostcommonformofthestandardPayToPublicKeyHash(P2PKH)transactiontype.P2PKHletsAlicespendsatoshistoatypicalBitcoinaddress,andthenletsBobfurtherspendthosesatoshisusingasimplecryptographickeypair.
Creating A P2PKH Public Key Hash To Receive Payment
Bob's Computer Alice's Computer TX 1
PrivateKey
FullPublic Key
Public KeyHash
Copy OfPublic Key
Hash
Copy OfPublic Key
Hash
Bobmustfirstgenerateaprivate/publickeypairbeforeAlicecancreatethefirsttransaction.BitcoinusestheEllipticCurveDigitalSignatureAlgorithm(ECDSA)withthesecp256k1curvesecp256k1privatekeysare256bitsofrandomdata.Acopyofthatdataisdeterministicallytransformedintoansecp256k1publickey.Becausethetransformationcanbereliablyrepeatedlater,thepublic
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 8/55
keydoesnotneedtobestored.
Thepublickey(pubkey)isthencryptographicallyhashed.Thispubkeyhashcanalsobereliablyrepeatedlater,soitalsodoesnotneedtobestored.Thehashshortensandobfuscatesthepublickey,makingmanualtranscriptioneasierandprovidingsecurityagainstunanticipatedproblemswhichmightallowreconstructionofprivatekeysfrompublickeydataatsomelaterpoint.
BobprovidesthepubkeyhashtoAlice.PubkeyhashesarealmostalwayssentencodedasBitcoinaddresses,whicharebase58encodedstringscontaininganaddressversionnumber,thehash,andanerrordetectionchecksumtocatchtypos.Theaddresscanbetransmittedthroughanymedium,includingonewaymediumswhichpreventthespenderfromcommunicatingwiththereceiver,anditcanbefurtherencodedintoanotherformat,suchasaQRcodecontaininga bitcoin:URI.
OnceAlicehastheaddressanddecodesitbackintoastandardhash,shecancreatethefirsttransaction.ShecreatesastandardP2PKHtransactionoutputcontaininginstructionswhichallowanyonetospendthatoutputiftheycanprovetheycontroltheprivatekeycorrespondingtoBobshashedpublickey.TheseinstructionsarecalledthepubkeyscriptorscriptPubKey.
Alicebroadcaststhetransactionanditisaddedtotheblockchain.ThenetworkcategorizesitasanUnspentTransactionOutput(UTXO),andBobswalletsoftwaredisplaysitasaspendablebalance.
When,sometimelater,BobdecidestospendtheUTXO,hemustcreateaninputwhichreferencesthetransactionAlicecreatedbyitshash,calledaTransactionIdentifier(txid),andthespecificoutputsheusedbyitsindexnumber(outputindex).HemustthencreateasignaturescriptacollectionofdataparameterswhichsatisfytheconditionsAliceplacedinthepreviousoutputspubkeyscript.SignaturescriptsarealsocalledscriptSigs.
Pubkeyscriptsandsignaturescriptscombinesecp256k1pubkeysandsignatureswithconditionallogic,creatingaprogramableauthorizationmechanism.
Spending A P2PKH Output
TX 1 Output
Bob's ComputerSignature Script
Signature Private Key
Full Public Key Full Public Key
Pubkey Script
Public Key HashPublic Key Hash
ForaP2PKHstyleoutput,Bobssignaturescriptwillcontainthefollowingtwopiecesofdata:
1. Hisfull(unhashed)publickey,sothepubkeyscriptcancheckthatithashestothesamevalueasthepubkeyhashprovidedbyAlice.
2. Ansecp256k1signaturemadebyusingtheECDSAcryptographicformulatocombinecertaintransactiondata(describedbelow)withBobsprivatekey.ThisletsthepubkeyscriptverifythatBobownstheprivatekeywhichcreatedthepublickey.
Bobssecp256k1signaturedoesntjustproveBobcontrolshisprivatekeyitalsomakesthenonsignaturescriptpartsofhistransactiontamperproofsoBobcansafelybroadcastthemoverthepeertopeernetwork.
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 9/55
Some Of The Data Signed By Default
Transaction 1 (TX 1)
Signed Data
Transaction 2
Bob's Computer
TX2 Template
TXID
TXID
Output Index Number
Output Index Number
Pubkey Script
Pubkey Script AmountSignatureFull Public Key
Private Key Pubkey Script Amount
Asillustratedinthefigureabove,thedataBobsignsincludesthetxidandoutputindexoftheprevioustransaction,thepreviousoutputspubkeyscript,thepubkeyscriptBobcreateswhichwillletthenextrecipientspendthistransactionsoutput,andtheamountofsatoshistospendtothenextrecipient.Inessence,theentiretransactionissignedexceptforanysignaturescripts,whichholdthefullpublickeysandsecp256k1signatures.
Afterputtinghissignatureandpublickeyinthesignaturescript,BobbroadcaststhetransactiontoBitcoinminersthroughthepeertopeernetwork.Eachpeerandminerindependentlyvalidatesthetransactionbeforebroadcastingitfurtherorattemptingtoincludeitinanewblockoftransactions.
Thevalidationprocedurerequiresevaluationofthesignaturescriptandpubkeyscript.InaP2PKHoutput,thepubkeyscriptis:
OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG
Thespenderssignaturescriptisevaluatedandprefixedtothebeginningofthescript.InaP2PKHtransaction,thesignaturescriptcontainsansecp256k1signature(sig)andfullpublickey(pubkey),creatingthefollowingconcatenation:
OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIG
ThescriptlanguageisaForthlikestackbasedlanguagedeliberatelydesignedtobestatelessandnotTuringcomplete.Statelessnessensuresthatonceatransactionisaddedtotheblockchain,thereisnoconditionwhichrendersitpermanentlyunspendable.Turingincompleteness(specifically,alackofloopsorgotos)makesthescriptlanguagelessflexibleandmorepredictable,greatlysimplifyingthesecuritymodel.
Totestwhetherthetransactionisvalid,signaturescriptandpubkeyscriptoperationsareexecutedoneitematatime,startingwithBobssignaturescriptandcontinuingtotheendofAlicespubkeyscript.ThefigurebelowshowstheevaluationofastandardP2PKHpubkeyscriptbelowthefigureisadescriptionoftheprocess.
P2PKHScriptValidation
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 10/55
Evaluation Stack Over Time During Succesful P2PKH Script Validation
Instructions And Data Provided By Alice In Transaction #1's Pubkey Script
Data Provided By Bob In Transaction #2's Input Signature Script
CHECKSIGOP_EQUALVERIFYPk HashOP_HASH160OP_DUP
PubKeySig
OP_CHECKSIG
OP_EQUALVERIFY
Pk HashOP_HASH160
PubKey
Sig
OP_DUP
TRUE
PubKey
Sig
Pk Hash
Pk Hash
PubKey
Sig
Pk Hash
PubKey
Sig
PubKey
PubKey
Sig
PubKey
SigSig
Thesignature(fromBobssignaturescript)isadded(pushed)toanemptystack.Becauseitsjustdata,nothingisdoneexceptaddingittothestack.Thepublickey(alsofromthesignaturescript)ispushedontopofthesignature.
FromAlicespubkeyscript,the OP_DUPoperationisexecuted. OP_DUPpushesontothestackacopyofthedatacurrentlyatthetopofitinthiscasecreatingacopyofthepublickeyBobprovided.
Theoperationexecutednext, OP_HASH160,pushesontothestackahashofthedatacurrentlyontopofitinthiscase,Bobspublickey.ThiscreatesahashofBobspublickey.
AlicespubkeyscriptthenpushesthepubkeyhashthatBobgaveherforthefirsttransaction.Atthispoint,thereshouldbetwocopiesofBobspubkeyhashatthetopofthestack.
Nowitgetsinteresting:Alicespubkeyscriptexecutes OP_EQUALVERIFY. OP_EQUALVERIFYisequivalenttoexecuting OP_EQUALfollowedby OP_VERIFY(notshown).
OP_EQUAL(notshown)checksthetwovaluesatthetopofthestackinthiscase,itcheckswhetherthepubkeyhashgeneratedfromthefullpublickeyBobprovidedequalsthepubkeyhashAliceprovidedwhenshecreatedtransaction#1. OP_EQUALpops(removesfromthetopofthestack)thetwovaluesitcompared,andreplacesthemwiththeresultofthatcomparison:zero(false)orone(true).
OP_VERIFY(notshown)checksthevalueatthetopofthestack.Ifthevalueisfalseitimmediatelyterminatesevaluationandthetransactionvalidationfails.Otherwiseitpopsthetruevalueoffthestack.
Finally,Alicespubkeyscriptexecutes OP_CHECKSIG,whichchecksthesignatureBobprovidedagainstthenowauthenticatedpublickeyhealsoprovided.Ifthesignaturematchesthepublickeyandwasgeneratedusingallofthedatarequiredtobesigned, OP_CHECKSIGpushesthevaluetrueontothetopofthestack.
Iffalseisnotatthetopofthestackafterthepubkeyscripthasbeenevaluated,thetransactionisvalid(providedtherearenootherproblemswithit).
Pubkeyscriptsarecreatedbyspenderswhohavelittleinterestwhatthatscriptdoes.Receiversdocareaboutthescriptconditions
P2SHScripts
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 11/55
and,iftheywant,theycanaskspenderstouseaparticularpubkeyscript.Unfortunately,custompubkeyscriptsarelessconvenientthanshortBitcoinaddressesandtherewasnostandardwaytocommunicatethembetweenprogramspriortowidespreadimplementationoftheBIP70PaymentProtocoldiscussedlater.
Tosolvetheseproblems,paytoscripthash(P2SH)transactionswerecreatedin2012toletaspendercreateapubkeyscriptcontainingahashofasecondscript,theredeemscript.
ThebasicP2SHworkflow,illustratedbelow,looksalmostidenticaltotheP2PKHworkflow.Bobcreatesaredeemscriptwithwhateverscripthewants,hashestheredeemscript,andprovidestheredeemscripthashtoAlice.AlicecreatesaP2SHstyleoutputcontainingBobsredeemscripthash.
Creating A P2SH Redeem Script Hash To Receive Payment
Bob's Computer Alice's Computer TX 1
PrivateKey
FullPublic Key Redeem Script
ScriptHash
Copy OfScriptHash
Copy OfScriptHash
WhenBobwantstospendtheoutput,heprovideshissignaturealongwiththefull(serialized)redeemscriptinthesignaturescript.ThepeertopeernetworkensuresthefullredeemscripthashestothesamevalueasthescripthashAliceputinheroutputitthenprocessestheredeemscriptexactlyasitwouldifitweretheprimarypubkeyscript,lettingBobspendtheoutputiftheredeemscriptdoesnotreturnfalse.
Spending A P2SH Output
TX 1 Output
Bob's ComputerSignature Script
Signature Private Key
Full Redeem Script Full Redeem Script
Pubkey Script
Redeem Script HashRedeem Script Hash
ThehashoftheredeemscripthasthesamepropertiesasapubkeyhashsoitcanbetransformedintothestandardBitcoinaddressformatwithonlyonesmallchangetodifferentiateitfromastandardaddress.ThismakescollectingaP2SHstyleaddressassimpleascollectingaP2PKHstyleaddress.Thehashalsoobfuscatesanypublickeysintheredeemscript,soP2SHscriptsareassecureasP2PKHpubkeyhashes.
AfterthediscoveryofseveraldangerousbugsinearlyversionsofBitcoin,atestwasaddedwhichonlyacceptedtransactionsfromthenetworkiftheirpubkeyscriptsandsignaturescriptsmatchedasmallsetofbelievedtobesafetemplates,andiftherestofthetransactiondidntviolateanothersmallsetofrulesenforcinggoodnetworkbehavior.Thisisthe IsStandard()test,andtransactionswhichpassitarecalledstandardtransactions.
NonstandardtransactionsthosethatfailthetestmaybeacceptedbynodesnotusingthedefaultBitcoinCoresettings.Iftheyareincludedinblocks,theywillalsoavoidtheIsStandardtestandbeprocessed.
BesidesmakingitmoredifficultforsomeonetoattackBitcoinforfreebybroadcastingharmfultransactions,thestandardtransactiontestalsohelpspreventusersfromcreatingtransactionstodaythatwouldmakeaddingnewtransactionfeaturesinthe
StandardTransactions
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 12/55
futuremoredifficult.Forexample,asdescribedabove,eachtransactionincludesaversionnumberifusersstartedarbitrarilychangingtheversionnumber,itwouldbecomeuselessasatoolforintroducingbackwardsincompatiblefeatures.
AsofBitcoinCore0.9,thestandardpubkeyscripttypesare:
P2PKHisthemostcommonformofpubkeyscriptusedtosendatransactiontooneormultipleBitcoinaddresses.
Pubkey script: OP_DUP OP_HASH160 OP_EQUALVERIFY OP_CHECKSIGSignature script:
P2SHisusedtosendatransactiontoascripthash.EachofthestandardpubkeyscriptscanbeusedasaP2SHredeemscript,butinpracticeonlythemultisigpubkeyscriptmakessenseuntilmoretransactiontypesaremadestandard.
Pubkey script: OP_HASH160 OP_EQUALSignature script: [sig] [sig...]
AlthoughP2SHmultisigisnowgenerallyusedformultisigtransactions,thisbasescriptcanbeusedtorequiremultiplesignaturesbeforeaUTXOcanbespent.
Inmultisigpubkeyscripts,calledmofn,mistheminimumnumberofsignatureswhichmustmatchapublickeynisthenumberofpublickeysbeingprovided.Bothmandnshouldbeopcodes OP_1through OP_16,correspondingtothenumberdesired.
BecauseofanoffbyoneerrorintheoriginalBitcoinimplementationwhichmustbepreservedforcompatibility, OP_CHECKMULTISIGconsumesonemorevaluefromthestackthanindicatedbym,sothelistofsecp256k1signaturesinthesignaturescriptmustbeprefacedwithanextravalue( OP_0)whichwillbeconsumedbutnotused.
Thesignaturescriptmustprovidesignaturesinthesameorderasthecorrespondingpublickeysappearinthepubkeyscriptorredeemscript.Seethedesciptionin OP_CHECKMULTISIGfordetails.
Pubkey script: [B pubkey] [C pubkey...] OP_CHECKMULTISIGSignature script: OP_0 [B sig] [C sig...]
Althoughitsnotaseparatetransactiontype,thisisaP2SHmultisigwith2of3:
Pubkey script: OP_HASH160 OP_EQUALRedeem script: OP_CHECKMULTISIGSignature script: OP_0
PayToPublicKeyHash(P2PKH)
PayToScriptHash(P2SH)
Multisig
Pubkey
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 13/55
PubkeyoutputsareasimplifiedformoftheP2PKHpubkeyscript,buttheyarentassecureasP2PKH,sotheygenerallyarentusedinnewtransactionsanymore.
Pubkey script: OP_CHECKSIGSignature script:
Nulldatapubkeyscriptsletyouaddasmallamountofarbitrarydatatotheblockchaininexchangeforpayingatransactionfee,butdoingsoisdiscouraged.(Nulldataisastandardpubkeyscripttypeonlybecausesomepeoplewereaddingdatatotheblockchaininmoreharmfulways.)
Pubkey Script: OP_RETURN (Null data scripts cannot be spent, so there's no signature script.)
Ifyouuseanythingbesidesastandardpubkeyscriptinanoutput,peersandminersusingthedefaultBitcoinCoresettingswillneitheraccept,broadcast,normineyourtransaction.Whenyoutrytobroadcastyourtransactiontoapeerrunningthedefaultsettings,youwillreceiveanerror.
Ifyoucreatearedeemscript,hashit,andusethehashinaP2SHoutput,thenetworkseesonlythehash,soitwillaccepttheoutputasvalidnomatterwhattheredeemscriptsays.Thisallowspaymenttononstandardpubkeyscriptalmostaseasilyaspaymenttostandardpubkeyscripts.However,whenyougotospendthatoutput,peersandminersusingthedefaultsettingswillchecktheredeemscripttoseewhetherornotitsastandardpubkeyscript.Ifitisnt,theywontprocessitfurthersoitwillbeimpossibletospendthatoutputuntilyoufindaminerwhodisablesthedefaultsettings.
Note:standardtransactionsaredesignedtoprotectandhelpthenetwork,notpreventyoufrommakingmistakes.Itseasytocreatestandardtransactionswhichmakethesatoshissenttothemunspendable.
AsofBitcoinCore0.9.3,standardtransactionsmustalsomeetthefollowingconditions:
Thetransactionmustbefinalized:eitheritslocktimemustbeinthepast(orlessthanorequaltothecurrentblockheight),orallofitssequencenumbersmustbe0xffffffff.
Thetransactionmustbesmallerthan100,000bytes.Thatsaround200timeslargerthanatypicalsingleinput,singleoutputP2PKHtransaction.
Eachofthetransactionssignaturescriptsmustbesmallerthan1,650bytes.Thatslargeenoughtoallow15of15multisigtransactionsinP2SHusingcompressedpublickeys.
Bare(nonP2SH)multisigtransactionswhichrequiremorethan3publickeysarecurrentlynonstandard.
Thetransactionssignaturescriptmustonlypushdatatothescriptevaluationstack.ItcannotpushnewOPcodes,withtheexceptionofOPcodeswhichsolelypushdatatothestack.
Thetransactionmustnotincludeanyoutputswhichreceivefewerthan1/3asmanysatoshisasitwouldtaketospenditinatypicalinput.Thatscurrently546satoshisforaP2PKHorP2SHoutputonaBitcoinCorenodewiththedefaultrelayfee.Exception:standardnulldataoutputsmustreceivezerosatoshis.
NullData
NonStandardTransactions
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 14/55
OP_CHECKSIGextractsanonstackargumentfromeachsignatureitevaluates,allowingthesignertodecidewhichpartsofthetransactiontosign.Sincethesignatureprotectsthosepartsofthetransactionfrommodification,thisletssignersselectivelychoosetoletotherpeoplemodifytheirtransactions.
Thevariousoptionsforwhattosignarecalledsignaturehashtypes.TherearethreebaseSIGHASHtypescurrentlyavailable:
SIGHASH_ALL,thedefault,signsalltheinputsandoutputs,protectingeverythingexceptthesignaturescriptsagainstmodification.
SIGHASH_NONEsignsalloftheinputsbutnoneoftheoutputs,allowinganyonetochangewherethesatoshisaregoingunlessothersignaturesusingothersignaturehashflagsprotecttheoutputs.
SIGHASH_SINGLEsignsonlythisinputandonlyonecorrespondingoutput(theoutputwiththesameoutputindexnumberastheinput),ensuringnobodycanchangeyourpartofthetransactionbutallowingothersignerstochangetheirpartofthetransaction.Thecorrespondingoutputmustexistorthevalue1willbesigned,breakingthesecurityscheme.
Thebasetypescanbemodifiedwiththe SIGHASH_ANYONECANPAY(anyonecanpay)flag,creatingthreenewcombinedtypes:
SIGHASH_ALL|SIGHASH_ANYONECANPAYsignsalloftheoutputsbutonlythisoneinput,anditalsoallowsanyonetoaddorremoveotherinputs,soanyonecancontributeadditionalsatoshisbuttheycannotchangehowmanysatoshisaresentnorwheretheygo.
SIGHASH_NONE|SIGHASH_ANYONECANPAYsignsonlythisoneinputandallowsanyonetoaddorremoveotherinputsoroutputs,soanyonewhogetsacopyofthisinputcanspendithowevertheydlike.
SIGHASH_SINGLE|SIGHASH_ANYONECANPAYsignsonlythisinputandonlyonecorrespondingoutput,butitalsoallowsanyonetoaddorremoveotherinputs.
Becauseeachinputissigned,atransactionwithmultipleinputscanhavemultiplesignaturehashtypessigningdifferentpartsofthetransaction.Forexample,asingleinputtransactionsignedwith NONEcouldhaveitsoutputchangedbytheminerwhoaddsittotheblockchain.Ontheotherhand,ifatwoinputtransactionhasoneinputsignedwith NONEandoneinputsignedwith ALL,the ALLsignercanchoosewheretospendthesatoshiswithoutconsultingthe NONEsignerbutnobodyelsecanmodifythetransaction.
Onethingallsignaturehashtypessignisthetransactionslocktime.(CallednLockTimeintheBitcoinCoresourcecode.)Thelocktimeindicatestheearliesttimeatransactioncanbeaddedtotheblockchain.
Locktimeallowssignerstocreatetimelockedtransactionswhichwillonlybecomevalidinthefuture,givingthesignersachancetochangetheirminds.
Ifanyofthesignerschangetheirmind,theycancreateanewnonlocktimetransaction.Thenewtransactionwilluse,asoneofitsinputs,oneofthesameoutputswhichwasusedasaninputtothelocktimetransaction.Thismakesthelocktimetransactioninvalidifthenewtransactionisaddedtotheblockchainbeforethetimelockexpires.
Caremustbetakenneartheexpirytimeofatimelock.Thepeertopeernetworkallowsblocktimetobeuptotwohoursaheadofrealtime,soalocktimetransactioncanbeaddedtotheblockchainuptotwohoursbeforeitstimelockofficiallyexpires.Also,blocksarenotcreatedatguaranteedintervals,soanyattempttocancelavaluabletransactionshouldbemadeafewhoursbeforethetimelockexpires.
PreviousversionsofBitcoinCoreprovidedafeaturewhichpreventedtransactionsignersfromusingthemethoddescribedabove
SignatureHashTypes
LocktimeAndSequenceNumber
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 15/55
tocancelatimelockedtransaction,butanecessarypartofthisfeaturewasdisabledtopreventdenialofserviceattacks.Alegacyofthissystemarefourbytesequencenumbersineveryinput.Sequencenumbersweremeanttoallowmultiplesignerstoagreetoupdateatransactionwhentheyfinishedupdatingthetransaction,theycouldagreetoseteveryinputssequencenumbertothefourbyteunsignedmaximum(0xffffffff),allowingthetransactiontobeaddedtoablockevenifitstimelockhadnotexpired.
Eventoday,settingallsequencenumbersto0xffffffff(thedefaultinBitcoinCore)canstilldisablethetimelock,soifyouwanttouselocktime,atleastoneinputmusthaveasequencenumberbelowthemaximum.Sincesequencenumbersarenotusedbythenetworkforanyotherpurpose,settinganysequencenumbertozeroissufficienttoenablelocktime.
Locktimeitselfisanunsigned4byteintegerwhichcanbeparsedtwoways:
Iflessthan500million,locktimeisparsedasablockheight.Thetransactioncanbeaddedtoanyblockwhichhasthisheightorhigher.
Ifgreaterthanorequalto500million,locktimeisparsedusingtheUnixepochtimeformat(thenumberofsecondselapsedsince19700101T00:00UTCcurrentlyover1.395billion).Thetransactioncanbeaddedtoanyblockwhoseblocktimeisgreaterthanthelocktime.
Transactionstypicallypaytransactionfeesbasedonthetotalbytesizeofthesignedtransaction.ThetransactionfeeisgiventotheBitcoinminer,asexplainedintheblockchainsection,andsoitisultimatelyuptoeachminertochoosetheminimumtransactionfeetheywillaccept.
Bydefault,minersreserve50KBofeachblockforhighprioritytransactionswhichspendsatoshisthathaventbeenspentforalongtime.Theremainingspaceineachblockistypicallyallocatedtotransactionsbasedontheirfeeperbyte,withhigherpayingtransactionsbeingaddedinsequenceuntilalloftheavailablespaceisfilled.
AsofBitcoinCore0.9,transactionswhichdonotcountashighprioritytransactionsneedtopayaminimumfee(currently1,000satoshis)tobebroadcastacrossthenetwork.Anytransactionpayingonlytheminimumfeeshouldbepreparedtowaitalongtimebeforetheresenoughsparespaceinablocktoincludeit.Pleaseseetheverifyingpaymentsectionforwhythiscouldbeimportant.
SinceeachtransactionspendsUnspentTransactionOutputs(UTXOs)andbecauseaUTXOcanonlybespentonce,thefullvalueoftheincludedUTXOsmustbespentorgiventoaminerasatransactionfee.FewpeoplewillhaveUTXOsthatexactlymatchtheamounttheywanttopay,somosttransactionsincludeachangeoutput.
ChangeoutputsareregularoutputswhichspendthesurplussatoshisfromtheUTXOsbacktothespender.TheycanreusethesameP2PKHpubkeyhashorP2SHscripthashaswasusedintheUTXO,butforthereasonsdescribedinthenextsubsection,itishighlyrecommendedthatchangeoutputsbesenttoanewP2PKHorP2SHaddress.
Inatransaction,thespenderandreceivereachrevealtoeachotherallpublickeysoraddressesusedinthetransaction.Thisallowseitherpersontousethepublicblockchaintotrackpastandfuturetransactionsinvolvingtheotherpersonssamepublickeysoraddresses.
Ifthesamepublickeyisreusedoften,ashappenswhenpeopleuseBitcoinaddresses(hashedpublickeys)asstaticpaymentaddresses,otherpeoplecaneasilytrackthereceivingandspendinghabitsofthatperson,includinghowmanysatoshistheycontrolinknownaddresses.
Itdoesnthavetobethatway.Ifeachpublickeyisusedexactlytwiceoncetoreceiveapaymentandoncetospendthatpayment
TransactionFeesAndChange
AvoidingKeyReuse
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 16/55
theusercangainasignificantamountoffinancialprivacy.
Evenbetter,usingnewpublickeysoruniqueaddresseswhenacceptingpaymentsorcreatingchangeoutputscanbecombinedwithothertechniquesdiscussedlater,suchasCoinJoinormergeavoidance,tomakeitextremelydifficulttousetheblockchainbyitselftoreliablytrackhowusersreceiveandspendtheirsatoshis.
Avoidingkeyreusecanalsoprovidesecurityagainstattackswhichmightallowreconstructionofprivatekeysfrompublickeys(hypothesized)orfromsignaturecomparisons(possibletodayundercertaincircumstancesdescribedbelow,withmoregeneralattackshypothesized).
1. Unique(nonreused)P2PKHandP2SHaddressesprotectagainstthefirsttypeofattackbykeepingECDSApublickeyshidden(hashed)untilthefirsttimesatoshissenttothoseaddressesarespent,soattacksareeffectivelyuselessunlesstheycanreconstructprivatekeysinlessthanthehourortwoittakesforatransactiontobewellprotectedbytheblockchain.
2. Unique(nonreused)privatekeysprotectagainstthesecondtypeofattackbyonlygeneratingonesignatureperprivatekey,soattackersnevergetasubsequentsignaturetouseincomparisonbasedattacks.Existingcomparisonbasedattacksareonlypracticaltodaywheninsufficiententropyisusedinsigningorwhentheentropyusedisexposedbysomemeans,suchasasidechannelattack.
So,forbothprivacyandsecurity,weencourageyoutobuildyourapplicationstoavoidpublickeyreuseand,whenpossible,todiscourageusersfromreusingaddresses.IfyourapplicationneedstoprovideafixedURItowhichpaymentsshouldbesent,pleaseseethe bitcoin:URIsectionbelow.
NoneofBitcoinssignaturehashtypesprotectthesignaturescript,leavingthedooropenforalimiteddenialofserviceattackcalledtransactionmalleability.Thesignaturescriptcontainsthesecp256k1signature,whichcantsignitself,allowingattackerstomakenonfunctionalmodificationstoatransactionwithoutrenderingitinvalid.Forexample,anattackercanaddsomedatatothesignaturescriptwhichwillbedroppedbeforethepreviouspubkeyscriptisprocessed.
Althoughthemodificationsarenonfunctionalsotheydonotchangewhatinputsthetransactionusesnorwhatoutputsitpaystheydochangethecomputedhashofthetransaction.Sinceeachtransactionlinkstoprevioustransactionsusinghashesasatransactionidentifier(txid),amodifiedtransactionwillnothavethetxiditscreatorexpected.
ThisisntaproblemformostBitcointransactionswhicharedesignedtobeaddedtotheblockchainimmediately.Butitdoesbecomeaproblemwhentheoutputfromatransactionisspentbeforethattransactionisaddedtotheblockchain.
Bitcoindevelopershavebeenworkingtoreducetransactionmalleabilityamongstandardtransactiontypes,butacompletefixisstillonlyintheplanningstages.Atpresent,newtransactionsshouldnotdependonprevioustransactionswhichhavenotbeenaddedtotheblockchainyet,especiallyiflargeamountsofsatoshisareatstake.
Transactionmalleabilityalsoaffectspaymenttracking.BitcoinCoresRPCinterfaceletsyoutracktransactionsbytheirtxidbutifthattxidchangesbecausethetransactionwasmodified,itmayappearthatthetransactionhasdisappearedfromthenetwork.
Currentbestpracticesfortransactiontrackingdictatethatatransactionshouldbetrackedbythetransactionoutputs(UTXOs)itspendsasinputs,astheycannotbechangedwithoutinvalidatingthetransaction.
Bestpracticesfurtherdictatethatifatransactiondoesseemtodisappearfromthenetworkandneedstobereissued,thatitbereissuedinawaythatinvalidatesthelosttransaction.Onemethodwhichwillalwaysworkistoensurethereissuedpaymentspendsallofthesameoutputsthatthelosttransactionusedasinputs.
TransactionMalleability
Contracts
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 17/55
ContractsaretransactionswhichusethedecentralizedBitcoinsystemtoenforcefinancialagreements.Bitcoincontractscanoftenbecraftedtominimizedependencyonoutsideagents,suchasthecourtsystem,whichsignificantlydecreasestheriskofdealingwithunknownentitiesinfinancialtransactions.
ThefollowingsubsectionswilldescribeavarietyofBitcoincontractsalreadyinuse.Becausecontractsdealwithrealpeople,notjusttransactions,theyareframedbelowinstoryformat.
Besidesthecontracttypesdescribedbelow,manyothercontracttypeshavebeenproposed.SeveralofthemarecollectedontheContractspageoftheBitcoinWiki.
CharliethecustomerwantstobuyaproductfromBobthebusinessman,butneitherofthemtruststheotherperson,sotheyuseacontracttohelpensureCharliegetshismerchandiseandBobgetshispayment.
AsimplecontractcouldsaythatCharliewillspendsatoshistoanoutputwhichcanonlybespentifCharlieandBobbothsigntheinputspendingit.ThatmeansBobwontgetpaidunlessCharliegetshismerchandise,butCharliecantgetthemerchandiseandkeephispayment.
Thissimplecontractisntmuchhelpiftheresadispute,soBobandCharlieenlistthehelpofAlicethearbitratortocreateanescrowcontract.Charliespendshissatoshistoanoutputwhichcanonlybespentiftwoofthethreepeoplesigntheinput.NowCharliecanpayBobifeverythingisok,BobcanrefundCharliesmoneyiftheresaproblem,orAlicecanarbitrateanddecidewhoshouldgetthesatoshisiftheresadispute.
Tocreateamultiplesignature(multisig)output,theyeachgivetheothersapublickey.ThenBobcreatesthefollowingP2SHmultisigredeemscript:
OP_2 [A's pubkey] [B's pubkey] [C's pubkey] OP_3 OP_CHECKMULTISIG
(Opcodestopushthepublickeysontothestackarenotshown.)
OP_2and OP_3pushtheactualnumbers2and3ontothestack. OP_2specifiesthat2signaturesarerequiredtosign OP_3specifiesthat3publickeys(unhashed)arebeingprovided.Thisisa2of3multisigpubkeyscript,moregenericallycalledamofnpubkeyscript(wheremistheminimummatchingsignaturesrequiredandninthenumberofpublickeysprovided).
BobgivestheredeemscripttoCharlie,whocheckstomakesurehispublickeyandAlicespublickeyareincluded.ThenhehashestheredeemscripttocreateaP2SHredeemscriptandpaysthesatoshistoit.Bobseesthepaymentgetaddedtotheblockchainandshipsthemerchandise.
Unfortunately,themerchandisegetsslightlydamagedintransit.Charliewantsafullrefund,butBobthinksa10%refundissufficient.TheyturntoAlicetoresolvetheissue.AliceasksforphotoevidencefromCharliealongwithacopyoftheredeemscriptBobcreatedandCharliechecked.
Afterlookingattheevidence,Alicethinksa40%refundissufficient,soshecreatesandsignsatransactionwithtwooutputs,onethatspends60%ofthesatoshistoBobspublickeyandonethatspendstheremaining40%toCharliespublickey.
InthesignaturescriptAliceputshersignatureandacopyoftheunhashedserializedredeemscriptthatBobcreated.ShegivesacopyoftheincompletetransactiontobothBobandCharlie.Eitheroneofthemcancompleteitbyaddinghissignaturetocreatethefollowingsignaturescript:
OP_0 [A's signature] [B's or C's signature] [serialized redeem script]
EscrowAndArbitration
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 18/55
(Opcodestopushthesignaturesandredeemscriptontothestackarenotshown. OP_0isaworkaroundforanoffbyoneerrorintheoriginalimplementationwhichmustbepreservedforcompatibility.Notethatthesignaturescriptmustprovidesignaturesinthesameorderasthecorrespondingpublickeysappearintheredeemscript.Seethedescriptionin OP_CHECKMULTISIGfordetails.)
Whenthetransactionisbroadcasttothenetwork,eachpeerchecksthesignaturescriptagainsttheP2SHoutputCharliepreviouslypaid,ensuringthattheredeemscriptmatchestheredeemscripthashpreviouslyprovided.Thentheredeemscriptisevaluated,withthetwosignaturesbeingusedasinputdata.Assumingtheredeemscriptvalidates,thetwotransactionoutputsshowupinBobsandCharlieswalletsasspendablebalances.
However,ifAlicecreatedandsignedatransactionneitherofthemwouldagreeto,suchasspendingallthesatoshistoherself,BobandCharliecanfindanewarbitratorandsignatransactionspendingthesatoshistoanother2of3multisigredeemscripthash,thisoneincludingapublickeyfromthatsecondarbitrator.ThismeansthatBobandCharlieneverneedtoworryabouttheirarbitratorstealingtheirmoney.
Resource:BitRatedprovidesamultisigarbitrationserviceinterfaceusingHTML/JavaScriptonaGNUAGPLlicensedwebsite.
AlicealsoworksparttimemoderatingforumpostsforBob.EverytimesomeonepoststoBobsbusyforum,Aliceskimstheposttomakesureitisntoffensiveorspam.Alas,Boboftenforgetstopayher,soAlicedemandstobepaidimmediatelyaftereachpostsheapprovesorrejects.Bobsayshecantdothatbecausehundredsofsmallpaymentswillcosthimthousandsofsatoshisintransactionfees,soAlicesuggeststheyuseamicropaymentchannel.
BobasksAliceforherpublickeyandthencreatestwotransactions.Thefirsttransactionpays100millibitcoinstoaP2SHoutputwhose2of2multisigredeemscriptrequiressignaturesfrombothAliceandBob.Thisisthebondtransaction.BroadcastingthistransactionwouldletAliceholdthemillibitcoinshostage,soBobkeepsthistransactionprivatefornowandcreatesasecondtransaction.
Thesecondtransactionspendsallofthefirsttransactionsmillibitcoins(minusatransactionfee)backtoBobaftera24hourdelayenforcedbylocktime.Thisistherefundtransaction.Bobcantsigntherefundtransactionbyhimself,sohegivesittoAlicetosign,asshownintheillustrationbelow.
MicropaymentChannel
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 19/55
Alice broadcasts the bond to the Bitcoin network immediately.She broadcasts the final version of the refund when she finishes work
or before the locktime. If she fails to broadcast before refund v1's time lockexpires, Bob can broadcast refund v1 to get a full refund.
Bitcoin Micropayment Channels (As Implemented In Bitcoinj)
Alice's Computer(Server)
Bob's Computer(Client)
A: Signed; please send me the bond toprove you funded the account
Bond(2-of-2
multisig)
A: Some work done; please sign refund v2reducing your refund by 1 mBTC
A: More work done; please sign v3reducing your refund by another 1 mBTC
A: [...]Refund v45
Bob: 66Alice: 44(No Lock) A: I'm done for the day. I'm
going to broadcast refund v45
Refund v1Bob: 100Alice: 0
(Locktime)
B: Please sign refund version 1,which is a full refund of the bondthat can't be spent for 24 hours
B: Here's the bond; please start working
B: Signed; refund now pays Bob: 99; Alice: 1
B: Signed; refund now pays Bob: 98; Alice: 2
B: [...]
Alicechecksthattherefundtransactionslocktimeis24hoursinthefuture,signsit,andgivesacopyofitbacktoBob.ShethenasksBobforthebondtransactionandchecksthattherefundtransactionspendstheoutputofthebondtransaction.ShecannowbroadcastthebondtransactiontothenetworktoensureBobhastowaitforthetimelocktoexpirebeforefurtherspendinghismillibitcoins.Bobhasntactuallyspentanythingsofar,exceptpossiblyasmalltransactionfee,andhellbeabletobroadcasttherefundtransactionin24hoursforafullrefund.
Now,whenAlicedoessomeworkworth1millibitcoin,sheasksBobtocreateandsignanewversionoftherefundtransaction.Versiontwoofthetransactionspends1millibitcointoAliceandtheother99backtoBobitdoesnothavealocktime,soAlicecansignitandspenditwhenevershewants.(Butshedoesntdothatimmediately.)
AliceandBobrepeattheseworkandpaystepsuntilAlicefinishesfortheday,oruntilthetimelockisabouttoexpire.Alicesignsthefinalversionoftherefundtransactionandbroadcastsit,payingherselfandrefundinganyremainingbalancetoBob.Thenextday,whenAlicestartswork,theycreateanewmicropaymentchannel.
IfAlicefailstobroadcastaversionoftherefundtransactionbeforeitstimelockexpires,Bobcanbroadcastthefirstversionandreceiveafullrefund.ThisisonereasonmicropaymentchannelsarebestsuitedtosmallpaymentsifAlicesInternetservicegoesoutforafewhoursnearthetimelockexpiry,shecouldbecheatedoutofherpayment.
Transactionmalleability,discussedaboveintheTransactionssection,isanotherreasontolimitthevalueofmicropaymentchannels.Ifsomeoneusestransactionmalleabilitytobreakthelinkbetweenthetwotransactions,AlicecouldholdBobs100millibitcoinshostageevenifshehadntdoneanywork.
Forlargerpayments,Bitcointransactionfeesareverylowasapercentageofthetotaltransactionvalue,soitmakesmoresensetoprotectpaymentswithimmediatelybroadcastseparatetransactions.
Resource:ThebitcoinjJavalibraryprovidesacompletesetofmicropaymentfunctions,anexampleimplementation,andatutorialallunderanApachelicense.
CoinJoin
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 20/55
Aliceisconcernedaboutherprivacy.Sheknowseverytransactiongetsaddedtothepublicblockchain,sowhenBobandCharliepayher,theycaneacheasilytrackthosesatoshistolearnwhatBitcoinaddressesshepays,howmuchshepaysthem,andpossiblyhowmanysatoshisshehasleft.
Aliceisntacriminal,shejustwantsplausibledeniabilityaboutwhereshehasspenthersatoshisandhowmanyshehasleft,soshestartsuptheToranonymityserviceonhercomputerandlogsintoanIRCchatroomasAnonGirl.
AlsointhechatroomareNemoandNeminem.Theycollectivelyagreetotransfersatoshisbetweeneachothersonoonebesidesthemcanreliablydeterminewhocontrolswhichsatoshis.Buttheyrefacedwithadilemma:whotransferstheirsatoshistooneoftheothertwopseudonymouspersonsfirst?TheCoinJoinstylecontract,shownintheillustrationbelow,makesthisdecisioneasy:theycreateasingletransactionwhichdoesallofthespendingsimultaneously,ensuringnoneofthemcanstealtheotherssatoshis.
Example CoinJoin TransactionOnly the participants know who gets which output.
Nemo's UTXOs
Neminem's UTXOs
AnonGirl's UTXOs
CoinJoin Transaction
Inputs
Outputs
10 mBTC
90 mBTC
100 mBTC
55 mBTC
25 mBTC
20 mBTC
From Bob
From Charlie
100 mBTC Person 1
100 mBTC Person 2
100 mBTC Person 3
EachcontributorlooksthroughtheircollectionofUnspentTransactionOutputs(UTXOs)for100millibitcoinstheycanspend.TheytheneachgenerateabrandnewpublickeyandgiveUTXOdetailsandpubkeyhashestothefacilitator.Inthiscase,thefacilitatorisAnonGirlshecreatesatransactionspendingeachoftheUTXOstothreeequallysizedoutputs.Oneoutputgoestoeachofthecontributorspubkeyhashes.
AnonGirlthensignsherinputsusing SIGHASH_ALLtoensurenobodycanchangetheinputoroutputdetails.ShegivesthepartiallysignedtransactiontoNemowhosignshisinputsthesamewayandpassesittoNeminem,whoalsosignsitthesameway.Neminemthenbroadcaststhetransactiontothepeertopeernetwork,mixingallofthemillibitcoinsinasingletransaction.
Asyoucanseeintheillustration,theresnowayforanyonebesidesAnonGirl,Nemo,andNeminemtoconfidentlydeterminewhoreceivedwhichoutput,sotheycaneachspendtheiroutputwithplausibledeniability.
NowwhenBoborCharlietrytotrackAlicestransactionsthroughtheblockchain,theyllalsoseetransactionsmadebyNemoand
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 21/55
Neminem.IfAlicedoesafewmoreCoinJoins,BobandCharliemighthavetoguesswhichtransactionsmadebydozensorhundredsofpeoplewereactuallymadebyAlice.
ThecompletehistoryofAlicessatoshisisstillintheblockchain,soadeterminedinvestigatorcouldtalktothepeopleAnonGirlCoinJoinedwithtofindouttheultimateoriginofhersatoshisandpossiblyrevealAnonGirlasAlice.Butagainstanyonecasuallybrowsingblockchainhistory,Alicegainsplausibledeniability.
TheCoinJointechniquedescribedabovecoststheparticipantsasmallamountofsatoshistopaythetransactionfee.Analternativetechnique,purchaserCoinJoin,canactuallysavethemsatoshisandimprovetheirprivacyatthesametime.
AnonGirlwaitsintheIRCchatroomuntilshewantstomakeapurchase.Sheannouncesherintentiontospendsatoshisandwaitsuntilsomeoneelsewantstomakeapurchase,likelyfromadifferentmerchant.Thentheycombinetheirinputsthesamewayasbeforebutsettheoutputstotheseparatemerchantaddressessonobodywillbeabletofigureoutsolelyfromblockchainhistorywhichoneofthemboughtwhatfromthemerchants.
Sincetheywouldvehadtopayatransactionfeetomaketheirpurchasesanyway,AnonGirlandhercospendersdontpayanythingextrabutbecausetheyreducedoverheadbycombiningmultipletransactions,savingbytes,theymaybeabletopayasmalleraggregatetransactionfee,savingeachoneofthematinyamountofsatoshis.
Resource:Analphaquality(asofthiswriting)implementationofdecentralizedCoinJoinisCoinMux,availableundertheApachelicense.
ABitcoinwalletcanrefertoeitherawalletprogramorawalletfile.Walletprogramscreatepublickeystoreceivesatoshisandusethecorrespondingprivatekeystospendthosesatoshis.Walletfilesstoreprivatekeysand(optionally)otherinformationrelatedtotransactionsforthewalletprogram.
Walletprogramsandwalletfilesareaddressedbelowinseparatesubsections,andthisdocumentattemptstoalwaysmakeitclearwhetherweretalkingaboutwalletprogramsorwalletfiles.
Permittingreceivingandspendingofsatoshisistheonlyessentialfeatureofwalletsoftwarebutaparticularwalletprogramdoesntneedtodoboththings.Twowalletprogramscanworktogether,oneprogramdistributingpublickeysinordertoreceivesatoshisandanotherprogramsigningtransactionsspendingthosesatoshis.
Walletprogramsalsoneedtointeractwiththepeertopeernetworktogetinformationfromtheblockchainandtobroadcastnewtransactions.However,theprogramswhichdistributepublickeysorsigntransactionsdontneedtointeractwiththepeertopeernetworkthemselves.
Thisleavesuswiththreenecessary,butseparable,partsofawalletsystem:apublickeydistributionprogram,asigningprogram,andanetworkedprogram.Inthesubsectionsbelow,wewilldescribecommoncombinationsoftheseparts.
Note:wespeakaboutdistributingpublickeysgenerically.Inmanycases,P2PKHorP2SHhasheswillbedistributedinsteadofpublickeys,withtheactualpublickeysonlybeingdistributedwhentheoutputstheycontrolarespent.
Thesimplestwalletisaprogramwhichperformsallthreefunctions:itgeneratesprivatekeys,derivesthecorrespondingpublic
Wallets
WalletPrograms
FullServiceWallets
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 22/55
keys,helpsdistributethosepublickeysasnecessary,monitorsforoutputsspenttothosepublickeys,createsandsignstransactionsspendingthoseoutputs,andbroadcaststhesignedtransactions.
Full-Service Wallet
CreatePrivateKeys
DerivePublicKeys
DistributePublicKeys
MonitorFor
Outputs
CreateUnsigned
TxesSignTxes
BroadcastTxes
Asofthiswriting,almostallpopularwalletscanbeusedasfullservicewallets.
Themainadvantageoffullservicewalletsisthattheyareeasytouse.Asingleprogramdoeseverythingtheuserneedstoreceiveandspendsatoshis.
ThemaindisadvantageoffullservicewalletsisthattheystoretheprivatekeysonadeviceconnectedtotheInternet.Thecompromiseofsuchdevicesisacommonoccurrence,andanInternetconnectionmakesiteasytotransmitprivatekeysfromacompromiseddevicetoanattacker.
Tohelpprotectagainsttheft,manywalletprogramsofferuserstheoptionofencryptingthewalletfileswhichcontaintheprivatekeys.Thisprotectstheprivatekeyswhentheyarentbeingused,butitcannotprotectagainstanattackdesignedtocapturetheencryptionkeyortoreadthedecryptedkeysfrommemory.
Toincreasesecurity,privatekeyscanbegeneratedandstoredbyaseparatewalletprogramoperatinginamoresecureenvironment.Thesesigningonlywalletsworkinconjunctionwithanetworkedwalletwhichinteractswiththepeertopeernetwork.
Signingonlywalletsprogramstypicallyusedeterministickeycreation(describedinalatersubsection)tocreateparentprivateandpublickeyswhichcancreatechildprivateandpublickeys.
Signing-Only Wallet
Networked Wallet
CreateParentPrivate
Key
DeriveParentPublicKey
DeriveChildPublicKeys
SignTxes
BroadcastTxes
DistributePublicKeys
MonitorFor
Outputs
CreateUnsigned
Txes
Whenfirstrun,thesigningonlywalletcreatesaparentprivatekeyandtransfersthecorrespondingparentpublickeytothenetworkedwallet.
Thenetworkedwalletusestheparentpublickeytoderivechildpublickeys,optionallyhelpsdistributethem,monitorsforoutputsspenttothosepublickeys,createsunsignedtransactionsspendingthoseoutputs,andtransferstheunsignedtransactionstothesigningonlywallet.
Often,usersaregivenachancetoreviewtheunsignedtransactionsdetails(particularlytheoutputdetails)usingthesigningonlywallet.
Aftertheoptionalreviewstep,thesigningonlywalletusestheparentprivatekeytoderivetheappropriatechildprivatekeysandsignsthetransactions,givingthesignedtransactionsbacktothenetworkedwallet.
SigningOnlyWallets
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 23/55
Thenetworkedwalletthenbroadcaststhesignedtransactionstothepeertopeernetwork.
Thefollowingsubsectionsdescribethetwomostcommonvariantsofsigningonlywallets:offlinewalletsandhardwarewallets.
Severalfullservicewalletsprogramswillalsooperateastwoseparatewallets:oneprograminstanceactingasasigningonlywallet(oftencalledanofflinewallet)andtheotherprograminstanceactingasthenetworkedwallet(oftencalledanonlinewalletorwatchingonlywallet).
Theofflinewalletissonamedbecauseitisintendedtoberunonadevicewhichdoesnotconnecttoanynetwork,greatlyreducingthenumberofattackvectors.Ifthisisthecase,itisusuallyuptotheusertohandlealldatatransferusingremovablemediasuchasUSBdrives.Theusersworkflowissomethinglike:
1. (Offline)Disableallnetworkconnectionsonadeviceandinstallthewalletsoftware.Startthewalletsoftwareinofflinemodetocreatetheparentprivateandpublickeys.Copytheparentpublickeytoremovablemedia.
2. (Online)Installthewalletsoftwareonanotherdevice,thisoneconnectedtotheInternet,andimporttheparentpublickeyfromtheremovablemedia.Asyouwouldwithafullservicewallet,distributepublickeystoreceivepayment.Whenreadytospendsatoshis,fillintheoutputdetailsandsavetheunsignedtransactiongeneratedbythewallettoremovablemedia.
3. (Offline)Opentheunsignedtransactionintheofflineinstance,reviewtheoutputdetailstomakesuretheyspendthecorrectamounttothecorrectaddress.Thispreventsmalwareontheonlinewalletfromtrickingtheuserintosigningatransactionwhichpaysanattacker.Afterreview,signthetransactionandsaveittoremovablemedia.
4. (Online)Openthesignedtransactionintheonlineinstancesoitcanbroadcastittothepeertopeernetwork.
Theprimaryadvantageofofflinewalletsistheirpossibilityforgreatlyimprovedsecurityoverfullservicewallets.Aslongastheofflinewalletisnotcompromised(orflawed)andtheuserreviewsalloutgoingtransactionsbeforesigning,theuserssatoshisaresafeeveniftheonlinewalletiscompromised.
Theprimarydisadvantageofofflinewalletsishassle.Formaximumsecurity,theyrequiretheuserdedicateadevicetoonlyofflinetasks.Theofflinedevicemustbebootedupwheneverfundsaretobespent,andtheusermustphysicallycopydatafromtheonlinedevicetotheofflinedeviceandback.
Hardwarewalletsaredevicesdedicatedtorunningasigningonlywallet.Theirdedicationletsthemeliminatemanyofthevulnerabilitiespresentinoperatingsystemsdesignedforgeneraluse,allowingthemtosafelycommunicatedirectlywithotherdevicessousersdontneedtotransferdatamanually.Theusersworkflowissomethinglike:
1. (Hardware)Createparentprivateandpublickeys.Connecthardwarewallettoanetworkeddevicesoitcangettheparentpublickey.
2. (Networked)Asyouwouldwithafullservicewallet,distributepublickeystoreceivepayment.Whenreadytospendsatoshis,fillinthetransactiondetails,connectthehardwarewallet,andclickSpend.Thenetworkedwalletwillautomaticallysendthetransactiondetailstothehardwarewallet.
3. (Hardware)Reviewthetransactiondetailsonthehardwarewalletsscreen.SomehardwarewalletsmaypromptforapassphraseorPINnumber.Thehardwarewalletsignsthetransactionanduploadsittothenetworkedwallet.
4. (Networked)Thenetworkedwalletreceivesthesignedtransactionfromthehardwarewalletandbroadcastsittothenetwork.
OfflineWallets
HardwareWallets
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 24/55
Theprimaryadvantageofhardwarewalletsistheirpossibilityforgreatlyimprovedsecurityoverfullservicewalletswithmuchlesshasslethanofflinewallets.
Theprimarydisadvantageofhardwarewalletsistheirhassle.Eventhoughthehassleislessthanthatofofflinewallets,theusermuststillpurchaseahardwarewalletdeviceandcarryitwiththemwhenevertheyneedtomakeatransactionusingthesigningonlywallet.
Anadditional(hopefullytemporary)disadvantageisthat,asofthiswriting,veryfewpopularwalletprogramssupporthardwarewalletsalthoughalmostallpopularwalletprogramshaveannouncedtheirintentiontosupportatleastonemodelofhardwarewallet.
Walletprogramswhichrunindifficulttosecureenvironments,suchaswebservers,canbedesignedtodistributepublickeys(includingP2PKHorP2SHaddresses)andnothingmore.Therearetwocommonwaystodesigntheseminimalistwallets:
Distributing-Only Wallet
Other Wallet(s)
DeriveChildPublicKeys
DistributePublicKeys
MonitorFor
Outputs
CreateParentPrivate
Key
DeriveParentPublicKey
CreateUnsigned
TxesSignTxes
BroadcastTxes
Prepopulateadatabasewithanumberofpublickeysoraddresses,andthendistributeonrequestapubkeyscriptoraddressusingoneofthedatabaseentries.Toavoidkeyreuse,webserversshouldkeeptrackofusedkeysandneverrunoutofpublickeys.Thiscanbemadeeasierbyusingparentpublickeysassuggestedinthenextmethod.
Useaparentpublickeytocreatechildpublickeys.Toavoidkeyreuse,amethodmustbeusedtoensurethesamepublickeyisntdistributedtwice.Thiscanbeadatabaseentryforeachkeydistributedoranincrementingpointertothekeyindexnumber.
Neithermethodaddsasignificantamountofoverhead,especiallyifadatabaseisusedanywaytoassociateeachincomingpaymentwithaseparatepublickeyforpaymenttracking.SeethePaymentProcessingsectionfordetails.
Bitcoinwalletsattheircoreareacollectionofprivatekeys.Thesecollectionsarestoreddigitallyinafile,orcanevenbephysicallystoredonpiecesofpaper.
Privatekeysarewhatareusedtounlocksatoshisfromaparticularaddress.InBitcoin,aprivatekeyinstandardformatissimplya256bitnumber,betweenthevalues:
0x01and0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140,representingnearlytheentirerangeof2 1values.Therangeisgovernedbythesecp256k1ECDSAencryptionstandardusedbyBitcoin.
DistributingOnlyWallets
WalletFiles
PrivateKeyFormats
256
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 25/55
Inordertomakecopyingofprivatekeyslesspronetoerror,WalletImportFormatmaybeutilized.WIFusesbase58Checkencodingonanprivatekey,greatlydecreasingthechanceofcopyingerror,muchlikestandardBitcoinaddresses.
1. Takeaprivatekey.
2. Adda0x80byteinfrontofitformainnetaddressesor0xeffortestnetaddresses.
3. Appenda0x01byteafteritifitshouldbeusedwithcompressedpublickeys(describedinalatersubsection).Nothingisappendedifitisusedwithuncompressedpublickeys.
4. PerformaSHA256hashontheextendedkey.
5. PerformaSHA256hashonresultofSHA256hash.
6. TakethefirstfourbytesofthesecondSHA256hashthisisthechecksum.
7. Addthefourchecksumbytesfrompoint5attheendoftheextendedkeyfrompoint2.
8. ConverttheresultfromabytestringintoaBase58stringusingBase58Checkencoding.
Theprocessiseasilyreversible,usingtheBase58decodingfunction,andremovingthepadding.
Miniprivatekeyformatisamethodforencodingaprivatekeyinunder30characters,enablingkeystobeembeddedinasmallphysicalspace,suchasphysicalbitcointokens,andmoredamageresistantQRcodes.
1. ThefirstcharacterofminikeysisS.
2. Inordertodetermineifaminiprivatekeyiswellformatted,aquestionmarkisaddedtotheprivatekey.
3. TheSHA256hashiscalculated.Ifthefirstbyteproducedisa`00,itiswellformatted.Thiskeyrestrictionactsasatypocheckingmechanism.Auserbruteforcestheprocessusingrandomnumbersuntilawellformattedminiprivatekeyisproduced.
4. Inordertoderivethefullprivatekey,theusersimplytakesasingleSHA256hashoftheoriginalminiprivatekey.Thisprocessisoneway:itisintractabletocomputetheminiprivatekeyformatfromthederivedkey.
Manyimplementationsdisallowthecharacter1intheminiprivatekeyduetoitsvisualsimilaritytol.
Resource:AcommontooltocreateandredeemthesekeysistheCasasciusBitcoinAddressUtility.
BitcoinECDSApublickeysrepresentapointonaparticularEllipticCurve(EC)definedinsecp256k1.Intheirtraditionaluncompressedform,publickeyscontainanidentificationbyte,a32byteXcoordinate,anda32byteYcoordinate.TheextremelysimplifiedillustrationbelowshowssuchapointontheellipticcurveusedbyBitcoin,x =y +7,overafieldofcontiguousnumbers.
WalletImportFormat(WIF)
MiniPrivateKeyFormat
PublicKeyFormats
2 3
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 26/55
-4-3-2-101234
-2 0 2 4 6 8
sqrt(x**3+7)-sqrt(x**3+7)x,y=1.00,2.83
(Secp256k1actuallymoduloscoordinatesbyalargeprime,whichproducesafieldofnoncontiguousintegersandasignificantlylessclearplot,althoughtheprinciplesarethesame.)
Analmost50%reductioninpublickeysizecanberealizedwithoutchanginganyfundamentalsbydroppingtheYcoordinate.ThisispossiblebecauseonlytwopointsalongthecurveshareanyparticularXcoordinate,sothe32byteYcoordinatecanbereplacedwithasinglebitindicatingwhetherthepointisonwhatappearsintheillustrationasthetopsideorthebottomside.
NodataislostbycreatingthesecompressedpublickeysonlyasmallamountofCPUisnecessarytoreconstructtheYcoordinateandaccesstheuncompressedpublickey.Bothuncompressedandcompressedpublickeysaredescribedinofficialsecp256k1documentationandsupportedbydefaultinthewidelyusedOpenSSLlibrary.
Becausetheyreeasytouse,andbecausetheyreducealmostbyhalftheblockchainspaceusedtostorepublickeysforeveryspentoutput,compressedpublickeysarethedefaultinBitcoinCoreandaretherecommendeddefaultforallBitcoinsoftware.
However,BitcoinCorepriorto0.6useduncompressedkeys.Thiscreatesafewcomplications,asthehashedformofanuncompressedkeyisdifferentthanthehashedformofacompressedkey,sothesamekeyworkswithtwodifferentP2PKHaddresses.Thisalsomeansthatthekeymustbesubmittedinthecorrectformatinthesignaturescriptsoitmatchesthehashinthepreviousoutputspubkeyscript.
Forthisreason,BitcoinCoreusesseveraldifferentidentifierbytestohelpprogramsidentifyhowkeysshouldbeused:
Privatekeysmeanttobeusedwithcompressedpublickeyshave0x01appendedtothembeforebeingBase58encoded.(Seetheprivatekeyencodingsectionabove.)
Uncompressedpublickeysstartwith0x04compressedpublickeysbeginwith0x03or0x02dependingonwhethertheyregreaterorlessthanthemidpointofthecurve.Theseprefixbytesareallusedinofficialsecp256k1documentation.
Thehierarchicaldeterministickeycreationandtransferprotocol(HDprotocol)greatlysimplifieswalletbackups,eliminatestheneedforrepeatedcommunicationbetweenmultipleprogramsusingthesamewallet,permitscreationofchildaccountswhichcanoperateindependently,giveseachparentaccounttheabilitytomonitororcontrolitschildrenevenifthechildaccountiscompromised,anddivideseachaccountintofullaccessandrestrictedaccesspartssountrustedusersorprogramscanbeallowedtoreceiveormonitorpaymentswithoutbeingabletospendthem.
TheHDprotocoltakesadvantageoftheECDSApublickeycreationfunction, point(),whichtakesalargeinteger(theprivatekey)andturnsitintoagraphpoint(thepublickey):
point(private_key) == public_key
Becauseoftheway point()functions,itspossibletocreateachildpublickeybycombininganexisting(parent)publickeywithanotherpublickeycreatedfromanyinteger(i)value.Thischildpublickeyisthesamepublickeywhichwouldbecreatedbythepoint()functionifyouaddedtheivaluetotheoriginal(parent)privatekeyandthenfoundtheremainderofthatsumdividedbya
HierarchicalDeterministicKeyCreation
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 27/55
globalconstantusedbyallBitcoinsoftware(G):
point( (parent_private_key + i) % G ) == parent_public_key + point(i)
Thismeansthattwoormoreindependentprogramswhichagreeonasequenceofintegerscancreateaseriesofuniquechildkeypairsfromasingleparentkeypairwithoutanyfurthercommunication.Moreover,theprogramwhichdistributesnewpublickeysforreceivingpaymentcandosowithoutanyaccesstotheprivatekeys,allowingthepublickeydistributionprogramtorunonapossiblyinsecureplatformsuchasapublicwebserver.
Childpublickeyscanalsocreatetheirownchildpublickeys(grandchildpublickeys)byrepeatingthechildkeyderivationoperations:
point( (child_private_key + i) % G ) == child_public_key + point(i)
Whethercreatingchildpublickeysorfurtherdescendedpublickeys,apredictablesequenceofintegervalueswouldbenobetterthanusingasinglepublickeyforalltransactions,asanyonewhoknewonechildpublickeycouldfindalloftheotherchildpublickeyscreatedfromthesameparentpublickey.Instead,arandomseedcanbeusedtodeterministicallygeneratethesequenceofintegervaluessothattherelationshipbetweenthechildpublickeysisinvisibletoanyonewithoutthatseed.
TheHDprotocolusesasinglerootseedtocreateahierarchyofchild,grandchild,andotherdescendedkeyswithunlinkabledeterministicallygeneratedintegervalues.Eachchildkeyalsogetsadeterministicallygeneratedseedfromitsparent,calledachaincode,sothecompromisingofonechaincodedoesntnecessarycompromisetheintegersequenceforthewholehierarchy,allowingthemasterchaincodetocontinuebeingusefulevenif,forexample,awebbasedpublickeydistributionprogramgetshacked.
Normal Hierarchical Deterministic (HD) Key Derivation (BIP32)
Parent Private Key Child Private Key
One-Way HashParent Chain Code
Parent Public Key Child Public Key
DerivedMathematicalRelationship
Child Chain Code
Index Number
MathematicalRelationship
Asillustratedabove,HDkeyderivationtakesfourinputs:
Theparentprivatekeyandparentpublickeyareregularuncompressed256bitECDSAkeys.
Theparentchaincodeis256bitsofseeminglyrandomdata.
Theindexnumberisa32bitintegerspecifiedbytheprogram.
Inthenormalformshownintheaboveillustration,theparentchaincode,theparentpublickey,andtheindexnumberarefedintoaonewaycryptographichash(HMACSHA512)toproduce512bitsofdeterministicallygeneratedbutseeminglyrandomdata.Theseeminglyrandom256bitsontherighthandsideofthehashoutputareusedasanewchildchaincode.Theseeminglyrandom256bitsonthelefthandsideofthehashoutputareusedastheintegervaluetobecombinedwitheithertheparentprivatekeyorparentpublickeyto,respectively,createeitherachildprivatekeyorchildpublickey:
point( (parent_private_key + lefthand_hash_output) % G ) == child_public_keypoint(child_private_key) == parent_public_key + point(lefthand_hash_output)
Specifyingdifferentindexnumberswillcreatedifferentunlinkablechildkeysfromthesameparentkeys.Repeatingtheprocedure
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 28/55
forthechildkeysusingthechildchaincodewillcreateunlinkablegrandchildkeys.
Becausecreatingchildkeysrequiresbothakeyandachaincode,thekeyandchaincodetogetherarecalledtheextendedkey.Anextendedprivatekeyanditscorrespondingextendedpublickeyhavethesamechaincode.The(toplevelparent)masterprivatekeyandmasterchaincodearederivedfromrandomdata,asillustratedbelow.
Creation Of The Master Keys
128, 256,Or 512 BitsOf Entropy(The Seed)
512-BitOne-Way
Hash
MasterPrivate Key256 Bits
MasterChain Code
256 Bits
MasterPublic Key
MasterExtended
Private Key
MasterExtendedPublic Key
Arootseediscreatedfromeither128bits,256bits,or512bitsofrandomdata.Thisrootseedofaslittleas128bitsisthetheonlydatatheuserneedstobackupinordertoderiveeverykeycreatedbyaparticularwalletprogramusingparticularsettings.
Warning:Asofthiswriting,HDwalletprogramsarenotexpectedtobefullycompatible,sousersmustonlyusethesameHDwalletprogramwiththesameHDrelatedsettingsforaparticularrootseed.
Therootseedishashedtocreate512bitsofseeminglyrandomdata,fromwhichthemasterprivatekeyandmasterchaincodearecreated(together,themasterextendedprivatekey).Themasterpublickeyisderivedfromthemasterprivatekeyusingpoint(),which,togetherwiththemasterchaincode,isthemasterextendedpublickey.Themasterextendedkeysarefunctionallyequivalenttootherextendedkeysitisonlytheirlocationatthetopofthehierarchywhichmakesthemspecial.
Hardenedextendedkeysfixapotentialproblemwithnormalextendedkeys.Ifanattackergetsanormalparentchaincodeandparentpublickey,hecanbruteforceallchaincodesderivingfromit.Iftheattackeralsoobtainsachild,grandchild,orfurtherdescendedprivatekey,hecanusethechaincodetogeneratealloftheextendedprivatekeysdescendingfromthatprivatekey,asshowninthegrandchildandgreatgrandchildgenerationsoftheillustrationbelow.
Cross-Generational Key Compromise
Parent Child Grandchild Great-Grandchild
Private PrivateParent KeyDerivation
Chain ChainNormal Child
Key Derivation
PublicPublic
Private
Chain
Public
Private
Chain
Public
Perhapsworse,theattackercanreversethenormalchildprivatekeyderivationformulaandsubtractaparentchaincodefromachildprivatekeytorecovertheparentprivatekey,asshowninthechildandparentgenerationsoftheillustrationabove.Thismeansanattackerwhoacquiresanextendedpublickeyandanyprivatekeydescendedfromitcanrecoverthatpublickeysprivatekeyandallkeysdescendedfromit.
Forthisreason,thechaincodepartofanextendedpublickeyshouldbebettersecuredthanstandardpublickeysandusersshouldbeadvisedagainstexportingevennonextendedprivatekeystopossiblyuntrustworthyenvironments.
HardenedKeys
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 29/55
Thiscanbefixed,withsometradeoffs,byreplacingthethenormalkeyderivationformulawithahardenedkeyderivationformula.
Thenormalkeyderivationformula,describedinthesectionabove,combinestogethertheindexnumber,theparentchaincode,andtheparentpublickeytocreatethechildchaincodeandtheintegervaluewhichiscombinedwiththeparentprivatekeytocreatethechildprivatekey.
Normal (Top) And Hardened (Bottom) Child Private Key Derivation
Parent Private Key Child Private Key
One-WayHashParent Chain Code Child Chain Code
Index 0x80000000
Parent Private Key Child Private Key
Parent Chain Code One-WayHash
Parent Public Key
Child Chain Code
Index
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 30/55
Hierarchical Deterministic Key Derivation
Hardened
Normal
Hardened
Normal
Normalm/0'
M/0'
m/0'/0
m/0'/1'
M/0'/0
m/0'/0/0
M/0'/0/0
Normal extendedpublic keys
can derive childpublic keys
M/0'/1'
m/0'/1'/0
Only derivation fromextended private keys
is possible forhardened keys
M/0'/1'/0
WalletsfollowingtheBIP32HDprotocolonlycreatehardenedchildrenofthemasterprivatekey(m)topreventacompromisedchildkeyfromcompromisingthemasterkey.Astherearenonormalchildrenforthemasterkeys,themasterpublickeyisnotusedinHDwallets.Allotherkeyscanhavenormalchildren,sothecorrespondingextendedpublickeysmaybeusedinstead.
TheHDprotocolalsodescribesaserializationformatforextendedpublickeysandextendedprivatekeys.Fordetails,pleaseseethewalletsectioninthedeveloperreferenceorBIP32forthefullHDprotocolspecification.
RootseedsintheHDprotocolare128,256,or512bitsofrandomdatawhichmustbebackedupprecisely.Tomakeitmoreconvenienttousenondigitalbackupmethods,suchasmemorizationorhandcopying,BIP39definesamethodforcreatinga512bitrootseedfromapseudosentence(mnemonic)ofcommonnaturallanguagewordswhichwasitselfcreatedfrom128to256bitsofentropyandoptionallyprotectedbyapassword.
Thenumberofwordsgeneratedcorrelatestotheamountofentropyused:
EntropyBits Words
128 12
160 15
192 18
224 21
256 24
Thepassphrasecanbeofanylength.Itissimplyappendedtothemnemonicpseudosentence,andthenboththemnemonicandpasswordarehashed2,048timesusingHMACSHA512,resultinginaseeminglyrandom512bitseed.Becauseanyinputtothehashfunctioncreatesaseeminglyrandom512bitseed,thereisnofundamentalwaytoprovetheuserenteredthecorrectpassword,possiblyallowingtheusertoprotectaseedevenwhenunderduress.
Forimplementationdetails,pleaseseeBIP39.
StoringRootSeeds
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 31/55
LooseKeywallets,alsocalledJustaBunchOfKeys(JBOK),areadeprecatedformofwalletthatoriginatedfromtheBitcoinCoreclientwallet.TheBitcoinCoreclientwalletwouldcreate100privatekey/publickeypairsautomaticallyviaaPseudoRandomNumberGenerator(PRNG)forlateruse.
Theseunusedprivatekeysarestoredinavirtualkeypool,withnewkeysbeinggeneratedwheneverapreviouslygeneratedkeywasused,ensuringthepoolmaintained100unusedkeys.(Ifthewalletisencrypted,newkeysareonlygeneratedwhilethewalletisunlocked.)
Thiscreatedconsiderabledifficultyinbackinguponeskeys,consideringbackupshavetoberunmanuallytosavethenewlygeneratedprivatekeys.Ifanewkeypairsetisgenerated,used,andthenlostpriortoabackup,thestoredsatoshisarelikelylostforever.Manyolderstylemobilewalletsfollowedasimilarformat,butonlygeneratedanewprivatekeyuponuserdemand.
Thiswallettypeisbeingactivelyphasedoutanddiscouragedfrombeingusedduetothebackuphassle.
Paymentprocessingencompassesthestepsspendersandreceiversperformtomakeandacceptpaymentsinexchangeforproductsorservices.Thebasicstepshavenotchangedsincethedawnofcommerce,butthetechnologyhas.Thissectionwillexplainhowreceiversandspenderscan,respectively,requestandmakepaymentsusingBitcoinandhowtheycandealwithcomplicationssuchasrefundsandrecurrentrebilling.
Bitcoinpaymentprocessingisbeingactivelydevelopedatthemoment,soeachsubsectionbelowattemptstodescribewhatswidelydeployednow,whatsnew,andwhatmightbecomingbeforetheendof2014.
Payment Processing With Bitcoin (From A Receiver's Perspective)
PriceOrder
InBTC
NewOrder Request
Payment
VerifyPayment& FulfillOrder
IssueRefund
(Sometimes)
DisburseIncome
(Optional)
RebillRecurring(Optional)
ThefigureaboveillustratespaymentprocessingusingBitcoinfromareceiversperspective,startingwithaneworder.Thefollowingsubsectionswilleachaddressthethreecommonstepsandthethreeoccasionaloroptionalsteps.
ItisworthmentioningthateachofthesestepscanbeoutsourcedbyusingthirdpartyAPIsandservices.
Becauseofexchangeratevariabilitybetweensatoshisandnationalcurrencies(fiat),manyBitcoinordersarepricedinfiatbutpaidinsatoshis,necessitatingapriceconversion.
ExchangeratedataiswidelyavailablethroughHTTPbasedAPIsprovidedbycurrencyexchanges.Severalorganizationsalsoaggregatedatafrommultipleexchangestocreateindexprices,whicharealsoavailableusingHTTPbasedAPIs.
Anyapplicationswhichautomaticallycalculateordertotalsusingexchangeratedatamusttakestepstoensurethepricequotedreflectsthecurrentgeneralmarketvalueofsatoshis,ortheapplicationscouldaccepttoofewsatoshisfortheproductorservicebeingsold.Alternatively,theycouldaskfortoomanysatoshis,drivingawaypotentialspenders.
Tominimizeproblems,yourapplicationsmaywanttocollectdatafromatleasttwoseparatesourcesandcomparethemtosee
LooseKeyWallets
Payment Processing
PricingOrders
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 32/55
howmuchtheydiffer.Ifthedifferenceissubstantial,yourapplicationscanenterasafemodeuntilahumanisabletoevaluatethesituation.
Youmayalsowanttoprogramyourapplicationstoenterasafemodeifexchangeratesarerapidlyincreasingordecreasing,indicatingapossibleproblemintheBitcoinmarketwhichcouldmakeitdifficulttospendanysatoshisreceivedtoday.
ExchangerateslieoutsidethecontrolofBitcoinandrelatedtechnologies,sotherearenoneworplannedtechnologieswhichwillmakeitsignificantlyeasierforyourprogramtocorrectlyconvertordertotalsfromfiatintosatoshis.
Becausetheexchangeratefluctuatesovertime,ordertotalspeggedtofiatmustexpiretopreventspendersfromdelayingpaymentinthehopethatsatoshiswilldropinprice.Mostwidelyusedpaymentprocessingsystemscurrentlyexpiretheirinvoicesafter10to20minutes.
Shorterexpirationperiodsincreasethechancetheinvoicewillexpirebeforepaymentisreceived,possiblynecessitatingmanualinterventiontorequestanadditionalpaymentortoissuearefund.Longerexpirationperiodsincreasethechancethattheexchangeratewillfluctuateasignificantamountbeforepaymentisreceived.
Beforerequestingpayment,yourapplicationmustcreateaBitcoinaddress,oracquireanaddressfromanotherprogramsuchasBitcoinCore.BitcoinaddressesaredescribedindetailintheTransactionssection.Alsodescribedinthatsectionaretwoimportantreasonstoavoidusinganaddressmorethanoncebutathirdreasonappliesespeciallytopaymentrequests:
Usingaseparateaddressforeachincomingpaymentmakesittrivialtodeterminewhichcustomershavepaidtheirpaymentrequests.Yourapplicationsneedonlytracktheassociationbetweenaparticularpaymentrequestandtheaddressusedinit,andthenscantheblockchainfortransactionsmatchingthataddress.
Thenextsubsectionswilldescribeindetailthefollowingfourcompatiblewaystogivethespendertheaddressandamounttobepaid.Forincreasedconvenienceandcompatibility,providingalloftheseoptionsinyourpaymentrequestsisrecommended.
1. Allwalletsoftwareletsitsuserspasteinormanuallyenteranaddressandamountintoapaymentscreen.Thisis,ofcourse,inconvenientbutitmakesaneffectivefallbackoption.
2. Almostalldesktopwalletscanassociatewith bitcoin:URIs,sospenderscanclickalinktoprefillthepaymentscreen.Thisalsoworkswithmanymobilewallets,butitgenerallydoesnotworkwithwebbasedwalletsunlessthespenderinstallsabrowserextensionormanuallyconfiguresaURIhandler.
3. Mostmobilewalletssupportscanning bitcoin:URIsencodedinaQRcode,andalmostallwalletscandisplaythemforacceptingpayment.Whilealsohandyforonlineorders,QRCodesareespeciallyusefulforinpersonpurchases.
4. Recentwalletupdatesaddsupportforthenewpaymentprotocolprovidingincreasedsecurity,authenticationofareceiversidentityusingX.509certificates,andotherimportantfeaturessuchasrefunds.
Warning:Specialcaremustbetakentoavoidthetheftofincomingpayments.Inparticular,privatekeysshouldnotbestoredonwebservers,andpaymentrequestsshouldbesentoverHTTPSorothersecuremethodstopreventmaninthemiddleattacksfromreplacingyourBitcoinaddresswiththeattackersaddress.
Tospecifyanamountdirectlyforcopyingandpasting,youmustprovidetheaddress,theamount,andthedenomination.Anexpirationtimefortheoffermayalsobespecified.Forexample:
(Note:allexamplesinthissectionusetestnetaddresses.)
RequestingPayments
PlainText
-
16/05/2015 Developer Guide - Bitcoin
https://bitcoin.org/en/developer-guide 33/55
Pay: mjSk1Ny9spzU2fouzYgLqGUD8U41iR35QNAmount: 100 BTCYou must pay by: 2014-04-01 at 23:00 UTC
Indicatingthedenominationiscritical.Asofthiswriting,popularBitcoinwalletsoftwaredefaultstodenominatingamountsineitherbitcoins(BTC),millibitcoins(mBTC)ormicrobitcoins(uBTC,bits).Choosingbetweeneachunitiswidelysupported,butothersoftwarealsoletsitsusersselectdenominationamountsfromsomeorallofthefollowingoptions:
Bitcoins Unit(Abbreviation)
1.0 bitcoin(BTC)
0.01 bitcent(cBTC)
0.001 millibitcoin(mBTC)
0.000001 microbitcoin(uBTC,bits)
0.00000001 satoshi
The bitcoin:URIschemedefinedinBIP21eliminatesdenominationconfusionandsavesthespenderfromcopyingandpastingtwoseparatevalues.Italsoletsthepaymentrequestprovidesomeadditionalinformationtothespender.Anexample:
bitcoin:mjSk1Ny9spzU2fouzYgLqGUD8U41iR35QN?amount=100
Onlytheaddressisrequired,andifitistheonlythingspecified,walletswillprefillapaymentrequestwithitandletthespenderenteranamount.Theamountspecifiedisalwaysindecimalbitcoins(BTC).
Twootherparametersarewidelysupported.The labelparameterisgenerallyusedtoprovidewalletsoftwarewiththerecipientsname.The messageparameterisgenerallyusedtodescribethepaymentrequesttothespender.Boththelabelandthemessagearecommonlystoredbythespenderswalletsoftwarebuttheyareneveraddedtotheactualtransaction,sootherBitcoinuserscannotseethem.BoththelabelandthemessagemustbeURIencoded.
Allfourparametersusedtogether,withappropriateURIencoding,canbeseeninthelinewrappedexamplebelow.
bitcoin:mjSk1Ny9spzU2fouzYgLqGUD8U41iR35QN\?amount=0.10\&label=Example+Merchant\&message=Order+of+flowers+%26+chocolates
TheURIschemeca