-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
402 lines (297 loc) · 18.4 KB
/
Program.cs
File metadata and controls
402 lines (297 loc) · 18.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
// ReSharper disable All
using System;
using System.Linq;
using System.Text;
using NBitcoin;
using NBitcoin.Crypto;
namespace _3._0OtherTypesOfOwnerships
{
class Program
{
static void Main()
{
//===========================================================================================
//Part5. Other types of ownership
//===========================================================================================
//Chapter1. P2PK[H] (Pay to Public Key [Hash])
//===========================================================================================
//Section1. P2PKH - Quick recap
//We learned that a Bitcoin address is generated by a public key hash and a network identifier.
Key privateKeyForPublicKeyHash = new Key();
var publicKeyHash = privateKeyForPublicKeyHash.PubKey.Hash;
var bitcoinAddress = publicKeyHash.GetAddress(Network.Main);
Console.WriteLine(publicKeyHash);
Console.WriteLine(bitcoinAddress);
//The Blockchain identifies a receiver by a ScriptPubKey.
//And such ScriptPubKey could be generated from a Bitcoin address.
var scriptPubKey = bitcoinAddress.ScriptPubKey;
Console.WriteLine(scriptPubKey);
//And vice versa.
//A Bitcoin address could be generated from a ScriptPubKey, but along with a network identifier.
var sameBitcoinAddress = scriptPubKey.GetDestinationAddress(Network.Main);
Console.WriteLine($"sameBitcoinAddress {sameBitcoinAddress}");
//==========================================================================================
//Section2. P2PK
Block genesisBlock = Network.Main.GetGenesis();
Transaction firstTransactionEver = genesisBlock.Transactions.First();
Console.WriteLine(firstTransactionEver);
var firstOutputEver = firstTransactionEver.Outputs.First();
var firstScriptPubKeyEver = firstOutputEver.ScriptPubKey;
Console.WriteLine(firstScriptPubKeyEver);
var firstBitcoinAddressEver = firstScriptPubKeyEver.GetDestinationAddress(Network.Main);
Console.WriteLine(firstBitcoinAddressEver == null);
var firstPublicKeyEver = firstScriptPubKeyEver.GetDestinationPublicKeys().First();
Console.WriteLine(firstPublicKeyEver);
var privateKeyForComparing = new Key();
Console.WriteLine("Pay To Public Key : " + privateKeyForComparing.PubKey.ScriptPubKey);
Console.WriteLine("Pay To Public Key Hash : " + privateKeyForComparing.PubKey.Hash.ScriptPubKey);
//============================================================================================
//Chapter2. P2WPKH(Pay to Witness Public Key Hash)
//=========================================================================================
//Chapter3. Multi-Sig
//Private key generator.
Key privateKeyGenerator = new Key();
BitcoinSecret bitcoinSecretFromPrivateKeyGenerator = privateKeyGenerator.GetBitcoinSecret(Network.Main);
Key privateKeyFromBitcoinSecret = bitcoinSecretFromPrivateKeyGenerator.PrivateKey;
Console.WriteLine($"privateKeyFromBitcoinSecret.ToString(Network.Main): {privateKeyFromBitcoinSecret.ToString(Network.Main)}");
//L5DZpEdbDDhhk3EqtktmGXKv3L9GxttYTecxDhM5huLd82qd9uvo is for Alice
//KxMrK5EJeUZ1z3Jyo2zPkurRVtYFefab4WQitV5CyjKApHsWfWg9 is for Bob
//KyStsAHgSehHvewS5YfGwhQGfEWYd8qY2XZg6q2M6TqaM8Q8rayg is for Satoshi
//L2f9Ntm8UUeTLZFv25oZ8WoRW8kAofUjdUdtCq9axCp1hZrsLZja is for Nico
BitcoinSecret bitcoinSecretForAlice = new BitcoinSecret("L5DZpEdbDDhhk3EqtktmGXKv3L9GxttYTecxDhM5huLd82qd9uvo", Network.Main);
BitcoinSecret bitcoinSecretForBob = new BitcoinSecret("KxMrK5EJeUZ1z3Jyo2zPkurRVtYFefab4WQitV5CyjKApHsWfWg9", Network.Main);
BitcoinSecret bitcoinSecretForSatoshi = new BitcoinSecret("KyStsAHgSehHvewS5YfGwhQGfEWYd8qY2XZg6q2M6TqaM8Q8rayg", Network.Main);
BitcoinSecret bitcoinSecretForNico = new BitcoinSecret("L2f9Ntm8UUeTLZFv25oZ8WoRW8kAofUjdUdtCq9axCp1hZrsLZja", Network.Main);
Key bobPrivateKey = bitcoinSecretForAlice.PrivateKey;
Key alicePrivateKey = bitcoinSecretForBob.PrivateKey;
Key satoshiPrivateKey = bitcoinSecretForSatoshi.PrivateKey;
Key nicoPrivateKey = bitcoinSecretForNico.PrivateKey;
Console.WriteLine($"bobPrivateKey.PubKey {bobPrivateKey.PubKey}");
Console.WriteLine($"alicePrivateKey.PubKey {alicePrivateKey.PubKey}");
Console.WriteLine($"satoshiPrivateKey.PubKey {satoshiPrivateKey.PubKey}");
Console.WriteLine($"nicoPrivateKey.PubKey {nicoPrivateKey.PubKey}");
var scriptPubKeyByMultiSig = PayToMultiSigTemplate
.Instance
.GenerateScriptPubKey(2, new PubKey[]
{
bobPrivateKey.PubKey,
alicePrivateKey.PubKey,
satoshiPrivateKey.PubKey
});
Console.WriteLine(scriptPubKeyByMultiSig);
Console.WriteLine($"scriptPubKeyByMultiSig.Hash: {scriptPubKeyByMultiSig.Hash}");
//Imagine the multi-sig scriptPubKeyByMultiSig received a coin in a transaction called received:
var received = new Transaction();
received.Outputs.Add(new TxOut(Money.Coins(1.0m), scriptPubKeyByMultiSig));
//First they get the Coin they received from the transaction.
Coin coin = received.Outputs.AsCoins().First();
//First get a one Bitcoin address for Nico to which they will send the coin.
BitcoinAddress nicoBitcoinAddress = nicoPrivateKey.PubKey.GetAddress(Network.Main);
//Then, with the TransactionBuilder, they create an unsigned transaction.
TransactionBuilder builder = new TransactionBuilder();
Transaction unsigned =
builder
.AddCoins(coin)
.Send(nicoBitcoinAddress, Money.Coins(1.0m))
.BuildTransaction(sign: false);
//The transaction is not yet signed. Here is how Alice signs it.
Transaction aliceSigned =
builder
.AddCoins(coin)
.AddKeys(alicePrivateKey)
.SignTransaction(unsigned);
//And then Bob.
Transaction bobSigned =
builder
.AddCoins(coin)
.AddKeys(bobPrivateKey)
//At this line, SignTransaction(unSigned) has the identical functionality with the SignTransaction(aliceSigned).
//It's because unsigned transaction has already been signed by Alice private key from above.
.SignTransaction(unsigned);
//Now, Bob and Alice can combine their signature into one transaction. This transaction will then be valid in terms of its signature as Bob and Alice have provided two of the signatures from the three owner signatures that were initially provided. The requirements of the 'two-of-three' multi sig have therefore been met.
Transaction fullySigned =
builder
.AddCoins(coin)
.CombineSignatures(aliceSigned, bobSigned);
Console.WriteLine(fullySigned);
//Let's look at the case that CombineSignatures() is required:
TransactionBuilder builderNew = new TransactionBuilder();
TransactionBuilder builderForAlice = new TransactionBuilder();
TransactionBuilder builderForBob = new TransactionBuilder();
Transaction unsignedNew =
builderNew
.AddCoins(coin)
.Send(nicoBitcoinAddress, Money.Coins(1.0m))
.BuildTransaction(sign: false);
Transaction aliceSignedNew =
builderForAlice
.AddCoins(coin)
.AddKeys(alicePrivateKey)
.SignTransaction(unsignedNew);
Console.WriteLine(aliceSignedNew);
Transaction bobSignedNew =
builderForBob
.AddCoins(coin)
.AddKeys(bobPrivateKey)
.SignTransaction(unsignedNew);
Console.WriteLine(bobSignedNew);
//In this case, the CombineSignatures() method is essentially needed.
Transaction fullySignedNew =
builderNew
.AddCoins(coin)
.CombineSignatures(aliceSigned, bobSigned);
Console.WriteLine(fullySignedNew);
//========================================================================================
//Chapter4. P2SH(Pay To Script Hash)
//In the previous part we generated this multi-sig:
//Key bobPrivateKey = new Key();
//Key alicePrivateKey = new Key();
//Key satoshiPrivateKey = new Key();
//var scriptPubKeyByMultiSig = PayToMultiSigTemplate
// .Instance
// .GenerateScriptPubKey(2, new[] { bobPrivateKey.PubKey, alicePrivateKey.PubKey, satoshiPrivateKey.PubKey });
//Console.WriteLine(scriptPubKeyByMultiSig);
//Output:
//2 0282213c7172e9dff8a852b436a957c1f55aa1a947f2571585870bfb12c0c15d61 036e9f73ca6929dec6926d8e319506cc4370914cd13d300e83fd9c3dfca3970efb 0324b9185ec3db2f209b620657ce0e9a792472d89911e0ac3fc1e5b5fc2ca7683d 3 OP_CHECKMULTISIG
//Complicated isn’t it?
//Instead, let’s see how such a scriptPubKeyByMultiSig would look in a P2SH payment.
//Key bobPrivateKey = new Key();
//Key alicePrivateKey = new Key();
//Key satoshiPrivateKey = new Key();
//Note that PaymentScript property is appended after a GenerateScriptPubKey() method.
var scriptPubKeyByP2sh = PayToMultiSigTemplate
.Instance
.GenerateScriptPubKey(2, new[] { bobPrivateKey.PubKey, alicePrivateKey.PubKey, satoshiPrivateKey.PubKey }).PaymentScript;
Console.WriteLine($"scriptPubKeyByP2sh: {scriptPubKeyByP2sh}");
//Since it is a hash, you can easily convert it to a base58 string BitcoinScriptAddress.
//Key bobPrivateKey = new Key();
//Key alicePrivateKey = new Key();
//Key satoshiPrivateKey = new Key();
Script redeemScriptPubKey =
PayToMultiSigTemplate
.Instance
.GenerateScriptPubKey(2, new[] { bobPrivateKey.PubKey, alicePrivateKey.PubKey, satoshiPrivateKey.PubKey });
Console.WriteLine($"redeemScriptPubKey.Hash.ScriptPubKey: {redeemScriptPubKey.Hash.ScriptPubKey}");
Console.WriteLine($"scriptPubKeyByP2sh: {scriptPubKeyByP2sh}");
Console.WriteLine(redeemScriptPubKey.Hash.GetAddress(Network.Main));
Console.WriteLine($"redeemScript.Hash: {redeemScriptPubKey.Hash}");
//Imagine that the multi-sig P2SH receives a coin in a transaction called received.
Script redeemScriptPubKeyForP2shPayment =
PayToMultiSigTemplate
.Instance
.GenerateScriptPubKey(
2,
new[] { bobPrivateKey.PubKey, alicePrivateKey.PubKey, satoshiPrivateKey.PubKey });
var receivedForP2shPayment = new Transaction();
receivedForP2shPayment.Outputs.Add(
new TxOut(Money.Coins(1.0m),
redeemScriptPubKeyForP2shPayment.Hash));
ScriptCoin scriptCoinForP2shPayment = receivedForP2shPayment
.Outputs
.AsCoins()
.First()
.ToScriptCoin(redeemScriptPubKeyForP2shPayment);
//Create TransactionBuilder.
TransactionBuilder builderForP2shPayment = new TransactionBuilder();
TransactionBuilder builderForP2shPaymentForAlice = new TransactionBuilder();
TransactionBuilder builderForP2shPaymentForBob = new TransactionBuilder();
Transaction unsignedForP2shPayment =
builderForP2shPayment
.AddCoins(scriptCoinForP2shPayment)
.Send(nicoBitcoinAddress, Money.Coins(1.0m))
.BuildTransaction(sign: false);
Transaction aliceSignedForP2shPayment =
builderForP2shPaymentForAlice
.AddCoins(scriptCoinForP2shPayment)
.AddKeys(alicePrivateKey)
.SignTransaction(unsignedForP2shPayment);
Transaction bobSignedForP2shPayment =
builderForP2shPaymentForBob
.AddCoins(scriptCoinForP2shPayment)
.AddKeys(bobPrivateKey)
.SignTransaction(unsignedForP2shPayment);
Transaction fullySignedForP2shPayment =
builderForP2shPaymentForBob
.AddCoins(scriptCoinForP2shPayment)
.CombineSignatures(aliceSignedForP2shPayment, bobSignedForP2shPayment);
Console.WriteLine($"fullySignedForP2shPayment: {fullySignedForP2shPayment}");
//==========================================================================================
//Chapter5. P2WSH(Pay To Witness Script Hash)
//That you can print with the following code:
var privateKeyForP2wsh = new Key();
var scriptPubKeyForP2wsh = privateKeyForP2wsh.PubKey.ScriptPubKey.WitHash.ScriptPubKey;
Console.WriteLine($"scriptPubKeyForP2wsh: {scriptPubKeyForP2wsh}");
//==========================================================================================
//Chapter6. P2W* over P2SH
//Printing the ScriptPubKey:
var privateKeyForP2shP2wpkh = new Key();
Console.WriteLine(privateKeyForP2shP2wpkh.PubKey.WitHash.ScriptPubKey.Hash.ScriptPubKey);
Console.WriteLine($"privateKeyForP2shP2wpkh.PubKey.WitHash.ScriptPubKey.Hash.ScriptPubKey: {privateKeyForP2shP2wpkh.PubKey.WitHash.ScriptPubKey.Hash.ScriptPubKey}");
//Let’s print the scriptPubKey by following the first rule:
//1.Replacing the ScriptPubKey by its P2SH equivalent.
var privateKeyForP2shP2wpkhEx = new Key();
Console.WriteLine(privateKeyForP2shP2wpkhEx.PubKey.ScriptPubKey.WitHash.ScriptPubKey.Hash.ScriptPubKey);
//2.The former ScriptPubKey will be placed as the only push in the scriptSig in the spending transaction.
//3.All other data will be pushed in the witness of the spending transaction.
//=========================================================================================
//Chapter7. Arbitrary
//So first, let’s build the RedeemScript,
BitcoinAddress bitcoinAddressOfThisBook = BitcoinAddress.Create("1KF8kUVHK42XzgcmJF4Lxz4wcL5WDL97PB");
var birthDate = Encoding.UTF8.GetBytes("18/07/1988");
var birthDateHash = Hashes.Hash256(birthDate);
var redeemScriptPubKeyForSendingCoinToBook = new Script(
"OP_IF "
+ "OP_HASH256 " + Op.GetPushOp(birthDateHash.ToBytes()) + " OP_EQUAL " +
"OP_ELSE "
+ bitcoinAddressOfThisBook.ScriptPubKey + " " +
"OP_ENDIF");
//Let’s say I sent money with such redeemScriptPubKeyForSendingCoinToBook:
var txForSendingCoinToBook = new Transaction();
txForSendingCoinToBook.Outputs.Add(
new TxOut(Money.Parse("0.0001"),
redeemScriptPubKeyForSendingCoinToBook.Hash));
var scriptCoinForSendingToBook = txForSendingCoinToBook
.Outputs
.AsCoins()
.First()
.ToScriptCoin(redeemScriptPubKeyForSendingCoinToBook);
//So let’s create a transaction that want to spend such output:
Transaction txSpendingCoinOfThisBook = new Transaction();
txSpendingCoinOfThisBook.AddInput(new TxIn(new OutPoint(txForSendingCoinToBook, 0)));
//Option 1 : Spender knows my birth date.
Op pushBirthdate = Op.GetPushOp(birthDate);
//Go to IF.
Op selectIf = OpcodeType.OP_1;
Op redeemBytes = Op.GetPushOp(redeemScriptPubKeyForSendingCoinToBook.ToBytes());
Script scriptSig = new Script(pushBirthdate, selectIf, redeemBytes);
txSpendingCoinOfThisBook.Inputs[0].ScriptSig = scriptSig;
//Verify the script pass
var verificationByBirthDate = txSpendingCoinOfThisBook
.Inputs
.AsIndexedInputs()
.First()
.VerifyScript(txForSendingCoinToBook.Outputs[0].ScriptPubKey);
Console.WriteLine(verificationByBirthDate);
//Output:
//True
//Option 2 : Spender knows my private key.
//BitcoinSecret privateKeyRelatedToTheBookBitcoinAddress = new BitcoinSecret("PrivateKeyRepresentedInBase58StringRelatedToTheBookBitcoinAddress");
//var sig = txSpendingCoinOfThisBook.SignInput(privateKeyRelatedToTheBookBitcoinAddress, scriptCoinForSendingToBook);
//var p2pkhProof = PayToPubkeyHashTemplate
// .Instance
// .GenerateScriptSig(sig, privateKeyRelatedToTheBookBitcoinAddress.PrivateKey.PubKey);
////Go to IF.
//selectIf = OpcodeType.OP_0;
//scriptSig = p2pkhProof + selectIf + redeemBytes;
//txSpendingCoinOfThisBook.Inputs[0].ScriptSig = scriptSig;
//Verify the script pass
var verificationByPrivateKey = txSpendingCoinOfThisBook
.Inputs
.AsIndexedInputs()
.First()
.VerifyScript(txForSendingCoinToBook.Outputs[0].ScriptPubKey);
Console.WriteLine(verificationByPrivateKey);
Console.ReadLine();
}
}
}