Upload
others
View
3
Download
0
Embed Size (px)
Citation preview
ATechnicalIntroductiontoBitcoinNiklas Fors,2018-02-20
Bitcoin
• Decentralized digitalcurrency• Anyonecanbepartofthenetwork
• Globaldistributedledgercalledblockchain
FirstAppearance• Bitcoin:APeer-to-PeerElectronicCashSystembySatoshiNakamoto,November2008• Firstimplementation:January2009
Centralizedvsdecentralized
Centralizeddatabase
DecentralizedcontrolAnyonecanjointhenetwork
Accounts
Accounts
Accounts
Accounts
Accounts
Accounts Accounts
Accounts
Accounts
Accounts
Decentralizeddatabase
CentralizedcontrolAcentralauthoritydecideswhichnodesarepartofthenetwork
CryptographicBackground
Importantconceptsfromcryptography:• Cryptographichashfunctions• Applications:message/fileintegrity,hashpointers,storingpasswords…
• Digitalsignatures• Applications:emailsignatures(PGP),…
CryptographicHashFunctions
Infinitesetofvalues(allpossiblestrings)
Finitesetofvalues(e.g.,using256bits)
y
xH(x)
H(y)
HashCollision
Infinitesetofvalues(allpossiblestrings)
Finitesetofvalues(e.g.,using256bits)
x
y
H(x)=H(y)
Hashcollision:differentinputvaluesyieldthesamehashvalue
ImportantPropertiesforBitcoin
1)Collision-resistanceAhashfunctionHissaidtobecollisionresistant ifitisinfeasibletofindtwovalues,xandy,suchthatx≠y,yetH(x)=H(y).
2)HidingGiveny=H(x),itshouldbeinfeasibletofigureoutx.
3)PuzzlefriendlinessCanbeusedforpuzzleswheretheonlysolvingstrategyisbruteforcing
SHA256
Examplessha256(niklas) =
760dcecfbe1ce8c36f9ac03686d3ad74e4c4f08978648677aa62b87014c27365
sha256(niklaz) =1f5fd1befbf9da49d1fc5f8c241fc932800aa907358742155d091d880c2b18d8
BitcoinusesthehashfunctionSHA256(fromSHA-2family).Theoutputuses256bits=>2^256differentvaluesYou will getahash collision when computing 2^128hashes (onaverage)
HashPointers
… data…
prev:...
B1
last:H(prev ||data)
Last isahashpointer,whichisthehashofthecontentofB1.IfwechangethedatainB1,thevalueoflastwillchange.Thus,giventhehashpointer,wecanverifythatB1hasnotchanged(probabilistic).
||isconcatenation
ALinkedChainofBlocks
… data…
prev:...
… data…
prev:H(B1)
B1 B2 B3
… data…
prev:H(B2)
last:H(B3)
Giventhevalueoflast,it’sverydifficulttochangethedataofB1,withoutchangingthevalueoflast.
DigitalSignaturesSigningmessagesthatcanbeverified.
API(privateKey,publicKey)<- generateKeys()signature<- sign(privateKey,message)verify(publicKey,message,signature)
Property:verify(publicKey,message,sign(privateKey,message))==true
Bitcoin
• Addresses• Transaction-basedledger• Blocks– acollectionoftransactions• Mining– verifyingblocks• Double-spendproblem
PublicKeysasIdentities
InBitcoin,publickeysareusedasidentities.
Coinsaresenttoaddresses,whichisthehashofthepublickey.
Touseacoin:Createanewtransactionandsignitwiththecorrespondingprivatekey.
Transactions-basedledger
In:Out:25->Alice
Transaction1
In1[0]Out:17->Bob8->Alice
Transaction2
Theledgeristransaction-based(noaccounts)• Atransactionhasinputcoinsandoutputcoins(indexfrom0)• Inputsareconsumedinthetransaction(cannotbeusedagain)• Outputsareproducedfromtheinputs,thus,sum(inputs)>=sum(outputs)• Theinputsreferenceoutputsfromprevioustransactions
SIGNED(Alice)
In:2[0]Out:8->Carol9->Bob
Transaction3
SIGNED(Bob)
In:2[1]Out:6->Carol2->Alice
Transaction4
SIGNED(Alice)
In:3[0]4[0]Out:14->Bob
Transaction5
SIGNED(Carol)
Endresult:Alice:2Bob:23 UTXO: unspent transaction output
ExampleTransactions
ChangeaddressA(2)à B(1),A(1)
JointpaymentA(1),B(1)à C(2)
MergingB(1),B(1)à B(2)
SplittingB(2)à B(1),B(1)
Don’tLoseYourPrivateKey!
Todayworth(approximately):7500*10000=75000000USD
{ "hash":"1b4890246...", "vin_sz":1,"vout_sz":1"size":223,"inputs":[
{"prev_out":{"hash":"76a91496b...""n":0},
"scriptSig":"47304402201420..."}],"out":[
{"value":2298949,"scriptPubKey": "OP_DUP ... <pubKeyHash>..."}
]}
ExampleofTransactionData
Bitcoinscripts!
Address
ExampleTransactionVerification
Toverifyaninput1. Findthereferencedoutput2. Hashthepublickey(h)givenintheinput3. Comparehwithaddressspecifiedinreferencedoutput4. Verifysignaturewithpublickey
In:Out:25->Alice
Transaction1
In1[0]Out:…
Transaction2
Address(hashofpublickey)
Signatureandpublickey
BitcoinScripts(Pay-to-PubkeyHash script)
scriptSig: <sig> <pubKey>
scriptPubKey: OP_DUPOP_HASH160<pubKeyHash>OP_EQUALVERIFYOP_CHECKSIG
Scriptinreferencedoutput(earliertransaction): Scriptininput(newtransaction)
Thescriptsareconcatenated:<sig><pubKey>OP_DUPOP_HASH160<pubKeyHash>OP_EQUALVERIFYOP_CHECKSIG
ScriptExecution
Command Stack Description
<sig> <sig> Push
<pubKey> <sig><pubKey> Push
<OP_DUP> <sig><pubKey><pubKey> Duplicatetopofstack
<OP_HASH160> <sig> <pubKey><hashOfPubKey> Hashtopof stack
<pubKeyHash> <sig><pubKey> <hashOfPubKey> <pubKeyHash> Push
OP_EQUALVERIFY <sig><pubKey> Top ofstackshouldbeequal
OP_CHECKSIG true Verify signature ofpublickey
Frominput
Fromreferencedoutput
ScriptingLanguages
• ThescriptinglanguageinBitcoinislimited• However,othercryptocurrencies (Ethereum,…) havescriptinglanguagesthatareTuring-complete=>makingitpossibletowritearbitraryprograms• A waytoimplementsmartcontracts (contractsspecifiedincode)
Blockchain
prev:...
…transactions
…
prev:H(B2)
…transactions
…
prev:H(B1)
…transactions
…
• Ablockisacollectionoftransactions(somethousandstransactions)• Anewblockiscreatedevery10minutes(onaverage)• Theblocksareputinablockchain
B1 B3B2
DoubleSpendAttempt
...… ->A...
…T1:A->B
…
…T2:A->C
…
BlockcreatedbyminerM1
BlockcreatedbyminerM2
Whichtransactionisvalid?T1orT2?Both?
Alicecreatestwotransactionthatusesthesameoutput,thus,adoublespendattempt!
Twoblockarecreatedsimultaneouslybytwodifferentminers.
Answer:wedon’tknowyet
WhichBlocktoExtend?(1)
...… ->A...
…T1:A->B
…
…T2:A->C
…
…
Anewblockiscreatedbyaminer.Whichpreviousblocktoextend?
Theminerdecidesthat!(probablytheblockthattheminerobservedfirst)
WhichBlocktoExtend?(1)
...… ->A...
…T1:A->B
…
…T2:A->C
…
…
Inthiscase,theminerselectedthetopblock.
WhichBlocktoExtend?(2)
...… ->A...
…T1:A->B
…
…T2:A->C
…
… …
Anewblockiscreated.Whichblocktoextend?
LongestChainisExtended!
...… ->A...
…T1:A->B
…
…T2:A->C
…
Honestminersextendthelongestchain!
…
Thetopblockhasalongerchain
…
Thus,itseemsthatT1succeeded,buttheanswerisofprobabilisticnature.
After6blockconfirmations, it’sverylikelythatthetransactionsucceeded.
BlockCreation(1)
Howisablockcreated?Minersneedtosolveacryptographicpuzzle!
Forthewholenetwork,ittakesanaverageof10minutestosolvethepuzzle.
BlockCreation
Thepuzzlerequiresasolutionto:
H(nonce ||prev_hash ||… )<difficultyTarget
Thehashshouldhavealeadingnumberofzerobits(difficultydecideshowmany)
Theminertriesdifferentvaluesofthenonce tomeetthetarget(bybruteforcing).
Thepuzzleishardtosolve,butveryeasytoverify.
ProofofWork
ThistechniqueiscalledProofofWork(PoW),anapproachfordistributedconsensus
Itcanbethoughtofasone-CPU-one-vote.
PoW preventsattacksonthenetwork,orrather,itmakesthemverycostly.
Ifyouown10%ofallhashpowerofthenetwork,thenyouwillonaveragecreate10%oftheblocks.
(Thereareotherconsensusmechanisms:ProofofStake,…)
Exa=10^1821290000000000000000hashes/s
Requiresalotofenergy!
Howlongtimebeforewegetahashcollisionwiththishashrate?!"#$
!%∗'("$/(86400*365)=469142742209years13799000000years(the age ofthe universe)
Answer:34times the age ofthe universe
Network(fromBitcoinpaper)
Thestepstorunthenetworkareasfollows:1. Newtransactionsarebroadcasttoallnodes.2. Eachnodecollectsnewtransactionsintoablock.3. Eachnodeworksonfindingadifficultproof-of-workforitsblock.4. Whenanodefindsaproof-of-work,itbroadcaststheblocktoallnodes.5. Nodesaccepttheblockonlyifalltransactionsinitarevalidandnot
alreadyspent.6. Nodesexpresstheiracceptanceoftheblockbyworkingoncreatingthe
nextblockinthechain,usingthehashoftheacceptedblockastheprevioushash.
Merkle Tree
prev:H()mrkl_root:H()
nonce:hash:…
H()H()
H()H()
transactiontransaction
H()H()
transactioncoinbase
BlockheaderThetransactionsinablockarestoredinaMerkle tree
CPUminingpseudocode
TARGET=(65535<<208)/DIFFICULTY;coinbase_nonce=0;while(1){
header=makeBlockHeader(transactions,coinbase_nonce); for(header_nonce=0;header_nonce<(1<<32); header_nonce++){ if(SHA256(SHA256(makeBlock(header,header_nonce))) < TARGET)
break;//block found!}coinbase_nonce++;
}
MiningIncentive
Whydominersmine?Becausetheyarerewarded!Therewardsencouragethemstayhonest.
Blockrewards• Newcoinsarecreatedineachblock(calledthecoinbase transaction)
• Thenumberdecreasesovertime
• Transactionfees(whensum(inputs)>sum(outputs))
TheGenesisBlock
TheGensis blockcontainsthefollowingtextinitscoinbase transaction:
TheTimes03/Jan/2009Chancelloronbrinkofsecondbailout forbanks
(approximatelyeveryfouryears)
Currentnumberofblocks:~500000Currentblockreward(approximately):12.5*10k=125kUSD
TheCostofMining
Ifminingreward >miningcostminerprofits
whereminingreward=blockreward+transactionfeesminingcost=hardwarecost+operatingcosts(electricity,cooling,etc.)
MiningHardware
Theminersareincreasinglyusingmoreefficienthardware:1. CPU2. GPU3. FPGA4. ASIC
MiningPools
Source:blockchain.info
Togetamorestablestreamofincome,beamemberofaminingpool.
Scalability?
• Anewblockiscreatedevery10minutes• Themaxblocksizeis1MB• Numberoftransactionspersecond:~average transaction size/1MB/60*10• Thecurrent limitisabout 7transactions/second=>604800/day
Ongoing work- SegWit:roughly doubling theblocksize- Lightningnetwork:secondlayer ontop of Bitcoin blockchain formicropayments
Currentmediantransactionfee:0.5-1USD
Source:bitinfocharts.com
ReadMore
• Thecontentofthislectureisbasedonthebook:BitcoinandCryptocurrency Technologies• TheauthorsalsohaveacourseonCoursera