blockchain programming in csharp

Upload: asmtrash

Post on 08-Jul-2018

271 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/19/2019 Blockchain Programming in CSharp

    1/83

     

    Blockchain Programming in C# Authored by Nicolas Dorier

    Contributor for NBitcoin,

    The .NET Bitcoin Framework

    Co-authored ith Bill !trait

    Founder of Billd "abs 

  • 8/19/2019 Blockchain Programming in CSharp

    2/83

     

    #Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Table of ContentsI.  Introdction ..................................................................................................................................... ! 

    ".  ore$ord ..................................................................................................................................... ! 

    %.  h' Blockchain Programming and not Bitcoin Programming ..................................................  

    3.  h' C# .......................................................................................................................................  

    !.  Pre*re+isites ..............................................................................................................................  

    a.  Skills .........................................................................................................................................  

    ,.  -ools ........................................................................................................................................  

    .  Cro$d/nding this ,ook ..............................................................................................................  

    .  Com0lementar' 1eading .............................................................................................................  

    2.  Diagrams ...................................................................................................................................... 2 

    .  4icense5 CC (ASA 3U) ....................................................................................................................  

    6.  Pro7ect Set0 ............................................................................................................................... 6 

    II.  Bitcoin trans/er .............................................................................................................................. "8 

    ".  Bitcoin Address .......................................................................................................................... "8 

    %.  -ransaction ................................................................................................................................ " 

    3.  Blockchain.................................................................................................................................. "6 

    !.  9-he Blockchain is more than 7st Bitcoin: ............................................................................... "6 

    .  S0end 'or coin ......................................................................................................................... %8 

    .  Proo/ o/ o$nershi0 as an athentication method .................................................................... %! 

    III.  ;e' Storage and

  • 8/19/2019 Blockchain Programming in CSharp

    3/83

  • 8/19/2019 Blockchain Programming in CSharp

    4/83

     

    %Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    I.  Introduction 

    1. Foreword

    A passage inFountain Head 

     by Ayn Rand resonated with me.

    P>1U4 PUPP>- AS->1 -@> 14DH AND @A1; @A1DH -@> P1-AC- DISCUSS>D --@>1. 4I> @>N @> IS I-@ @A1;H N- ;NIN< @>1> I-

    C>S 1H @> U>S-IN>D @I.

    GNAND AS;>D5

    J@A1DH @A> GU >>1 B>>N IN 4>J

    1A1; -U1N>D - 4; S-1AI1 UIC;4G5

    JI S-I44 A.J

    JBU- @>N GU A4; -@1U4 IS A->1 -@AN -@A-J

    JUC@ A->1H P4> @ SAG -@A- @APPIN>SS IS IPSSIB4> N >A1-@. 4; @ @A1D -@>G A44 -1G -

    IND S>N> KG IN 4I>. 4; @ -@>G S-1UA-U1> >LIS- IN PAIN BG

    @A- CNC>IAB4> 1I D>AND -@A- A @UAN B>IN< >LIS- 1 ANG-@IN< BU- @IS N KG 

    >>1G N> -@> AN-S I-. >>1G PA1- @I AN-S I-. BU- -@>G N>>1 IND I-. I ND>1 @G. -@>G @IN>

    AND SAG -@>G DNM- UND>1S-AND -@> >ANIN< 4I>. -@>1>MS A PA1-ICU4A1 ;IND P>P4> -@A- I D>SPIS>. 

    -@S> @ S>>; S> S1- A @I1 PU1PS> 1 UNI>1SA4 1H 

    @ AN -@A- -@>G US- IND -@>S>4>S.? GU @>A1 I- A44 A1UND US. -@A- S>>S - B> -@> ICIA4

    B1ID> U1 C>N-U1G. >>1G B; GU P>N. >>1G D14IN< S>4*CN>SSIN. I- S>>S - B> -@> NB4>

    -@IN< - CN>SS. IMD -@IN; I- U4D B> -@> S- S@A>U4 N> .J

    J4;H D U-H -1> A -@IC; B1ANC@ A -1>>H @>4D I- IN B-@ @ANDSH N> IS-

    C4S>D A- >AC@ >NDO -@>NH @IS 1IS-S AND ;NUC;4>S ->NS>D A 1>SIS-ANC>H @> B>N- -@> B1ANC@

    S44G IN- AN A1C. JN I CAN A;> @A- I AN- I-5 A BH A SP>A1H A CAN>H A 1AI4IN

    >ANIN< 4I>.J

    JGU1 S-1>N -SS>D -@> B1ANC@ ASID>. J-@> A->1IA4 -@> >A1-@ >1S GU AND @A- GU A;> I-...J

    I think the Blockchain is like the tree branch. For outsiders, it feels like a boring and useless collectionof bits. For programmers and entrepreneurs, it is a marvelous raw material that can be shaped withour imagination. We give it meaning and purpose.

    Just as you need to know about wood to make a bow, spear or cane from a branch, you need to learnabout programming to shape the Blockchain. My hope is that you will discover how much your skilland intelligence can shape that useless collection of bits.

    Let me warn you: learning about the Blockchain is like taking the red pill from The Matrix. You may findyourself ready to quit your job to work on it full time.

    This book will take you from basic to advanced use of the Blockchain. It will not teach you how to usean API (such as the RPC API provided with Bitcoin Core), but it will teach you how to make such anAPI.

    FACT& !atoshi Nakamoto once described Bitcoin as 'borin( (rey in colour.)

  • 8/19/2019 Blockchain Programming in CSharp

    5/83

     

    *Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    While programming to an API can assist in getting an application up quickly, the developer is limited toinnovations that can take place against the API. By fully understanding the Blockchain, the developeris empowered to unleash its full potential.

    2. Why Blockchain Programming and not Bitcoin Programming?

    The Blockchain is to (old what Bitcoin is to +ewelry.

    e did not com0are Bitcoin to a gold coinH ,t rather $ith a 7e$elr'. -hat?s ,ecase gold?s /irst killer

    a00 $as 7e$elr'. Coins came later.

    Do not ,e /ooled into thinking that Bitcoin is /la$ed $hile the Blockchain is =ala,le. I/ gold is

    =ala,leH $old 'o thro$ a$a' a gold necklace -he Blockchain is ,ilt on and thri=es ,ecase o/

    ,itcoin. An' increase in =ale o/ the Blockchain $ill increase the amont o/ Bitcoin that is s0ent to

    se itH $hich $ill increase its demand.

    hether or not 'or a00 $ill se the 9Bitcoin as a crrenc': /eatre is 'or o$n decision.

    Blockchain is the ra$ material. Bitcoin is the /el. Bitcoin as a crrenc' is a /eatre that emerges

    e=er' time someone thinks this /el is also a good medim o/ eFchange. Go can do a lot more $ith

    the Blockchain than eFchange =ale. Go don?t e=en ha=e to ,elie=e in the crrenc'. e $ill sho$

    'o ho$ to se Bitcoin as a crrenc' in this ,ookH ,t that?s not all

    3. Why C#?

    -he .N>- /rame$ork is 0o0lar in cor0orate en=ironments. e also ,elie=e this is the 0er/ect tool /or

    start0s and ho,,'ists.

    •  .N>- can create 0orta,le code that /nctions across ISH AndroidH indo$s ta,letsQ0honeH

    deskto0sH ser=ers and em,edded de=ices.

    •  >=er'thing /rom the com0iler to the core rntime is o0en sorce.

    •  -he BiRS0ark 0rogram allo$s an' start0 to get all icroso/t toolsH inclding "8Qmonth o/

    ARre ser=iceH /or /ree.

    •  isal Stdio Commnit' %8"3 is a 0ro/essional grade ID> that 'o can se /reel' as

    ho,,'ist.

    •  C# is closel' related to Ka=a and CTT. As schH it can ,e easil' read ,' de=elo0ers $ho alread'

    kno$ C s'ntaF.

    •  Nicolas DorierH one o/ the athors o/ this ,ookH created the most 0o0lar Bitcoin rame$ork

    /or .N>-H called NBitcoin. Go can /ind it here5 htt0s5QQgith,.comQNicolasDorierQNBitcoin

    -he athors o/ this ,ook ha=e o=er " 'ears com,ined eF0erience $ith C#. It is or go*to langage

    /or an' 0ro7ect /or /n or 0ro/it.

    Fact& e hae not been aid by icrosoft. /t0s not too late to chan(e that.

    4. Pre-reqi!ite!

    a.  "kill!•  Go need to ,e com/orta,le $ith o,7ect oriented as $ell as /nctional 0rogramming.

  • 8/19/2019 Blockchain Programming in CSharp

    6/83

     

    1Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    •  A ,asic gras0 o/ C# is hel0/lH ,t $e /eel the code $ill ,e legi,le to Ka=a and other C*,ased

    langages.

    •  No mathematic kno$ledge is re+ired. e $ill not co=er cr'0togra0h' ,e'ond the ,are

    minimm that 'o need to kno$ to make a secre ser=ice.

    •  Go don?t need to ha=e dee0 kno$ledge o/ Bitcoin. e do recommend reading astering

    Bitcoin ,' Andreas Antono0olos /or eFtra credit.

    .  $ool!•  isal Stdio %8"3 * Go can get it /or /ree ,' searching /or 9isal stdio %8"3 commnit':

    on

  • 8/19/2019 Blockchain Programming in CSharp

    7/83

     

    5Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    •  Nicolas Dorier?s articles on CodePro7ect

    (htt05QQ$$$.code0ro7ect.comQem,ersQNicolasDorier)

    •  -he De=elo0er?s 1e/erence

  • 8/19/2019 Blockchain Programming in CSharp

    8/83

     

    6Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    ,. icen!e CC /0"0 3

    As 'o ha=e seen in the 9Cro$d/nding this ,ook: 0artH $e $ill distri,te this ,ook to o$ner o/

    Bitcoin addresses that /nded it.

    nce in 0ossession o/ this ,ookH 'o are /ree to share and ada0tH as s0eci/ied in the Attri,tion*Share

    Alike 3.8 Un0orted (CC BG*SA 3.8).

    e $old consider it a cortes' i/ an'one $ho recei=ed this ,ook /or /ree $old send along a small

    ti0 $hen 0rom0ted.

    As cr'0tocrrenc' addicts might sa'5 Proo/ o/ Stake and Proo/ o/ ork are the ,est eF0ression o/

    a//ectionH e=er'thing else is iat. ☺ 

  • 8/19/2019 Blockchain Programming in CSharp

    9/83

     

    7Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    . Proect "et(

    Be/ore $e ,egin $ith the instrctionH $e shold descri,e ho$ $e eF0ect 'or 0ro7ect to ,e set 0.

    ".  0en isal Stdio and create a ne$ Console A00lication. Name it

    9ProgrammingBlockchain.:

    %.  1ight click on 91e/erences: in Soltion >F0lorer and select 9anage N

  • 8/19/2019 Blockchain Programming in CSharp

    10/83

     

    89Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    II. Bitcoin transfer

    1. Bitcoin 0ddre!!

    Go kno$ that 'or Bitcoin Address is $hat 'o share to the $orld to get 0aid. Go 0ro,a,l' kno$that 'or $allet so/t$are ses a private key to s0end the mone' 'o recei=ed on this address.

    A Bitcoin Address is made 0 o/ a Base58check encoded com,ination o/ 'or public key’s hash and

    some in/ormation a,ot the net$ork the address is /or. -he BaseCheck encoding has some neat

    /eatresH sch as checksms to 0re=ent t'0os and a lack o/ am,igos characters sch as 98: and

    9.:

    Fact& TestNet is a bitcoin network for deeloment uroses, the bitcoin on this

    network are worth nothin(. MainNet  is the bitcoin network eerybody knows.

    Go might not kno$ that as /ar as the Blockchain is concernedH there is no sch thing as a Bitcoin

    Address. Internall'H the Bitcoin 0rotocol identi/ies the reci0ient o/ Bitcoin ,' a ScriptPubey. A

    Scri0tP,;e' is a short scri0t that eF0lains $hat conditions mst ,e met to claim o$nershi0 o/

    ,itcoins. e $ill go into the t'0es o/ instrctions that can ,e gi=en in a Scri0tP,;e' as $e mo=e

    throgh the lessons o/ this ,ook. -he Scri0tP,;e' ma' contain the hashed 0,lic ke'(s) 0ermitted

    to s0end the ,itcoin.

    Fact& :racticin( Bitcoin :ro(rammin( on ainNet makes mistakes morememorable.

    -his diagram illstrates the relationshi0s ,et$een the 0,lic ke'H 0ri=ate ke'H ,itcoin addressH and

    the Scri0tP,;e'.

  • 8/19/2019 Blockchain Programming in CSharp

    11/83

     

    88Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    No$ $e can sho$ 'o the relationshi0 in code. 0en Cha0ter".csH add 9sing NBitcoinO: to the to0and then make the /ollo$ing method5

    pu1lic oid Lesson)"% {

    2ey key ' ne( 2ey"%; &&generates a ne( priate key. Pu12ey pu12ey ' key.Pu12ey; &&gets the matching pu1lic key. Console.,riteLine"-Pu1lic 2ey3 {40-5 pu12ey%;

    2ey6d hash ' pu12ey.7ash; &&gets a hash o+ the pu1lic key. Console.,riteLine"-7ashed pu1lic key3 {40-5 hash%; BitcoinPu12ey8ddress address ' pu12ey.Get8ddress"9et(ork.!ain%; &&retriees the

    1itcoin address. Console.,riteLine"-8ddress3 {40-5 address%; 

    Script scriptPu12ey:rom8ddress ' address.ScriptPu12ey; Console.,riteLine"-ScriptPu12ey +rom address3 {40-5 scriptPu12ey:rom8ddress%; Script scriptPu12ey:rom7ash ' hash.ScriptPu12ey; Console.,riteLine"-ScriptPu12ey +rom hash3 {40-5 scriptPu12ey:rom7ash%; 

  • 8/19/2019 Blockchain Programming in CSharp

    12/83

  • 8/19/2019 Blockchain Programming in CSharp

    13/83

     

    8$Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    P,lic ;e' @ash5 ",%daee%accde6d%6!/"%a8%!""/d%a

    Bitcoin Address5 "3Uh$6BmdaL,n7DLi>d!@U!'es72k;7FCo

    Fact& The hash of the ublic key is (enerated by erformin( a !;A#*1 hash on the

     ublic key, and then erformin( a

    So no$ 'o nderstand the relationshi0 ,et$een a Pri=ate ;e'H a P,lic ;e'H a P,lic ;e' @ashH a

    Bitcoin Address and a scri0tP,;e'.

    Pri=ate ke's are o/ten re0resented in BaseCheck called a Bitcoin Secret (also kno$n as !allet

    "#port $or#at or sim0l' !"$)H like Bitcoin Addresses.

    or the rest o/ the ,ook 'o $ill se an address that 'o ha=e generated /or 'orsel/.

    Note that it is eas' to go /rom Bitcoin Secret to Pri=ate ;e'. It is im0ortant to remem,er that it is

    im0ossi,le to go /rom a Bitcoin Address to P,lic ;e' ,ecase the Bitcoin Address contains a hash o/

    the P,lic ;e'H not the P,lic ;e' itsel/.

  • 8/19/2019 Blockchain Programming in CSharp

    14/83

     

    8%Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    pu1lic oid Lesson*"% 

    {

    2ey key ' ne( 2ey"%; 

    BitcoinSecret secret ' key.GetBitcoinSecret"9et(ork.!ain%; 

    Console.,riteLine"-Bitcoin Secret3 {40-5 secret%; 0 

    Bitcoin Secret5 ;'PaNGgSC$k=h

  • 8/19/2019 Blockchain Programming in CSharp

    15/83

  • 8/19/2019 Blockchain Programming in CSharp

    16/83

     

    81Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    NBitcoin +eries ,lockr and 0arses the in/ormation /or 'o so 'o don?t ha=e to do it manall'.

    pu1lic oid Lesson)"%{

    ar 1lockr ' ne( BlockrTransaction/epository"%;Transaction transaction '

    1lockr.Get"-*e1+I+Ica4aAda+d)411dI*dc1Ha@e14H)1c1@HI+eceaa1+*+)c@-%;Console.,riteLine"transaction.ToString"%%;

    0

  • 8/19/2019 Blockchain Programming in CSharp

    17/83

     

    85Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    JhashJ5 J!e,/2/2ca8ada/d"8,6,d2!dc,63ae,83",c,32/eceaa,/!%/"c%JH

    J=erJ5 "H

    J=inWsRJ5 "H

    J=otWsRJ5 %H

    JlockWtimeJ5 8H

    JsiReJ5 %%H

    JinJ5

    X

    J0re=WotJ5 X

    JhashJ5 J,/2d6"ac286"2/6,!626%2e",82%282%,%8d/"!ecd,a%e6368,6,//cJH

    JnJ5 8

    YHJscri0tSigJ5

    J38!!8%%86,,8/"ad!3,d,6e3ad!2%3%,e8"d%"e2,3aca,3/38/!8e8,3,"8%%83c8!6

    262388%8%63c23d!,!a%dda883aa2"c"dccd%c2a/%68dcd""de8"

    8%e33!%238836e2ea66e63ce/,2!8,ad/3d86e,c38",8,c6d",,838"a3!"2J

    Y

    EH

    JotJ5

    X

    J=aleJ5 J8.8668888JH

    Jscri0tP,;e'J5 JPWDUP PW@AS@"8 ,"d2%8da/8e6e32d8eaedd%%,ed6a!8,a,2"

    PW>UA4>1IG PWC@>C;SI

  • 8/19/2019 Blockchain Programming in CSharp

    18/83

     

    86Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    >=er' ot has an address de/ined ,' the transaction ID and indeF called the *utpoint. or eFam0leH

    the t0oint o/ the ot $ith 8.8" B-C in m' transaction is

    (2"8!6/d!2,a%"82d,28d3,"%2cae!//8a32,!a,H ").

    No$ let?s take a look at the in (aka (&"nH "nputs) o/ the transaction5

    -he -FIn is com0osed o/ the t0oint o/ the 0re=Wot ,eing s0ent and o/ a ScriptSig also called

    9Proo/ o/ $nershi0.: In m' caseH the 0re=Wot t0oint is

    (2de/a6a2a%c"!6!/3c!,6833,2,38/%3838,H 8)

    B' re0lacing the transaction ID in the code $e $rote /or 4esson" $e can re=ie$ the in/ormation

    associated $ith that transaction. e cold contine to trace the transaction IDs ,ack in this manner

    ntil $e reach the ,itcoins? coinbase+ the ,lock $here the' $ere mined.

    In or eFam0leH the 0re=Wot $as /or a total o/ ." B-C. In this transaction .866 B-C and .8" B-C $ere

    sent. -hat means 8.888" B-C is not acconted /or -he di//erence ,et$een the in0ts and ot0ts

    are called (ransaction $ees or Miner’s $ees. -his is the mone' that the miner collects /or inclding a

    gi=en transaction in a ,lock.

  • 8/19/2019 Blockchain Programming in CSharp

    19/83

     

    87Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    3. Blockchain

    Go might ha=e noticed that $hile $e 0ro=ed o$nershi0 o/ the s0ent -FtH and that $e ha=e not

    0ro=en the -Ft actall' eFists. -his is $here the main /nction o/ the Blockchain shines5

    -he Blockchain is the data,ase o/ all transactions that ha=e ha00ened since the the /irst Bitcoin

    transactionH kno$n as the

  • 8/19/2019 Blockchain Programming in CSharp

    20/83

     

    #9Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    In the rest o/ this ,ook $e $ill eF0lore the /ndamentals re+ired to ena,le all o/ these technologies

    and more. It all starts $ith s0ending a ,itcoin.

    %. "(end yor coin

    So no$ that 'o kno$ $hat a ,itcoin addressH a Scri0tP,;e'H a 0ri=ate ke'H and a miner are 'o?llmake 'or /irst transaction ,' hand. Create a ne$ class called Cha0ter"! and a method called

    4esson". As 'o 0roceed throgh this cha0ter 'o $ill add code line ,' line as it is 0resented to ,ild

    a method that $ill lea=e /eed,ack /or the ,ook in a -$itter st'le message.

    4et?s start ,' looking at the transaction that that contains the -Ft that 'o $ant to s0end as $e

    did in Cha0ter "".

    ar 1lockr ' ne( BlockrTransaction/epository"%; Transaction +undingTransaction '

    1lockr.Get"-41*14@I*aHd1d1a41*H@e4+ceaa*e@de14c@)4d))4c1+A*ac1*-%; 

    In or caseH $e $ant to s0end the second ot0t5

    JotJ5

    X

    J=aleJ5 J8.8668888JH

    Jscri0tP,;e'J5 JPWDUP PW@AS@"8 ,"d2%8da/8e6e32d8eaedd%%,ed6a!8,a,2"

    PW>UA4>1IG PWC@>C;SI

  • 8/19/2019 Blockchain Programming in CSharp

    21/83

     

    #8Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    -he ,ook?s donation address is5 ";kU@;!%LRgcmK!4FR!$c4D462PB

    ar programmingBlockchain '

    Bitcoin8ddress.Create"-)2:k?F72*KgcmJ:*Lx*(cLA,>LIPB-%; payment.

  • 8/19/2019 Blockchain Programming in CSharp

    22/83

  • 8/19/2019 Blockchain Programming in CSharp

    23/83

     

    #$Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Signing can ,e com0licated. 1e/er to

    htt0s5QQen.,itcoin.itQ$QimagesQenQ2Q28QBitcoinW0CheckSigWInDetail.0ng /or details. Bt $e?ll make

    it sim0le.

    irst insert the scri0tP,;e' in the scriptSig.

    Since the scri0tP,;e' is nothing ,t pay#entAddress.ScriptPubey this is sim0le.-hen 'o need to gi=e 'or 0ri=ate ke' /or signing.

    payment.6nputs#4$.ScriptSig ' payment8ddress.ScriptPu12ey;

    &&also

  • 8/19/2019 Blockchain Programming in CSharp

    24/83

     

    #%Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    '. Proo& o& owner!hi( a! an athentication method

    hen I $ill release the neFt cha0tersH I $ill athenticate 'o $ith the ke' 'o sed to 0a' me.

    Do 'o remem,er $hen I said5

    Address:  ";kU@;!%LRgcmK!4FR!$c4D462PBSignature: 

    @"7iLPRn3rLi8N6=61/Ar/>ae6Pml4DKB7"e-StS=0;d11IoQ-6t

  • 8/19/2019 Blockchain Programming in CSharp

    25/83

     

    #*Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    III.  Key Storage and Generation

    1.  7! it random enogh?

    hen 'o call ne3 ey4H nder the hoodH 'o are sing a P1N< (Psedo*1andom*Nm,er*ntro0' is measred ,' 9*74possibilities; and so 4T"6O %) ,its.

  • 8/19/2019 Blockchain Programming in CSharp

    26/83

     

    #1Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Is it enogh Pro,a,l'. Assming 'or attacker does not kno$ more in/ormation a,ot the realm o/

    0ossi,ilities.

    Bt since the hash o/ a 0,lic ke' is %8 ,'tes "8 ,itsH it is smaller than the total ni=erse o/ the

    addresses. Go might do ,etter.

    Note& Addin( entroy is linearly harder, crackin( entroy is e4onentially harder

    An interesting $a' o/ generating entro0' +ickl' is ,' asking hman inter=ention. (mo=ing the

    mose)

    I/ 'o don?t trst com0letel' the 0lat/orm P1N< ($hich is not so 0aranoic)H 'o can add entro0' to

    the P1N< ot0t that NBitcoin is sing.

    /andom?tils.8ddDntropy"-hello-%;

    /andom?tils.8ddDntropy"ne( 1yte#$ { )5 5 H 0%;ar nsaProo+2ey ' ne( 2ey"%; 

    hat NBitcoin does $hen 'o call Add%ntropy4data is5

    additional%ntropy < S=A4S=A4data > additional%ntropy

    -hen $hen 'o generate a ne$ nm,er5

    result < S=A4P6N74 > additional%ntropy 

    c.  8ey +eri9ation Fnction@o$e=erH the most im0ortant is not the nm,er o/ 0ossi,ilities. It is the time that an attacker $old

    need to sccess/ll' ,reak 'or ke'. -hat?s $here ;D enters the game.

    ;DH or ey ?erivation $unction is a $a' to ha=e a stronger ke'H e=en i/ 'or entro0' is lo$.

    Imagine that 'o $ant to generate a seedH and the attacker kno$s that there are "8.888.888

    0ossi,ilities.

    Sch a seed $old ,e normall' cracked 0rett' easil'.

    Bt $hat i/ 'o cold make the enmeration slo$er

    A ;D is a hash /nction that $aste com0ting resorces on 0r0ose.

    @ere is an eFam0le5

    ar deried ' SCrypt.BitcoinCompute>eried2ey"-hello-5 ne( 1yte#$ { )5 5 H 0%;/andom?tils.8ddDntropy"deried%; 

    >=en i/ 'or attacker kno$s that 'or sorce o/ entro0' is lettersH he $ill need to rn Scr'0t to

    check a 0ossi,ilit'H $hich take seconds on m' com0ter.

    Bottom line o/ the stor'5 -here is nothing 0aranoid into distrsting a P1N

  • 8/19/2019 Blockchain Programming in CSharp

    27/83

     

    #5Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    2. 8ey :ncry(tion

    In the 0re=ios 0art I talked +ickl' a,ot a s0ecial ;D called Scrypt. As I saidH the goal o/ a ;D is to

    make ,rte /orce costl'.

    So it shold ,e no sr0rise /or 'o that a standard alread' eFist /or encr'0ting 'or 0ri=ate ke' $ith a

    0ass$ord sing a ;D. -his is BIP3.

    ar key ' ne( 2ey"%;

    BitcoinSecret (i+ ' key.GetBitcoinSecret"9et(ork.!ain%;Console.,riteLine"(i+%;BitcoinDncryptedSecret encrypted ' (i+.Dncrypt"-secret-%;

    Console.,riteLine"encrypted%;(i+ ' encrypted.GetSecret"-secret-%;Console.,riteLine"(i+%; 

    4"3rr'!+ogBBdcD%k/sr+6m,S]ssUidBsro]dLaKmR/G-Sk>1d-301K,/=2-s

    4"3rr'!+ogBBdcD%k/sr+6m,

  • 8/19/2019 Blockchain Programming in CSharp

    28/83

     

    #6Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    3. 8ey ;eneration

    a.  ike the good ol< day!irstH $h' generating se=eral ke's

    -he main reason is 0ri=ac'. Since 'o can see the ,alance o/ all addressesH it is ,etter to se a ne$

    address /or each transaction.

    @o$e=erH in 0racticeH 'o can also generate ke's /or each contact. Becase this make a sim0le $a' to

    identi/' 'or 0a'er $ithot leaking too mch 0ri=ac'.

    Go can generate ke'H like 'o did /rom the ,eginning5

    ar key ' ne( 2ey"%; 

    @o$e=erH 'o ha=e t$o 0ro,lems $ith that5

    •  All ,ack0 o/ 'or $allet that 'o ha=e $ill ,ecome otdated $hen 'o generate a ne$ ke'.

      Go can?t delegate the address creation 0rocess to an ntrsted 0eerI/ 'o are de=elo0ing a $e, $allet and generate ke' on ,ehal/ o/ 'or sersH and one ser get hackH

    he $ill immediatel' start ss0ecting 'o.

    a.  B7P3, /(art 2e alread' sa$ BIP3 /or encr'0ting a ke'H ho$e=er this BIP is in realit' t$o ideas in one docment.

    -he second 0art o/ the BIPH sho$ ho$ 'o can delegate ;e' and Addresss creation to an ntrsted

    0eer. It $ill /iF one o/ or concern.

    -he idea is to generate a Passphrase'ode to the ke' generator. ith this Passphrase'odeH he $ill ,e

    a,le to generate >ncr'0ted ke's on 'or ,ehal/H $ithot kno$ing 'or 0ass$ordH nor an' 0ri=ateke'.

    -his Passphrase'ode can ,e gi=en to 'or ke' generator in I /ormat.

    Ti& /n NBitcoin, all tyes refi4ed by 'Bitcoin) are Base*6 =/F> data

    SoH as a ser that $ant to delegate ke' creationH /irst 'o $ill create the Passphrase'ode.

    BitcoinPassphraseCode passphraseCode ' ne( BitcoinPassphraseCode"-my secret-5

    9et(ork.!ain5 null%; 

  • 8/19/2019 Blockchain Programming in CSharp

    29/83

     

    #7Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Go then gi=e this passphrase'ode to 'or third 0art' ke' generator.

    -he ke' generator $ill then generate ne$ encr'0ted ke's /or 'o.

    Dncrypted2ey/esult encrypted2ey) ' passphraseCode.GenerateDncryptedSecret"%; 

    -his %ncryptedey6esult ha=e lots o/ in/ormation5

    irst5 the generated bitcoin addressH then an %ncryptedey as $e ha=e seen in the ey %ncryption 

    0artH and last ,t not the leastH the 'on,ir#ation'odeH so that the third 0art' can 0ro=e that the

    generated ke' and address corres0ond e//ecti=el' to 'or 0ass$ord.

    Dncrypted2ey/esult encrypted2ey) ' passphraseCode.GenerateDncryptedSecret"%;

    Console.,riteLine"encrypted2ey).Generated8ddress%;

    Console.,riteLine"encrypted2ey).Dncrypted2ey%;Console.,riteLine"encrypted2ey).Con+irmationCode%; 

    "P7@UASn]741oKrC6@nhsn,NtR+m>6o$FAeod6!'Rhh

  • 8/19/2019 Blockchain Programming in CSharp

    30/83

     

    $9Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    -re

    -re

    4tGncC1ai+-ggCa]0Cg,1d/=7NUr;7D6Rg+g]

    SoH $e ha=e 7st seen ho$ the third 0art' can generate encr'0ted ke' on 'or ,ehal/H $ithot

    kno$ing 'or 0ass$ord and 0ri=ate ke'.

    @o$e=erH one 0ro,lem remains5

    •  All ,ack0 o/ 'or $allet that 'o ha=e $ill ,ecome otdated $hen 'o generate a ne$ ke'H

    BIP 3%H or @ierarchical Deterministic allets (@D $allets) 0ro0oses another soltionH and is more

    $idel' s00orted.

    .  =+ Wallet /B7P 324et?s kee0 in mind the 0ro,lems that $e $ant to resol=e5

    •  Pre=ent otdated ,ack0s

    •  Delegating ke' Q address generation to an ntrsted 0eer

    A 9Deterministic: $allet $old /iF or ,ack0 0ro,lem.

    ith sch $alletH 'o $old ha=e to sa=e onl' the seed. rom this seedH 'o can generate the same

    series o/ 0ri=ate ke' o=er and o=er.

    -his is $hat the 9Deterministic: stands /or.

    As 'o can seeH /rom the master ke'H I can generate ne$ ke's5

  • 8/19/2019 Blockchain Programming in CSharp

    31/83

     

    $8Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Dxt2ey master2ey ' ne( Dxt2ey"%; Console.,riteLine"-!aster key 3 -  master2ey.ToString"9et(ork.!ain%%; +or "int i ' 4 ; i Q A ; i% {

    Dxt2ey key ' master2ey.>erie""uint%i%; Console.,riteLine"-2ey -  i - 3 -  key.ToString"9et(ork.!ain%%; 

    aster ke' 5

    F0r=6s%"]r@"!3;3KneCAikR!BsK!7Ud@C"DccAg/'%'G4A!L+-=]+Ci;LhN]Ld4@,sCs

    +B#sSLah/n4a7iBir!1FgdkNs#k

    ;e' 8 5

    F0r=6t=BA!;tU->&6#i'"PLP&&]P0&6/B>RC3g/-d7R0DR,AeLgD@hSmdnFS#@CL'c##c+-K1m%ka

    m7e>CC;R,iL'o;&]6ihi#2KKicga4U

    ;e' 3 5

    F0r=6t=BA!;tU-P$K'F]o#76hc>CoR2DA&4kR6t1$nBDi]gh&ePdD2et/i610&>&7;C$@

    =;$!i

    ;e' 5

    F0r=6t=BA!;tU--di>hNiDrr/APSsC;0Dia!s,2e@r'1=e1hke4>=o3L&43

  • 8/19/2019 Blockchain Programming in CSharp

    32/83

     

    $#Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    -he base58 t'0e e+i=alent o/ %&tey is called Bitcoin%&tey.

    Bt ho$ can $e sol=e or second 0ro,lem5 delegating address creation to a 0eer that can 0otentiall'

    ,e hacked (like a 0a'ment ser=er)

    -he trick is that 'o can 9neter: 'or master ke'H then 'o ha=e a 0,lic ($ithot 0ri=ate ke')

    =ersion o/ the master ke'. rom this netered =ersionH a third 0art' can generate 0,lic ke's $ithot

    kno$ing the 0ri=ate ke'.

    DxtPu12ey masterPu12ey ' master2ey.9euter"%;

    +or "int i ' 4 ; i Q A ; i%

    {DxtPu12ey pu1key ' masterPu12ey.>erie""uint%i%;

    Console.,riteLine"-Pu12ey -  i - 3 -  pu1key.ToString"9et(ork.!ain%%;0 

    P,;e' 8 5

    F0,2daCGA2N]/i2'3G"G%AiS7h1LU$$KKs4r

  • 8/19/2019 Blockchain Programming in CSharp

    33/83

     

    $$Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    master2ey ' ne( Dxt2ey"%;

    masterPu12ey ' master2ey.9euter"%;

    &&The payment serer generate pu1key) 

    DxtPu12ey pu1key) ' masterPu12ey.>erie""uint%)%;

    &&ou get the priate key o+ pu1key) Dxt2ey key) ' master2ey.>erie""uint%)%;

    &&Check it is legit Console.,riteLine"-Generated address 3 - 

    pu1key).Pu12ey.Get8ddress"9et(ork.!ain%%;Console.,riteLine"-Dxpected address 3 - 

    key).Priate2ey.Pu12ey.Get8ddress"9et(ork.!ain%%; 

  • 8/19/2019 Blockchain Programming in CSharp

    34/83

     

    $%Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    In this diagramH 'o can deri=ate Child("H") /rom 0arent in t$o di//erent $a'5

    Dxt2ey parent ' ne( Dxt2ey"%;Dxt2ey child)) ' parent.>erie")%.>erie")%; 

    r

    Dxt2ey parent ' ne( Dxt2ey"%;Dxt2ey child)) ' parent.>erie"ne( 2eyPath"-)&)-%%; 

    So in smmar'5

    It $orks the same /or %&tPubey.

    h' do 'o need hierarchical ke's Becase it might ,e a nice $a' to classi/' the t'0e o/ 'or ke's

    /or mlti accont 0r0ose. ore on BIP!!.

    It also 0ermit to segment accont rights across an organiRation.

    Imagine 'o are C> o/ a com0an'. Go $ant control o=er all $alletH ,t 'o don?t $ant that the

    Acconting de0artment s0end the mone' o/ the arketing de0artment.

  • 8/19/2019 Blockchain Programming in CSharp

    35/83

     

    $*Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    So 'or /irst idea $old ,e to generate one hierarch' /or each de0artment.

    @o$e=erH in sch caseH Accounting and Marketing $old ,e a,le to reco=er the C>?s 0ri=ate ke'.

    e de/ine sch child ke's as non@hardened.

    Dxt2ey ceo2ey ' ne( Dxt2ey"%; Console.,riteLine"-CD

  • 8/19/2019 Blockchain Programming in CSharp

    36/83

     

    $1Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    C>5

    F0r=6s%"]r@"!3;%LcKU6thgkBeha+=c7!AKF$Ps]R reco=ered5

    F0r=6s%"]r@"!3;%LcKU6thgkBeha+=c7!AKF$Ps]R shold create a hardened keyH so the acconting de0artment $ill not ,e a,le

    to clim,.

    Dxt2ey ceo2ey ' ne( Dxt2ey"%;

    Console.,riteLine"-CDerie"path%; 

    c.  >nemonic Code &or =+ 8ey! /B7P3As 'o ha=e seenH generating an @D ke's is eas'. @o$e=erH $hat i/ $e $ant as eas' $a' to transmit

    sch ke' ,' tele0hone or hand $riting

    Cold $allets like -reRorH generates the @D ;e's /rom a sentence that can easil' ,e $ritten do$n.

    -he' call sch sentence 9the seed: or 9mnemonic:. And it can e=entall' ,e 0rotected ,' a 0ass$ord

    or a PIN.

  • 8/19/2019 Blockchain Programming in CSharp

    37/83

  • 8/19/2019 Blockchain Programming in CSharp

    38/83

     

    $6Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    d.  +ark Wallet-his name is n/ortnate since there is nothing dark a,ot itH and it attract n$anted attention and

    $orries.

    Dark allet is a 0ractical soltion that /iF or t$o initial 0ro,lems5

    •  Pre=ent otdated ,ack0s•  Delegating ke' Q address generation to an ntrsted 0eer

    Bt it has a ,ons killer /eatre.

    Go ha=e to share onl' one address $ith the $orld (called StealthAddress)H $ithot leaking an'

    0ri=ac'.

    4et?s remind s that i/ 'o share one BitcoinAddress $ith e=er',od'H then all can see 'or ,alance

    ,' conslting the ,lockchainV -hat?s not the case $ith a StealthAddress. 

    -his is a real shame it $as la,eled as dark since it sol=es 0artiall' the im0ortant 0ro,lem o/ 0ri=ac'

    leaking cased ,' the 0sedo*anon'mit' o/ Bitcoin. A ,etter name $old ha=e ,een5 *ne Address.

    In Dark allet terminolog'H here are the di//erent actors5

    •  Scanner kno$s the Scan eyH a secret that allo$s him to detect the transactions that ,elong

    to the 6eceiver.

    •  -he 6eceiver kno$s the Spend eyH a secret that $ill allo$s him to s0end the coins he

    recei=es /rom one o/ sch transaction.

    •  -he Payer kno$s the StealthAddress o/ the 6eceiver 

    -he rest is o0erational details.

    UnderneathH this StealthAddress is com0osed o/ one or se=eral Spend Pubey (/or mlti sig)H and

    one Scan Pubey.

  • 8/19/2019 Blockchain Programming in CSharp

    39/83

     

    $7Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    ar scan2ey ' ne( 2ey"%;

    ar spend2ey ' ne( 2ey"%;

    BitcoinStealth8ddress stealth8ddress

    ' ne( BitcoinStealth8ddress 

    "

    scan2ey3 scan2ey.Pu12ey5

    pu12eys3 ne(#$ { spend2ey.Pu12ey 05signatureCount3 )5

    1it+ield3 null5

    net(ork3 9et(ork.!ain%; 

    -he payerH $ill take 'or StealthAddressH generate a tem0orar' ke' called %phe# ey and $ill

    generate a Stealth Pub eyH /rom $hich the Bitcoin address to $hich the 0a'ment $ill ,e done is

    generated.

    -henH he $ill 0ackage the %phe# Pubey in a Stealth Metadata o,7ect em,edded that in the

    PW1>-U1N o/ the transaction (as $e ha=e done /or the /irst challenge)

    @e $ill also add the ot0t to the generated ,itcoin address. (the address o/ the Stealth pub key)

    ar ephem2ey ' ne( 2ey"%;

    Transaction transaction ' ne( Transaction"%;

    stealth8ddress.SendTo"transaction5!oney.Coins").4m%5 ephem2ey%;Console.,riteLine"transaction%; 

    -he creation o/ the %phe#ey ,eing an im0lementation detailsH 'o can omit itH NBitcoin $ill

    generate one atomaticall'5

    Transaction transaction ' ne( Transaction"%;

    stealth8ddress.SendTo"transaction5 !oney.Coins").4m%%;

    Console.,riteLine"transaction%; 

  • 8/19/2019 Blockchain Programming in CSharp

    40/83

     

    %9Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    X

    V.

    JinJ5 EH

    JotJ5

    X

    J=aleJ5 J8.88888888JH

    Jscri0tP,;e'J5 JPW1>-U1N

    8888888888%""e2c3de6%6/2d,3!23/e!"/c3"8"d2a3ea!2e6/!",8d"cc2/a3/"6J

    YH

    X

    J=aleJ5 J".88888888JH

    Jscri0tP,;e'J5 JPWDUP PW@AS@"8 ,!3a,!%,,/c/d,,!e"ec6/"6%,,d"c36

    PW>UA4>1IG PWC@>C;SI

  • 8/19/2019 Blockchain Programming in CSharp

    41/83

     

    %8Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    -he code eF0laining ho$H as a ScannerH to scan a transaction and ho$H as a 1ecei=erH to nco=er the

    0ri=ate ke'H $ill ,e eF0lained later in the (ransactionBuilder 0art.

    It shold ,e noted that a StealthAddress can ha=e mlti0le spend pubkeysH in $hich caseH the

    address re0resent a mlti sig.

    ne limit o/ Dark allet is the se o/ *P)6%(6NH so $e can?t easil' em,ed ar,itrar' data in the

    transaction as $e ha=e done /or in Bitcoin -rans/er. (Crrent ,itcoin rles allo$s onl' one

    PW1>-U1N o/ !8 ,'tesH soon 8H 0er transaction)

  • 8/19/2019 Blockchain Programming in CSharp

    42/83

     

    %#Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    IV.  Other types of ownership

    1. P2P8=@ /Pay to Plic 8ey =a!h@

    In 0art % $e learned that a Bitcoin Address $as the hash o, a public key.e also learned that as /ar as the ,lockchain is concernedH there is no sch thing as a bitcoin

    address. -he ,lockchain identi/ies a recei=er $ith a ScriptPubeyH and sch ScriptPubey cold ,e

    generated /rom the address. (and =ice =ersa)

    2ey key ' ne( 2ey"%;

    Bitcoin8ddress address ' key.Pu12ey.Get8ddress"9et(ork.!ain%;

    Console.,riteLine"address.ScriptPu12ey%; 

    PWDUP PW@AS@"8 c,/",/d%,!6!3c883!!"a%6c8dee6 PW>UA4>1IG

    PWC@>C;SI<

    @o$e=erH all ScriptPubey does not re0resent a Bitcoin Address.

    @ere is an eFam0le o/ the /irst transaction in the ,lockchain. (-he genesis)

    Console.,riteLine"9et(ork.!ain.GetGenesis"%.Transactions#4$.ToString"%%; 

    X

    V

    JotJ5

    X

    J=aleJ5 J8.88888888JH

    Jscri0tP,;e'J5

    J8!2a/d,8/e!%2"62/"a2"38,2"8cda%e83686a26%e8ea"/"de,!6/,c3/!ce/3c!/3

    8!e"ec""%dec3!d/2,a8,d2a!c28%,,/""d/ PWC@>C;SI

  • 8/19/2019 Blockchain Programming in CSharp

    43/83

     

    %$Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    key ' ne( 2ey"%;

    Console.,riteLine"-Pay to pu1lic key 3 -  key.Pu12ey.ScriptPu12ey%;

    Console.,riteLine"%;Console.,riteLine"-Pay to pu1lic key hash 3 -  key.Pu12ey.7ash.ScriptPu12ey%; 

    Pa' to 0,lic ke' 5 8%/,8%",c2dedcc%/6a2e2cee"/ed,e!"d,/a263%"3%!!d/d/82%d!

    PWC@>C;SI<

    Pa' to 0,lic ke' hash 5 PWDUP PW@AS@"8 8ae!d!cec%,2%%d2%2c,28/!a,8a%82,%

    PW>UA4>1IG PWC@>C;SI<

    -hese % t'0es o/ 0a'ment are re/erred as P;P (0a' to 0,lic ke') and P;P= (0a' to 0,lic ke'

    hash).

    Satoshi decided to se P%P;@ instead o/ P%P; /or t$o reasons5

    •  >lli0tic Cr=e Cr'0togra0h'H the cr'0togra0h' sed ,' 'or public key and private key) is

    =lnera,le to a modi/ied ShorMs algorithm /or sol=ing the discrete logarithm 0ro,lem on

    elli0tic cr=es. In 0lain >nglishH it means thatH $ith a +antm com0terH in theor'H it is

    0ossi,le in some distant /tre to retrieve a private key ,ro# a public key.

    B' 0,lishing the 0,lic ke' onl' $hen the coin are s0endH sch attack is rendered

    ine//ecti=e. (assming addresses are not resed)

    •  -he hash ,eing smaller (%8 ,'tes)H it is smaller to 0rintH and easier to em,ed into small

    storage like a 1 code.

  • 8/19/2019 Blockchain Programming in CSharp

    44/83

  • 8/19/2019 Blockchain Programming in CSharp

    45/83

     

    %*Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Bitcoin8ddress nico ' ne( 2ey"%.Pu12ey.Get8ddress"9et(ork.!ain%;

    TransactionBuilder 1uilder ' ne( TransactionBuilder"%;

    Transaction unsigned '1uilder.8ddCoins"coin%

    .Send"nico5 !oney.Coins").4m%%

    .BuildTransaction"+alse%; 

    -he transaction is not crrentl' signed.

    @ere is ho$ Alice signs it.

    1uilder ' ne( TransactionBuilder"%;

    Transaction aliceSigned '

    1uilder.8ddCoins"coin%

    .8dd2eys"alice%

    .SignTransaction"unsigned%; 

    And then Satoshi

    1uilder ' ne( TransactionBuilder"%;

    Transaction satoshiSigned '

    1uilder.8ddCoins"coin%

    .8dd2eys"satoshi%

    .SignTransaction"unsigned%; 

  • 8/19/2019 Blockchain Programming in CSharp

    46/83

     

    %1Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    No$H Satoshi and Alice can com,ine their signatre into one transaction.

    1uilder ' ne( TransactionBuilder"%; Transaction +ullySigned ' 

    1uilder.8ddCoins"coin%

    .Com1ineSignatures"satoshiSigned5 aliceSigned%;

    Console.,riteLine"+ullySigned%; 

  • 8/19/2019 Blockchain Programming in CSharp

    47/83

     

    %5Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    X

    V.

    JinJ5

    X

    J0re=WotJ5 X

    JhashJ5 J6d/"e8""6!38,2%"8%%6a,ade6!dc6c!d%a,ee!2%ee2d%ea3c"JH

    JnJ5 8

    YH

    Jscri0tSigJ5 J8

    38!8%%"88a"!d!2c2%/e2c8!,!3%/23cde8,83,de6%!662,c6,ca3ea382,"a%8%%83e3

    dcc6,8,2/8a"3/d3"cd%36%!3/8/ca"a/c%!,3!%dd,6"/8"

    38!!8%%8!!c6/"8222cac"%c3c%8!2,e!%2e2d/!ed%d/,e323a%68%%8!ae2/da

    ada6,2a""c!e3%a836,",/68a,c"/3!/e%"8!"a!/2/"!/"d%8"J

    Y

    EH

    JotJ5

    X

    J=aleJ5 J".88888888JH

    Jscri0tP,;e'J5 JPWDUP PW@AS@"8 d!a8/c,!,c,/%/38ea,ed3daa238!/,26!d

    PW>UA4>1IG PWC@>C;SI

  • 8/19/2019 Blockchain Programming in CSharp

    48/83

     

    %6Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Don?t 'o think it $old ,e cool i/ $e cold to re0resent sch scriptPubey as easil' and com0actl'

    as a Bitcoin Address

    ellH this is 0ossi,le and it is called a Bitcoin Script Address also called Pa' to Scri0t @ash. (P%S@)

    No$ada'sH native Pay (o Multi Sig as 'o ha=e seen hereH and native P;PH are ne=er sed directl'

    as schH the' are $ra00ed into Pay (o Script =ash 0a'ment.

    3. P2"= /Pay $o "cri(t =a!h

    As seen 0re=iosl'H lti*Sig $orks easil' in codeH ho$e=erH ,e/ore 0%shH there $as no $a' to ask a

    cstomer to 0a' to a mlti*sig scriptPubey as easil' as $e cold hand him a Bitcoin Address.

    P;S=H or Pay (o Script =ashH is an eas' $a' to re0resent an' scriptPubey as a sim0le Bitcoin Script

    AddressH no matter ho$ com0licated it is.

    So let?s see $hat looked like the mlti sig $e created in the 0re=ios 0art.

    2ey 1o1 ' ne( 2ey"%;2ey alice ' ne( 2ey"%;

    2ey satoshi ' ne( 2ey"%;

    ar scriptPu12ey ' PayTo!ultiSigTemplate .6nstance

    .GenerateScriptPu12ey"5 ne(#$ { 1o1.Pu12ey5 alice.Pu12ey5 satoshi.Pu12ey 0%;

    Console.,riteLine"scriptPu12ey%; 

    % 8%%%"3c2"2%e6d//a%,!3a62c"/aa"a6!2/%2"28,/,"%c8c"d"

    83e6/23ca6%6dec6%de3"68cc!3286"!cd"3d388e3/d6c3d/ca3628e/,83%!,6"ec3d,%/%86,%82ce8e6a26%!2%d66""e8ac3/c"e,/c%ca23d 3

    PWC@>C;U4-ISI<

    Com0licated isn?t it

    InsteadH let?s see ho$ sch scriptPubey $old look like as a P;S= 0a'ment.

    2ey 1o1 ' ne( 2ey"%;

    2ey alice ' ne( 2ey"%;

    2ey satoshi ' ne( 2ey"%;

    Script redeemScript '

    PayTo!ultiSigTemplate .6nstance.GenerateScriptPu12ey"5 ne(#$ { 1o1.Pu12ey5 alice.Pu12ey5 satoshi.Pu12ey 0%;

    Console.,riteLine"redeemScript.7ash.ScriptPu12ey%; 

    PW@AS@"8 2,!"%e883!"a/8//cd/a,!d23,3%3!"68 PW>UA4

    Do 'o see the di//erence -his 0%sh scriptPubey re0resents the hash o/ m' mlti*sig scri0t.

    (redee#Script.=ash.ScriptPubey )

    Since it is a hashH 'o can easil' con=ert is as a ,ase string BitcoinScriptAddress.

  • 8/19/2019 Blockchain Programming in CSharp

    49/83

     

    %7Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    2ey 1o1 ' ne( 2ey"%;

    2ey alice ' ne( 2ey"%;

    2ey satoshi ' ne( 2ey"%;

    Script redeemScript '

    PayTo!ultiSigTemplate 

    .6nstance

    .GenerateScriptPu12ey"5 ne(#$ { 1o1.Pu12ey5 alice.Pu12ey5 satoshi.Pu12ey 0%;

    &&Console.,riteLine"redeemScript.7ash.ScriptPu12ey%; 

    Console.,riteLine"redeemScript.7ash.Get8ddress"9et(ork.!ain%%; 

    3>1=$4N/k@P'L3,+o=en i/ sch $allet does not nderstand $hat 9mlti

    sig: is.

    In P%S@ 0a'mentH $e re/er as the 6edee# ScriptH the scriptPubey that got hashed.

    Since the 0a'er onl' kno$s a,ot the =ash o, the 6edee#ScriptH he does not kno$ the 6edee#

    ScriptH and soH in or caseH don?t e=en ha=e to kno$ that he is sending mone' to a mlti sig o/

    Bo,QSatoshiQAlice.

    Signing sch transaction is similar to $hat $e ha=e done ,e/ore. -he onl' di//erence is that 'o ha=e

    to 0ro=ide the 6edee# Script $hen 'o ,ild the Coin /or the (ransactionBuilder.

    Imagine that the mlti sig P%S@ recei=e a coin in a transaction called received.

  • 8/19/2019 Blockchain Programming in CSharp

    50/83

     

    *9Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Script redeemScript '

    PayTo!ultiSigTemplate 

    .6nstance

    .GenerateScriptPu12ey"5 ne(#$ { 1o1.Pu12ey5 alice.Pu12ey5 satoshi.Pu12ey 0%;

    &&&&Console.,riteLine"redeemScript.7ash.ScriptPu12ey%; 

    &&Console.,riteLine"redeemScript.7ash.Get8ddress"9et(ork.!ain%%; 

    Transaction receied ' ne( Transaction"%;

    &&Pay to the script hash 

    receied.

  • 8/19/2019 Blockchain Programming in CSharp

    51/83

     

    *8Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Bitcoin8ddress address '

    Bitcoin8ddress.Create"-)2:k?F72*KgcmJ:*Lx*(cLA,>LIPB-%; ar 1irth ' Dncoding.?T:.GetBytes"-)&4I&)-%; ar 1irth7ash ' 7ashes.7ashA@"1irth%; Script redeemScript ' ne( Script" 

    -

  • 8/19/2019 Blockchain Programming in CSharp

    52/83

     

    *#Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    &&&&

  • 8/19/2019 Blockchain Programming in CSharp

    53/83

     

    *$Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    -he sage o/ the ,ilder is done in ! ste0s5

    •  Go gather the coins that s0entH•  Go gather the ke's that 'o o$nH

    •  Go enmerate ho$ mch mone' 'o $ant to send to $hat scri0tP,;e'H

    •  Go ,ild and sign the transactionH

    •  0tional5 'o gi=e the transaction to some,od' elseH then he $ill sign or contine to ,ild itH

    So let?s gather some coinsH /or that let?s create a /ake transaction $ith some /nds on it.

    4et?s sa' that the transaction has a P%P;@H P%P;H and mlti sig coin o/ Bo, and Alice.

  • 8/19/2019 Blockchain Programming in CSharp

    54/83

     

    *%Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    ar 1o1 ' ne( 2ey"%;

    ar alice ' ne( 2ey"%;

    ar 1o18lice ' PayTo!ultiSigTemplate 

    .6nstance

    .GenerateScriptPu12ey"5 1o1.Pu12ey5 alice.Pu12ey%;

    Transaction init ' ne( Transaction"%;init.

  • 8/19/2019 Blockchain Programming in CSharp

    55/83

     

    **Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    init ' ne( Transaction"%;init.Fce0t thatH i/ 'o remem,er or introdction on

    Dark alletH I said that 'o need a Scaney to see the Stealth'oin.

    4et?s create darkAliceBo, stealth address as in 0re=ios cha0ter5

    2ey scan2ey ' ne( 2ey"%;

    BitcoinStealth8ddress dark8liceBo1 '

    ne( BitcoinStealth8ddress "

    scan2ey3 scan2ey.Pu12ey5

    pu12eys3 ne(#$ { alice.Pu12ey5 1o1.Pu12ey 05

    signatureCount3 5

    1it+ield3 null5

    net(ork3 9et(ork.!ain

    %; 

    4et?s sa' someone sent this transaction5

  • 8/19/2019 Blockchain Programming in CSharp

    56/83

     

    *1Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    &&Someone sent to dark8liceBo1 

    init ' ne( Transaction"%;

    dark8liceBo1.SendTo"init5 !oney.Coins").4m%%; 

    -he scanner $ill detect the StealthCoin5

    &&Get the stealth coin (ith the scan2ey 

    StealthCoin stealthCoin' StealthCoin.:ind"init5 dark8liceBo15 scan2ey%; 

    And /or$ard it to ,o, and aliceH $ho $ill sign 5

    &&Spend it 

    tx ' 1uilder

    .8ddCoins"stealthCoin%

    .8dd2eys"1o15 alice5 scan2ey%

    .Send"satoshi5 !oney.Coins").4m%%

    .SetChange"1o18lice.7ash%

    .BuildTransaction"true%;Console.,riteLine"1uilder.Feri+y"tx%%; 

    -re

    Note& 2ou need the scaney for sendin( a !tealthCoin

  • 8/19/2019 Blockchain Programming in CSharp

    57/83

     

    *5Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    V. Other types of asset

    1. Colored Coin!

    In the 0re=ios cha0tersH $e ha=e seen se=eral t'0e o/ o$nershi0.Go ha=e seen all the di//erent kind o/ o$nershi0 and 0roo/ o/ o$nershi0H and nderstand ho$

    ,itcoin can ,e coded to in=ent ne$ kinds o/ o$nershi0.

    So ntil no$H 'o ha=e seen ho$ to eFchange Bitcoins on the net$ork. @o$e=er 'o can se the

    Bitcoin net$ork /or trans/erring and eFchanging an' t'0e o/ assets.

    e call sch assets 9colored coins:. As /ar as the Blockchain is concernedH there is no di//erence

    ,et$een a Coin and a Colored Coin.

    A colored coin is re0resented ,' a standard (&*ut. ost o/ the timeH sch (&*ut ha=e a residal

    Bitcoin =ale called 9Dst:. (88 satoshi)

    -he real =ale o/ a colored coin reside in $hat the issuer o/ the coin $ill eFchange against it.

    Since a colored coin is nothing ,t a standard coin $ith s0ecial meaningH it /ollo$s that all $hat 'o

    sa$ a,ot 0roo/ o/ o$nershi0 and the (ransactionBuilder sta's tre. Go can trans/er a colored coin

    $ith eFactl' the same rles as ,e/ore.

    As /ar as the ,lockchain is concernedH a 'olored 'oin is a 'oin like all others.

    Go can re0resent se=eral t'0e o/ asset $ith a colored coin5 com0an' sharesH ,ondsH stocksH =otes.

    Bt no matter $hat t'0e o/ asset 'o $ill re0resentH there $ill al$a's ha=e a trst relationshi0

    ,et$een the issuer o/ the asset and the o3ner.

    I/ 'o o$n some com0an' shareH then the com0an' might decide to not send 'o di=idends.

    I/ 'o o$n a ,onds and the ,ank might not eFchange it at matrit'.

    @o$e=erH a =iolation o/ contract might ,e atomaticall' detected $ith the hel0 o/ 6icardian

    'ontracts. A 6icardian 'ontract is a contract signed ,' the isser $ith the rights attached to the

    asset. Sch contract can ,e either hman reada,le (0d/)H ,t also strctred (7son)H so tools can

    atomaticall' 0ro=e an' =iolation. -he issuer can?t change the ricardian contract attached to anasset.

    -he Blockchain is onl' the trans0ort medim o/ a /inancial instrment.

    -he inno=ation is that e=er'one can create and trans/er its o$n asset $ithot intermediar'H $hereas

    traditional asset trans0ort medim (clearing hoses)H are either hea=il' reglatedH or 0r0ose/ll'

    ke0t secretH and closed to the general 0,lic.

    *pen Asset is the name o/ the 0rotocol created ,' la=ien Charlon that descri,es ho$ to trans,er 

    and e#it colored coins on the Blockchain.

    ther 0rotocols eFistH ,t 0en Asset is the most eas' and /leFi,le and the onl' one s00orted ,'

    NBitcoin.

  • 8/19/2019 Blockchain Programming in CSharp

    58/83

     

    *6Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    As the rest o/ the ,ookH I $ill not go in the details o/ the 0en Asset 0rotocolH the gith, 0age o/ the

    s0eci/ication is ,etter sited to this need.

    2.  7!!ing an 0!!et

    a.  Aecti9eor the 0r0ose o/ this eFerciseH I $ill emit BlockchainProgra##ingcoins.

    $ners o/ sch coins $ill ,e a,le to do$nload the Part 3 o/ this ,ook 7st ,' sending them ,ack to

    me.

    Don?t $orr'H the Part 3 $ill ,e a=aila,le /or e=er'oneH ,t /irst to o$ners o/ BlockchainProgra##ing 

    coins.

    I $ill send coins to 0eo0le that ga=e me a ti0H listed on the ,ook?s $e,site

    htt05QQ,lockchain0rogramming.aRre$e,sites.netQ 

    Go?ll get " coin e=er' -.--/ B(' 'o sent me T " coin i/ 'o added kind $ords.

    4et?s see ho$ I $old code sch /eatre.

    .  7!!ance CoinIn 0en AssetH the Asset ID is deri=ed /rom the isser ScriptPubey.

    I/ 'o $ant to isse a Colored CoinH 'o need to 0ro=e o$nershi0 o/ sch ScriptPubey. And the onl'

    $a' to do that on the Blockchain is ,' s0ending a coin ,elonging to sch ScriptPubey.

    -he coin that 'o $ill choose to s0end /or issing colored coins is called 9"ssuance 'oin: in NBitcoin.

    I $ant to emit an Asset /rom the ,ook ,itcoin address5 0$8kD=/;FGgc#H$/9&G/3c95!?92IPB .

    B' taking a look at m' ,alanceH I decided to se the /ollo$ing coin /or issing assets.

    X

    JtransactionIdJ5

    Je,!6a66c2!6c%d%!ca/6dd6c!e36%"d!6,,,8,6ddc"c6,c6%"!e!3,JH

    JindeFJ5 8H

    J=aleJ5 %888888H

    Jscri0tP,;e'J5 J2a6"!c"ee2,2//ca8!3,8a66%26,"2c6"6%acJH

    JredeemScri0tJ5 nll

    Y

    @ere is ho$ to create m' issance coin.

    ar coin ' ne( Coin"

    +romTx7ash3 ne( 

    uintA@"-e1*aAcI*cd*ca+dd@c*eHA@)d*11141d@dc)cA1c)*e*H1-%5

    +romecode>ata"-I@a)*c)eeI1I++ca4*H14aIA1)AIc@)Aac

    -%%%;

    ar issuance ' ne( 6ssuanceCoin"coin%; 

    No$ I need to ,ild transaction and sign the transaction $ith the hel0 o/ the (ransactionBuilder.

  • 8/19/2019 Blockchain Programming in CSharp

    59/83

     

    *7Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    ar nico ' Bitcoin8ddress.Create"-)As1Fp/h@dy,ycN!(PdxJ,>*x1+x/ee7e-%; ar 1ook2ey ' ne( BitcoinSecret"--%; TransactionBuilder 1uilder ' ne( TransactionBuilder"%; 

    ar tx ' 1uilder .8dd2eys"1ook2ey%

    .8ddCoins"issuance%

    .6ssue8sset"nico5 ne( 8sset!oney"issuance.8sset6d5 )4%% 

    .Send:ees"!oney.Coins"4.444)m%% 

    .SetChange"1ook2ey.Get8ddress"%%

    .BuildTransaction"true%; 

    Console.,riteLine"tx%; 

    X

    V

    JotJ5

    X

    J=aleJ5 J8.8888888JH

    Jscri0tP,;e'J5 JPWDUP PW@AS@"8 3/acdac/,cae66d"3e2,,!/d"e2d6

    PW>UA4>1IG PWC@>C;SI-U1N ot0t. In /actH this is the location $here in/ormation a,ot

    colored coins are st//ed.

    @ere is the /ormat o/ the data in the PW1>-U1N.

  • 8/19/2019 Blockchain Programming in CSharp

    60/83

     

    19Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    In or caseH antities ha=e onl' "8H $hich is the nm,er o/ Asset I issed to nico.

    etadata is ar,itrar' data. e $ill see that $e can 0t a rl that 0oint to an 9Asset De/inition:.

    An 9Asset ?e,inition: is a docment that descri,e $hat the Asset is. It is o0tionalH $e are not sing it

    in or case. (e?ll come ,ack later on it in the 1icardian Contract 0art)

    or more in/ormation check ot the 0en Asset S0eci/ication.

    -he transaction is read' to ,e sent on the net$ork5

    using "ar node ' 9ode.ConnectToLocal"9et(ork.!ain%% &&Connect to the node 

    {

    node.Fersion7andshake"%;&&Say hello &&8dertie your transaction "send Oust the hash% 

    node.Send!essage"ne( 6nPayload"6nentoryType.!SG=TK5 tx.Get7ash"%%%;

    &&Send it 

    node.Send!essage"ne( TxPayload"tx%%;Thread.Sleep"A44%; &&,ait a 1it 

    ' Bitcoin allet ha=e ,othH the ,ook address and the 9Nico: address.

    As 'o can seeH Bitcoin Core onl' sho$ the 8.888" B-C o/ /ees I 0aidH and ignore the 88 Satoshi coin

    ,ecase o/ s0am 0re=ention /eatre.

    -his classical ,itcoin $allet kno$s nothing a,ot Colored Coins.

    orse5 I/ a classical ,itcoin $allet s0end a colored coinH it $ill destro' the nderl'ing asset and

    trans/er onl' the ,itcoin =ale o/ the (&*ut. (88 satoshi)

    or 0re=enting a ser /rom sending Colored Coin to a $allet that do not s00ort itH 0en Asset ha=e

    its o$n address /ormatH that onl' colored coins $allets nderstand.

    nico ' Bitcoin8ddress.Create"-)As1Fp/h@dy,ycN!(PdxJ,>*x1+x/ee7e-%;

    Console.,riteLine"nico.ToColored8ddress"%%; 

  • 8/19/2019 Blockchain Programming in CSharp

    61/83

     

    18Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    ak+1+/dmAaL/PDm=]0cAn]m+rF!gc]

    No$H 'o can take a look on an 0en Asset com0ati,le $allet like Coin0rismH and see m' asset

    correctl' detected5

    As I ha=e told 'o ,e/oreH the Asset ID is deri=ed /rom the isser?s ScriptPubeyH here is ho$ to get it

    in code5

    ar 1ook ' Bitcoin8ddress.Create"-)2:k?F72*KgcmJ:*Lx*(cLA,>LIPB-%;

    ar asset6d ' ne( 8sset6d"1ook%.Get,i+"9et(ork.!ain%;

    Console.,riteLine"asset6d%; 

    AA/4S,";]/6tKRrU0kt7F;UL

  • 8/19/2019 Blockchain Programming in CSharp

    62/83

     

    1#Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    X

    JtransactionIdJ5 J/ad,2a%e!2/3aa8d"a22!cac6/a63e!6/d8c/c2e3!6ea!c,e!%JH

    JindeFJ5 8H

    J=aleJ5 88H

    Jscri0tP,;e'J5 J2a6"!3/acdac/,cae66d"3e2,,!/d"e2d6acJH

    JredeemScri0tJ5 nllH

    JassetIdJ5 JAA/4S,";]/6tKRrU0kt7F;ULata"-I@a)*HA@+ac

    dacA+A1caeAd)He@@I11A@*+d)eIdAac-%%%;Bitcoin8sset6d asset6d ' ne( Bitcoin8sset6d"-8F8F+LS1)2N+tJr?FpktOx2?KGx?T>*e-%;ColoredCoin colored ' coin.ToColoredCoin"asset6d5 )4%; 

    e?ll sho$ later ho$ 'o can se some $e, ser=ices or cstom code to get the coins more easil'.

    I also needed another coin (/orees)H to 0a' the /ees.

    -he asset trans/er is actall' =er' eas' $ith the (ransactionBuilder.

    ar 1ook ' Bitcoin8ddress.Create"-)2:k?F72*KgcmJ:*Lx*(cLA,>LIPB-%; ar nicoSecret ' ne( BitcoinSecret"--%; ar nico ' nicoSecret.Get8ddress"%; &&)As1Fp/h@dy,ycN!(PdxJ,>*x1+x/ee7e 

    ar +or:ees ' ne( Coin" +romTx7ash3 ne( 

    uintA@"-I+@e@ecHAAA))1H@ace4HIIa+11IHa*I1d+14Ic@1cHa@+a4cHe1a@-%5 +romecode>ata"-I@a)*HA@+acdacA+A1caeAd)He@@I11A@*+d)eIdAac

    -%%%; 

    TransactionBuilder 1uilder ' ne( TransactionBuilder"%; ar tx ' 1uilder 

    .8dd2eys"nicoSecret%

    .8ddCoins"colored5 +or:ees%

    .Send8sset"1ook5 ne( 8sset!oney"asset6d5 )4%% 

    .SetChange"nico%

    .Send:ees"!oney.Coins"4.444)m%% 

    .BuildTransaction"true%; Console.,riteLine"tx%; 

  • 8/19/2019 Blockchain Programming in CSharp

    63/83

     

    1$Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    X

    V.

    JotJ5

    X

    J=aleJ5 J8.88888888JH

    Jscri0tP,;e'J5 JPW1>-U1N !/!"8"888"8a88J

    YH

    X

    J=aleJ5 J8.8888888JH

    Jscri0tP,;e'J5 JPWDUP PW@AS@"8 c"ee2,2//ca8!3,8a66%26,"2c6"6%

    PW>UA4>1IG PWC@>C;SIUA4>1IG PWC@>C;SI

  • 8/19/2019 Blockchain Programming in CSharp

    64/83

     

    1%Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    4. nit te!t!

    Go can see that 0re=iosl' I hard coded the 0ro0erties o/ 'olored'oin.

    -he reason is that I $anted onl' to sho$ 'o ho$ to constrct a (ransaction ot o/ 'olored'oin 

    coins.

    In real li/eH 'o $old either de0ends on a third 0art' API to /etch the colored coins o/ a transaction

    or a ,alance. hich might ,e not a good ideaH ,ecase it add a trst de0endenc' to 'or 0rogram

    $ith the API 0ro=ider.

    NBitcoin allo$s 'o either to de0end on a $e, ser=iceH either to 0ro=ide 'or o$n im0lementation

    /or /etching the color o/ a (ransaction. -his allo$s 'o to ha=e a /leFi,le $a' to nit test 'or codeH

    se another?s im0lementation or 'or o$n.

    4et?s introdce t$o issers5 Sil=er and

  • 8/19/2019 Blockchain Programming in CSharp

    65/83

     

    1*Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Go can see that the 'olored(ransaction class $ill tell 'o5

      hich (&"n s0ends $hich Asset•  hich (&*ut emits $hich Asset

    •  hich (&*ut trans/ers $hich Asset

    Bt the method that interest s right no$ is $etch'olorH $hich $ill 0ermit 'o to eFtract colored

    in/ormation ot o/ the transaction 'o ga=e in in0t.

    Go see that it de0ends on a "'olored(ransaction6epository.

  • 8/19/2019 Blockchain Programming in CSharp

    66/83

     

    11Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    A "'olored(ransaction6epository is onl' a store that $ill gi=e 'o the 'olored(ransaction /rom the

    tFid. @o$e=er 'o can see that it de0ends on "(ransaction6epositoryH $hich ma0s a -ransaction id

    to its transaction.

    An im0lementation o/ "'olored(ransaction6epository is 'oinpris#'olored(ransaction6epository 

    $hich is a 0,lic API /or colored coins o0erations.

    @o$e=erH 'o can easil' do 'or o$nH here is ho$ $etch'olors $orks.

    -he sim0lest case is5 -he "'olored(ransaction6epository kno$s the colorH in sch case $etch'olors 

    onl' retrn that reslt.

    -he second case is that the "'olored(ransaction6epository does not kno$ an'thing a,ot the color

    o/ the transaction.

    So $etch'olors $ill need to com0te the color itsel/ according to the o0en asset s0eci/ication.

    @o$e=erH /or com0ting the colorH $etch'olors need the color o/ the 0arent transactions.

    So it /etch each o/ them on the "(ransaction6epositoryH and call $etch'olors on each o/ them.

    nce $etch'olors has resol=ed the color o/ the 0arent?s recrsi=el'H it com0te the transaction colorH

    and caches the reslt ,ack in the "'olored(ransaction6epository.

  • 8/19/2019 Blockchain Programming in CSharp

    67/83

     

    15Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    B' doing thatH /tre re+ests to /etch the color o/ a transaction $ill ,e resol=ed +ickl'.

    Some "'olored(ransaction6epository are read*onl' (like 'oinpris#'olored(ransaction6epository so

    the Pt o0eration is ignored)

    SoH ,ack to or eFam0le5

    -he trick $hen $riting nit tests is to se an in memor' "'olored(ransaction6epository5

    ar repo ' ne( 9oSqlColoredTransaction/epository"%; 

    No$H $e can 0t or init transaction inside.

    repo.Transactions.Put"init%; 

    Note that Pt is an eFtension methodsH so 'o $ill need to add

    using 9Bitcoin.

  • 8/19/2019 Blockchain Programming in CSharp

    68/83

     

    16Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    X

    Jin0tsJ5 EH

    JissancesJ5 EH

    Jtrans/ersJ5 EH

    JdestrctionsJ5 E

    Y

    As eF0ectedH the init transaction has no in0tsH issancesH trans/ers or destrctions o/ Colored Coins.

    So no$H let?s se the t$o coins sent to Sil=er and

  • 8/19/2019 Blockchain Programming in CSharp

    69/83

     

    17Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    X

    Jin0tsJ5 EH

    JissancesJ5

    X

    JindeFJ5 8H

    JassetJ5 JA->$a1SNeCgB7F7cr2Kt/'07+gAt4KsJH

    J+antit'J5 "8

    Y

    EH

    Jtrans/ersJ5 EH

    JdestrctionsJ5 E

    Y-his means that the /irst (&*ut ,ears "8 gold.

    No$ imagine that Satoshi $ants to send ! gold to Alice.

    irstl'H he $ill /etch the 'olored'oin ot o/ the transaction.

    ar goldCoin ' ColoredCoin.:ind"sendGoldToSatoshi5 color%.:irste+ault"%; 

    -henH ,ild a transaction like that5

    1uilder ' ne( TransactionBuilder"%; ar sendToBo18nd8lice ' 

    1uilder.8dd2eys"satoshi%

    .8ddCoins"goldCoin%

    .Send8sset"alice5 ne( 8sset!oney"gold6d5 *%% 

    .SetChange"satoshi% 

    .BuildTransaction"true%; 

    >Fce0t 'o $ill get the eFce0tion Not%nough$unds%&ception.

    -he reason is that the transaction is com0osed o/ 88 satoshi in in0t (the gold'oin)H and "%88

    satoshi in ot0t. (one (&*ut /or sending assets to AliceH and one /or sending ,ack the change to

    Satoshi)

    -his means that 'o are ot o/ 88 satoshi.

    Go can /iF the 0ro,lem ,' adding the last 'oin o/ " B-C in the init transaction that ,elongs to

    satoshi.

  • 8/19/2019 Blockchain Programming in CSharp

    70/83

     

    59Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    ar satoshiBtc ' init.

  • 8/19/2019 Blockchain Programming in CSharp

    71/83

     

    58Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    X

    V.

    JinJ5

    X

    J0re=WotJ5 X

    JhashJ5 J!""2/3e/!!/%d/d2e8,c3/!"/!/e6e%a3a%%"c6,38%e336c6/c3%eJH

    JnJ5 8

    YH

    Jscri0tSigJ5

    J38!8%%"883!%!38!6d!,,"3%e%c22333/3e"d2/,38ce2,a3d2,2a3cd,36!8%%82

    ea3d,2,!2,6a326dec!3d%2e6%3!ce8%da/"!ed86e2a862e8"

    83e%3%cda6"e2"682a6ede!c3ea"!"6e/,c"!a/d6/33"8,2,8%8d!,"J

    YHX

    J0re=WotJ5 X

    JhashJ5 Jae/a%%28666,aa8d2ddc2d%e"%!dd3%e"a26adda"82"d2dd8/JH

    JnJ5 %

    YH

    Jscri0tSigJ5

    J38!!8%%83!a38e,!ca%cc%a26c!d8",,a8c/!e!6c23a,,d"2/e"a3a8d/a!8%%8%e6/ 

    3d33/"/a%/,3",e!"%da3ce""83c/c!23%8832c,"/,e68"

    83e%3%cda6"e2"682a6ede!c3ea"!"6e/,c"!a/d6/33"8,2,8%8d!,"J

    Y

    EH

    JotJ5

    X

    J=aleJ5 J8.88888888JH

    Jscri0tP,;e'J5 JPW1>-U1N !/!"8"888%88!88J

    YH

    X

    J=aleJ5 J8.8888888JH

    Jscri0tP,;e'J5 JPWDUP PW@AS@"8 ,,!"cd%6/!e3,!,8/dcd8,6!!2dc/3%c!6d

    PW>UA4>1IG PWC@>C;SI

  • 8/19/2019 Blockchain Programming in CSharp

    72/83

     

    5#Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    YH

    X

    J=aleJ5 J8.66666!88JH

    Jscri0tP,;e'J5 JPWDUP PW@AS@"8 ,,!"cd%6/!e3,!,8/dcd8,6!!2dc/3%c!6d

    PW>UA4>1IG PWC@>C;SI$a1SNeCgB7F7cr2Kt/'07+gAt4Ks JH

    J+antit'J5 "8

    Y

    EH

    JissancesJ5 EH

    Jtrans/ersJ5

    X

    JindeFJ5 "H

    JassetJ5 J A->$a1SNeCgB7F7cr2Kt/'07+gAt4Ks JH

    J+antit'J5

    YH

    X

    JindeFJ5 %H

    JassetJ5 J A->$a1SNeCgB7F7cr2Kt/'07+gAt4Ks JH

    J+antit'J5 !Y

    EH

    JdestrctionsJ5 E

    Y

    e ha=e /inall' made a nit test that emit and trans/er some assets $ithot an' eFternal

    de0endencies.

    Go can make 'or o$n "'olored(ransaction6epository i/ 'o don?t $ant to de0end on a third 0art'

    ser=ice.

  • 8/19/2019 Blockchain Programming in CSharp

    73/83

     

    5$Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Go can /ind more com0leF scenarios in NBitcoin testsH and also one o/ m' article 9Bild them all: in

    code0ro7ect. (like mlti sig issance and colored coin s$a0s)

    %. )icardian contract!

    -his 0art is a co0' o/ an article I $rote on Coin0rism?s ,log. At the time o/ this $ritingH NBitcoin donot ha=e an' code related to 1icardian Contracts.

    a.  What i! a )icardian Contract

  • 8/19/2019 Blockchain Programming in CSharp

    74/83

     

    5%Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    It shold ,e noted that /rom Bitcoin 8."8H IsserScri0t is ar,itrar' and can ,e an'thing.

    -he 96icardian'ontract: can ,e ar,itrar'H and ke0t 0ri=ate. hoe=er hold the contract can 0ro=e

    that it a00lies to this Asset thanks to the hash in the Scri0tP,;e'.

    Bt let?s make sch 1icardianContract disco=era,le and =eri/ia,le ,' $allet clients $ith the Asset

    De/inition Protocol.

    4et?s assme $e are issing a oting token /or candidate AHB or C.

    4et?s add to the 0en Asset arkerH the /ollo$ing asset de/inition rl 5 htt05QQisser.comQcontract

    In the htt05QQisser.comQcontract 0ageH let?s create the /ollo$ing Asset De/inition ile 5

    X

    JIsserScri0tJ 5 IsserScri0tH

    JnameJ 5 J'AssetJH

    JcontractWrlJ 5 Jhtt05QQisser.comQreada,leContractJH

    JcontractWhashJ 5 JD;D;oceRi/e/ioIUIUI/oieR6868JH

    J-'0eJ 5 JoteJH

    JCandidatesJ 5 JAJHJBJHJCJEH

    Jalidit'J 5 J"8 7an %8"J

    Y

    And no$ $e can de/ine the 1icardianContract5

    1icardianContract AssetDe/initionile

    -his terminate or 1icardianContract im0lemented in A.

    c.  Check li!tA contract o,,ered by an issuer to holders

    -he contract is hosted ,' the isserH naltera,leH and signed e=er' time the Isser isses a ne$ assetH 

    ,or a valuable right held by holders+ and #anaged by the issuer+

    -he right in this sam0le is a =oting right /or candidate AHBHC to redeem ,e/ore "8 7an %8". 

    easily readable by people 4like a contract on paper+

    -he hman reada,le contract is in the contractWrlH ,t the KSN might ,e enogh. 

    readable by progra#s 4parsable like a database+

    -he details o/ the =ote are inside the Asset?e,inition$ileH in KSN /ormatH the athenticit' o/ the

    contract is =eri/ied ,' so/t$are $ith the "ssuerScriptH and the hash in the ScriptPubey. 

    digitally signed+

    -he ScriptPubey is signed $hen the isser isses the assetH thsH also the hash o/ the contractH and

    ,' eFtensionH the contract itsel/. 

    carries the keys and server in,or#ation

    "ssuerScript is inclded in the contract 

  • 8/19/2019 Blockchain Programming in CSharp

    75/83

  • 8/19/2019 Blockchain Programming in CSharp

    76/83

     

    51Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    4et?s start /nding some mone' to the 0o$erCoin addressH SatoshiH Alice and Bo,.

    ar po(erCoin ' ne( 2ey"%;

    ar alice ' ne( 2ey"%;ar 1o1 ' ne( 2ey"%;ar satoshi ' ne( 2ey"%;

    ar init ' ne( Transaction"%{

  • 8/19/2019 Blockchain Programming in CSharp

    77/83

     

    55Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    here 7et'oins is

    priate 6Dnumera1leQCoinU GetCoins"Transaction tx5 2ey o(ner%

    {

    return tx.

  • 8/19/2019 Blockchain Programming in CSharp

    78/83

     

    56Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    irstH I need to create some /nds /or voting'oin.

    ar otingCoin ' ne( 2ey"%;

    ar init ' ne( Transaction"%

    {

  • 8/19/2019 Blockchain Programming in CSharp

    79/83

     

    57Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    ar aliceFotingCoin ' ColoredCoin.:ind"toFoters5repo% .,here"c'Uc.ScriptPu12ey '' alice.ScriptPu12ey%

    .To8rray"%;

    1uilder ' ne( TransactionBuilder"%; ar toBo1 ' 

    1uilder

    .8ddCoins"aliceFotingCoin%

    .8dd2eys"alice%

    .Send8sset"1o15 ne( 8sset!oney"otingCoin5 )%% 

    .BuildTransaction"true%; repo.Transactions.Put"toBo1%; 

    Go can notice that there is no Set'hange the reason is that the in0t colored coin is s0ent entirel'H

    so nothing is le/t to ,e retrned.

    e.  otingImagine that Satoshi is too ,s' and decide not to =ote. No$ Bo, mst eF0ress his decision.

    -he =ote concerns $hether the com0an' shold ask /or a loan to the ,ank /or in=esting into ne$0rodction machines.

    Boss sa's on the com0an'?s $e,site5

    Send 'or coins to "@]$k7keao]/-SaKFD$a;kF0!agDi>RN /or 'es and to

    "3sAm]t$4AUn72d30=ts, /or no.

    Bo, decides that the com0an' shold take the loan5

    1uilder ' ne( TransactionBuilder"%; ar ote ' 

    1uilder

    .8ddCoins"1o1FotingCoin%

    .8dd2eys"1o1%

    .Send8sset"Bitcoin8ddress.Create"-)7N(kOkeaoN+TSaJx>(@a2kxp*Aag>iD9-%5 ne( 8sset!oney"otingCoin5 )%% 

    .BuildTransaction"true%; 

    No$ Boss can com0te the reslt o/ the =ote and see "*Ges 8*NoH Ges $inH so he takes the loan.

    >=er' 0artici0ants can also cont the reslt ,' themsel=es.

    &.  0lternati9e !e o& )icardian ContractIn the 0re=ios eFerciseH $e ha=e s00osed that Boss annonced the modalities o/ the =ote ot o/

    the BlockchainH on the com0an'?s $e,site.

    -his $orks greatH ,t Bo, need to kno$ that the $e,site eFists.

  • 8/19/2019 Blockchain Programming in CSharp

    80/83

     

    69Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    Another soltion is to 0,lish the modalities o/ the =ote directl' on the Blockchain $ithin an Asset

    ?e,inition $ileH so some so/t$are can atomaticall' get it and 0resent it to Bo,.

    -he onl' 0iece o/ code that $old ha=e changed is dring the issance o/ the oting Coins to =oters.

    issuance ' GetCoins"init5 otingCoin%.Select"c 'U ne( 6ssuanceCoin"c%%.To8rray"%; 

    issuance[0].DefinitionUrl = new Uri("http://boss.com/vote01.son"! 1uilder ' ne( TransactionBuilder"%; ar toFoters ' 

    1uilder.8ddCoins"issuance%

    .8dd2eys"otingCoin%

    .6ssue8sset"alice5 ne( 8sset!oney"otingCoin5 )%% 

    .6ssue8sset"satoshi5 ne( 8sset!oney"otingCoin5 )%% 

    .SetChange"otingCoin%

    .BuildTransaction"true%; repo.Transactions.Put"toFoters%; 

    In sch caseH Bo, can see that dring the issance o/ his =oting coinH an Asset ?e,inition $ile $as0,lishedH $hich is nothing more than a KSN docment $hose schema is 0artiall' s0eci/ied in 0en

    Asset.

    -he schema can ,e eFtended to ha=e in/ormation a,ot things like5

    •  >F0iration o/ the =ote

    •  Destination o/ the =otes /or each candidates

    •  @man /riendl' descri0tion o/ it

    @o$e=erH imagine that a hacker $ants to cheat the =ote. @e can al$a's modi/' the 7son docment

    (either man in the middle attackH 0h'sical access to ,oss.comH or access to Bo,?s machine) so Bo, is

    tricked and send his =ote to the $rong candidate.

    -rans/orming the Asset ?e,inition $ile into a 6icardian 'ontract ,' signing it $old make an'

    modi/ication immediatel' detecta,le ,' Bo,?s so/t$are. (See Proo/ / Athenticit' in the Asset

    De/inition Protocol)

    *. Proo& o& Brn and )e(tation

    -he +estion is sim0le5 in a P%P market $ere la$ en/orcement is too eF0ensi=eH ho$ 0artici0ants

    might minimiRe the 0ro,a,ilit' to get scammed

    0enBaaRar seems to ,e the /irst tr'ing to se 0roo/ o/ ,rn as a re0tation determinant.

    -here is se=eral res0onses to that (escro$ or notar'Qar,iter)H ,t one that $e $ill eF0lore here is

    called Proo/ / Brn.

    Imagine 'orsel/ in the middle ageH and 'o li=e in a small =illage $ith se=eral local merchants.

    ne da'H a tra=eling merchant comes to 'or =illage and sell 'o some goods at an n,elie=a,le lo$

    0rice com0ared to local one.

    @o$e=erH tra=eling merchant are $ell kno$n /or scamming 0eo0le $ith lo$ +alit' 0rodctH ,ecase

    losing re0tation is a small 0rice to 0a' /or them com0ared to local merchants.

    4ocal erchant in=ested into a nice storeH ad=ertising and their re0tation. Unha00' cstomers can

    easil' destro' them. Bt the tra=eling merchantH ha=ing no local store and onl' transient re0tationdon?t ha=e those incenti=es to not scam 0eo0le.

  • 8/19/2019 Blockchain Programming in CSharp

    81/83

     

    68Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    n the internetH $here the creation o/ an identit' is so chea0H all merchants are 0otentiall' as the

    tra=elling one /rom the middle age.

    -he soltion o/ market 0ro=iders $as to gather the real identit' o/ e=er' 0artici0ant in the marketH so

    la$ en/orcement ,ecome 0ossi,le.

    I/ 'o get scammed on AmaRon o/ >,a'H 'or ,ank $ill most likel' re/nd 'oH ,ecase the' ha=e a$a' to /ind the thie/ ,' contacting AmaRon and >,a'.

    In a 0rel' P%P market sing BitcoinH $e don?t ha=e that. I/ 'o get scamH 'o lose mone'.

    So ho$ a ,'er can trst the tra=eling merchant

    -he res0onse is5 ,' checking ho$ mch he in=ested into his re0tation.

    So as a good intentioned sellerH 'o $ant to ins0ire con/idence to 'or cstomer. or that 'o $ill

    destro' some o/ 'or $ealthH and e=er' cstomer $ill see. -his is the de/inition o/ 9in=esting into

    'or re0tation:.

    Imagine 'o ,rned 8 B-C /or 'or re0tation. And a cstomer $ant to ,' % B-C o/ goods /rom

    'o. @e has good reason to ,elie=e that 'o $ill not scam himH ,ecase 'o in=ested more into 'orre0tation that $hat 'o can get ot o/ him ,' scamming.

    It ,ecomes not economicall' 0ro/ita,le /or 'o to scam him.

    -he technical details $ill srel' =ar' and change o=er timeH ,t here is an eFam0le o/ Proo/ o/ Brn.

    ar alice ' ne( 2ey"%;

    &&Giing some money to alice ar init ' ne( Transaction"%

    {

    ataTemplate 

    .6nstance

    .GenerateScriptPu12ey"Dncoding.?T:.GetBytes"message%%;1urn.

  • 8/19/2019 Blockchain Programming in CSharp

    82/83

     

    6#Nicolas Dorier & Bill Strait

    CC (ASA 3U)

    X

    V.

    JinJ5

    X

    J0re=WotJ5 X

    JhashJ5 J822,2!8d,aa6cc"%d"6"6a6e!2c"dd3%a82,386!dde%aa"e6/JH

    JnJ5 8

    YH

    Jscri0tSigJ5

    J38!!8%%8%c622"!c6,3/26!e238e6!dd8""8c!,"!"e%%"3%!,a23"/62c!d//a,8%%82!%c"

    "d%e3dea!33e62a!c8ca!!e6a83c6e/68323!/,c%!,6!/,8"

    83/edc%/!/e/38cca/d2"c2%a23a6e,/,%"%%66ddc!!2/dd"%eea%cJ

    YEH

    JotJ5

    X

    J=aleJ5 J".88888888JH

    Jscri0tP,;e'J5 JPW1>-U1N !%22%e2!%8/2%%8%%!"c63%8!%",2%26%%J

    Y

    E

    Y

    nce in the BlockchainH this transaction is ndenia,le 0roo/ that Alice in=ested mone' /or her ,aker'.

    -he Coin $ith Scri0tP,;e' PW1>-U1N !%22%e2!%8/2%%8%%!"c63%8!%",2%26%%

    do not ha=e an' $a' to ,e s0entH so those coins are lost /ore=er.

    ,. Proo& o& ei!tence

  • 8/19/2019 Blockchain Programming in CSharp

    83/83

     

    VI.  Security

    1. $he challenge o& Bitcoin +e9elo(ment

    2. =ow to (ro9e a Coin ei!t! in the Blockchain

    3. =ow to (ro9e a Colored Coin ei!t! in the Blockchain

    4. Breaking tr!t relation!hi( with a third (arty 0P7

    %. Pre9enting >alleaility attack!

    '. Protecting yor (ri9ate key!