-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
UnitTestBase.cs
477 lines (408 loc) · 18 KB
/
UnitTestBase.cs
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
using Hardwarewallets.Net;
using Hardwarewallets.Net.AddressManagement;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Nethereum.Hex.HexConvertors.Extensions;
using Nethereum.RLP;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Numerics;
using System.Threading.Tasks;
using Trezor.Net.Contracts.Bitcoin;
using Trezor.Net.Contracts.Ethereum;
using Trezor.Net.Manager;
using static Trezor.Net.Contracts.Bitcoin.TxAck;
namespace Trezor.Net
{
[TestClass]
public abstract partial class UnitTestBase
{
#region Fields
//This must remain static for persistenance across tests
protected static TrezorManager TrezorManager;
private readonly string[] _Addresses = new string[50];
private TrezorManagerBroker _TrezorManagerBroker;
#endregion
#region Protected Abstract Methods
protected abstract Task<string> GetPin();
protected abstract Task<string> GetPassphrase();
#endregion
#region Protected Virtual Methods
protected virtual async Task<TrezorManager> ConnectAsync()
{
_TrezorManagerBroker = new TrezorManagerBroker(GetPin, GetPassphrase, 2000, new DefaultCoinUtility());
return await _TrezorManagerBroker.WaitForFirstTrezorAsync();
}
#endregion
#region Helpers
private async Task<string> GetAddressAsync(uint index)
{
return await GetAddressAsync(true, 0, false, index, false);
}
private async Task<string> GetAddressAsync(uint coinNumber, bool display)
{
var coinInfo = TrezorManager.CoinUtility.GetCoinInfo(coinNumber);
var address = await GetAddressAsync(coinInfo.IsSegwit, coinInfo.CoinType, false, 0, display);
return address;
}
private async Task<string> GetAddressAsync(bool isSegwit, uint coinNumber, bool isChange, uint index, bool display, string coinName = null, bool isPublicKey = false)
{
var addressPath = new BIP44AddressPath(isSegwit, coinNumber, 0, isChange, index);
var firstAddress = await TrezorManager.GetAddressAsync(addressPath, isPublicKey, display);
var addressPathString = $"m/{(isSegwit ? 49 : 44)}'/{coinNumber}'/{(isChange ? 1 : 0)}'/{0}/{index}";
var secondAddress = await GetAddressAsync(addressPathString);
Assert.IsTrue(firstAddress == secondAddress, "The parsed version of the address path yielded a different result to the non-parsed version");
return secondAddress;
}
private async Task<string> GetAddressAsync(string addressPath, bool display = false, string coinName = null, bool isPublicKey = false)
{
var bip44AddressPath = AddressPathBase.Parse<BIP44AddressPath>(addressPath);
//TODO: Duplicate code here
var address = await TrezorManager.GetAddressAsync(bip44AddressPath, isPublicKey, display);
Assert.IsTrue(!string.IsNullOrEmpty(address), $"The address was null or empty. Path: {addressPath}");
Console.WriteLine(address);
return address;
}
private async Task DoGetAddress(uint i)
{
var address = await GetAddressAsync(i);
_Addresses[i] = address;
}
#endregion
#region Setup / Teardown
[TestInitialize]
public async Task GetAndInitializeAsync()
{
if (TrezorManager != null)
{
return;
}
TrezorManager = await ConnectAsync();
}
[TestCleanup]
public void Cleanup()
{
//TODO: We should dispose of the TrezorManager here, but this is called after every test...
//TrezorManager.Dispose();
}
#endregion
#region Tests
[TestMethod]
public async Task SignBitcoinTransactionAsync()
{
//get address path for address in Trezor
var addressPath = AddressPathBase.Parse<BIP44AddressPath>("m/49'/0'/0'/0/0").ToArray();
// previous unspent input of Transaction
var txInput = new TxAck.TransactionType.TxInputType()
{
AddressNs = addressPath,
Amount = 100837,
ScriptType = InputScriptType.Spendp2shwitness,
PrevHash = "797ad8727ee672123acfc7bcece06bf648d3833580b1b50246363f3293d9fe20".ToHexBytes(), // transaction ID
PrevIndex = 0,
Sequence = 4294967293 // Sequence number represent Replace By Fee 4294967293 or leave empty for default
};
// TX we want to make a payment
var txOut = new TxAck.TransactionType.TxOutputType()
{
AddressNs = new uint[0],
Amount = 100837,
Address = "34i58jxXbcjHbHmo1Pdzx8UjqLphZuG8c1",
ScriptType = TxAck.TransactionType.TxOutputType.OutputScriptType.Paytoaddress // if is segwit use Spendp2shwitness
};
// Must be filled with basic data like below
var signTx = new SignTx()
{
//Expiry = 0,
LockTime = 0,
CoinName = "Bitcoin",
Version = 2,
OutputsCount = 1,
InputsCount = 1
};
// For every TX request from Trezor to us, we response with TxAck like below
var txAck = new TxAck()
{
Tx = new TxAck.TransactionType()
{
Inputs = { txInput }, // Tx Inputs
Outputs = { txOut }, // Tx Outputs
//Expiry = 0,
InputsCnt = 1, // must be exact number of Inputs count
OutputsCnt = 1, // must be exact number of Outputs count
Version = 2,
}
};
// If the field serialized.serialized_tx from Trezor is set,
// it contains a chunk of the signed transaction in serialized format.
// The chunks are returned in the right order and just concatenating all returned chunks will result in the signed transaction.
// So we need to add chunks to the list
var serializedTx = new List<byte>();
// We send SignTx() to the Trezor and we wait him to send us Request
var request = await TrezorManager.SendMessageAsync<TxRequest, SignTx>(signTx);
// We do loop here since we need to send over and over the same transactions to trezor because his 64 kilobytes memory
// and he will sign chunks and return part of signed chunk in serialized manner, until we receive finall type of Txrequest TxFinished
while (request.request_type != TxRequest.RequestType.Txfinished)
{
switch (request.request_type)
{
case TxRequest.RequestType.Txinput:
{
//We send TxAck() with TxInputs
request = await TrezorManager.SendMessageAsync<TxRequest, TxAck>(txAck);
// Now we have to check every response is there any SerializedTx chunk
if (request.Serialized != null)
{
// if there is any we add to our list bytes
serializedTx.AddRange(request.Serialized.SerializedTx);
}
break;
}
case TxRequest.RequestType.Txoutput:
{
//We send TxAck() with TxOutputs
request = await TrezorManager.SendMessageAsync<TxRequest, object>(txAck);
// Now we have to check every response is there any SerializedTx chunk
if (request.Serialized != null)
{
// if there is any we add to our list bytes
serializedTx.AddRange(request.Serialized.SerializedTx);
}
break;
}
case TxRequest.RequestType.Txextradata:
{
// for now he didn't ask me for extra data :)
break;
}
case TxRequest.RequestType.Txmeta:
{
/*
def copy_tx_meta(tx):
tx_copy = messages.TransactionType(**tx)
# clear fields
tx_copy.inputs_cnt = len(tx.inputs)
tx_copy.inputs = []
tx_copy.outputs_cnt = len(tx.bin_outputs or tx.outputs)
tx_copy.outputs = []
tx_copy.bin_outputs = []
tx_copy.extra_data_len = len(tx.extra_data or b"")
tx_copy.extra_data = None
return tx_copy
*/
//This code is converted from Trezor.py here:
//https://github.com/trezor/python-trezor/blob/2813522b05cef4e0e545a101f8b3559a3183b45b/trezorlib/btc.py#L161
TransactionType transactionType = new TransactionType { };
transactionType.InputsCnt = (uint)txAck.Tx.Inputs.Count;
transactionType.OutputsCnt = (uint)txAck.Tx.Outputs.Count;
if (txAck.Tx?.ExtraData != null)
{
transactionType.ExtraDataLen = (uint)txAck.Tx.ExtraData.Length;
}
var txRequest = await TrezorManager.SendMessageAsync<TxRequest, TxAck>(new TxAck
{
Tx = transactionType
});
break;
}
}
}
Debug.WriteLine($"TxSignature: {serializedTx.ToArray().ToHexCompact()}");
}
/// <summary>
/// Note: I don't know how to verify if this is returning the correct address or not
/// </summary>
[TestMethod]
public async Task DisplayStellarPublicKey()
{
var address = await GetAddressAsync("m/44'/148'/0'/0/0", true, null, true);
}
/// <summary>
/// Confirmed address valid as per online wallet
/// </summary>
[TestMethod]
public async Task GetCardanoAddress()
{
var isModelT = string.Compare(TrezorManager.Features.Model, "T", StringComparison.OrdinalIgnoreCase) == 0;
string address = null;
try
{
address = await GetAddressAsync(1815, false);
}
catch (NotSupportedException)
{
if (!isModelT) return;
}
if (isModelT)
{
Assert.IsTrue(!string.IsNullOrEmpty(address));
}
}
/// <summary>
/// Confirmed address valid as per online wallet
/// </summary>
[TestMethod]
public async Task GetTezosAddress()
{
var isModelT = string.Compare(TrezorManager.Features.Model, "T", StringComparison.OrdinalIgnoreCase) == 0;
string address = null;
try
{
address = await GetAddressAsync("44'/1729'/0'", false);
}
catch (NotSupportedException)
{
if (!isModelT) return;
}
if (isModelT)
{
Assert.IsTrue(!string.IsNullOrEmpty(address));
}
}
/// <summary>
/// Note: I don't know how to verify if this is returning the correct address or not
/// </summary>
[TestMethod]
public async Task GetNEMAddress()
{
var address = await GetAddressAsync("44'/43'/0'", false);
}
[TestMethod]
public async Task GetNamecoinAddress()
{
var address = await GetAddressAsync(7, false);
}
[TestMethod]
public async Task DisplayBitcoinAddress()
{
var address = await GetAddressAsync(0, true);
}
[TestMethod]
public async Task GetBitcoinAddress()
{
var address = await GetAddressAsync(true, 0, false, 0, false);
}
[TestMethod]
public async Task GetBitcoinAddresses()
{
var addressManager = new AddressManager(TrezorManager, new BIP44AddressPathFactory(true, 0));
//Get 10 addresses with all the trimming
const int numberOfAddresses = 3;
const int numberOfAccounts = 2;
var addresses = await addressManager.GetAddressesAsync(0, numberOfAddresses, numberOfAccounts, true, true);
Assert.IsTrue(addresses != null);
Assert.IsTrue(addresses.Accounts != null);
Assert.IsTrue(addresses.Accounts.Count == numberOfAccounts);
Assert.IsTrue(addresses.Accounts[0].Addresses.Count == numberOfAddresses);
Assert.IsTrue(addresses.Accounts[1].Addresses.Count == numberOfAddresses);
Assert.IsTrue(addresses.Accounts[0].ChangeAddresses.Count == numberOfAddresses);
Assert.IsTrue(addresses.Accounts[1].ChangeAddresses.Count == numberOfAddresses);
Assert.IsTrue(addresses.Accounts[0].Addresses[0].PublicKey.Length > addresses.Accounts[0].Addresses[0].Address.Length);
}
[TestMethod]
public async Task GetBitcoinCashAddress()
{
var address = await GetAddressAsync(false, 145, false, 0, false);
}
[TestMethod]
public async Task GetBitcoinCashParsedAddress()
{
var address = await GetAddressAsync("m/44'/145'/0'/0/0");
}
[TestMethod]
public async Task DisplayBitcoinCashAddress()
{
var address = await GetAddressAsync(false, 145, false, 0, true, "Bcash");
}
[TestMethod]
public async Task GetBitcoinGoldAddress()
{
var address = await GetAddressAsync(156, false);
}
[TestMethod]
public async Task DisplayEthereumAddress()
{
//Ethereum coins don't need the coin name
var address = await GetAddressAsync(false, 60, false, 0, true);
}
[TestMethod]
public async Task GetEthereumAddress()
{
var address = await GetAddressAsync("m/44'/60'/0'/1/0");
}
[TestMethod]
public async Task GetEthereumClassicAddressParsed()
{
var address = await GetAddressAsync("m/44'/61'/0'/1/0");
}
[TestMethod]
public async Task GetEthereumClassicAddress()
{
//Ethereum coins don't need the coin name
var address = await GetAddressAsync(false, 61, false, 0, false);
}
[TestMethod]
public async Task TestThreadSafety()
{
var tasks = new List<Task>();
const int addresses = 20;
for (uint i = 0; i < addresses; i++)
{
tasks.Add(DoGetAddress(i));
}
await Task.WhenAll(tasks);
for (uint i = 0; i < addresses; i++)
{
var address = await GetAddressAsync(i);
Console.WriteLine($"Index: {i} (No change) - Address: {address}");
if (address != _Addresses[i])
{
throw new Exception("The ordering got messed up");
}
}
}
[TestMethod]
public async Task SignEthereumTransaction()
{
//Note: these are not reasonable values. They should not be used for a transaction. Looking for a better example here...
var txMessage = new EthereumSignTx
{
Nonce = 0.ToHexBytes(),
GasPrice = 1000000000.ToHexBytes(),
GasLimit = 21000.ToHexBytes(),
To = "689c56aef474df92d44a1b70850f808488f9769c",
Value = 100000000000000.ToHexBytes(),
AddressNs = new BIP44AddressPath(false, 60, 0, false, 0).ToArray(),
ChainId = 4
};
var transaction = await TrezorManager.SendMessageAsync<EthereumTxRequest, EthereumSignTx>(txMessage);
Assert.AreEqual(transaction.SignatureR.Length, 32);
Assert.AreEqual(transaction.SignatureS.Length, 32);
}
[TestMethod]
public async Task SignEthereumTransaction2()
{
var txMessage = new EthereumSignTx
{
Nonce = 10.ToBytesForRLPEncoding().ToHex().ToHexBytes(),
GasPrice = 1000000000.ToBytesForRLPEncoding().ToHex().ToHexBytes(),
GasLimit = 21000.ToBytesForRLPEncoding().ToHex().ToHexBytes(),
To = "689c56aef474df92d44a1b70850f808488f9769c",
Value = BigInteger.Parse("10000000000000000000").ToBytesForRLPEncoding().ToHex().ToHexBytes(),
AddressNs = AddressPathBase.Parse<BIP44AddressPath>("m/44'/60'/0'/0/0").ToArray(),
ChainId = 1
};
var transaction = await TrezorManager.SendMessageAsync<EthereumTxRequest, EthereumSignTx>(txMessage);
Assert.AreEqual(transaction.SignatureR.Length, 32);
Assert.AreEqual(transaction.SignatureS.Length, 32);
}
[TestMethod]
public async Task GetBitcoinCashCoinInfo()
{
var defaultCoinUtility = new DefaultCoinUtility();
var bitcoinCashCoinInfo = defaultCoinUtility.GetCoinInfo(145);
Assert.IsTrue(bitcoinCashCoinInfo.CoinName == "Bcash");
}
#endregion
}
}