-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
635 lines (522 loc) · 25 KB
/
Copy pathProgram.cs
File metadata and controls
635 lines (522 loc) · 25 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
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using BitcoinLib.Services.Coins.Bitcoin;
using System.Linq;
using BitcoinLib.Responses;
using BitcoinLib.Responses.SharedComponents;
namespace SAPI.Sync
{
class Program
{
static string serverURL = "http://127.0.0.1:9679";
static string serverUser = string.Empty;
static string serverPass = string.Empty;
static string connString = string.Empty;
private static bool rescan = false;
private static int lastBlock = 0;
private static IConfiguration Configuration { get; set; }
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath((Directory.GetCurrentDirectory()))
.AddJsonFile("appsettings.json");
Configuration = builder.Build();
connString = $"Server=tcp:localhost,1433;Initial Catalog=SAPI;User ID=sa;Password={Configuration["SyncDb"]};Connection Timeout=30;";
serverUser = Configuration["rpcuser"];
serverPass = Configuration["rpcpass"];
var CoinService = new BitcoinService(serverURL,
serverUser,
serverPass,
"",
60);
CoinService.Parameters.CoinLongName = "SmartCash";
CoinService.Parameters.CoinShortName = "SMART";
CoinService.Parameters.IsoCurrencyCode = "XSC";
CoinService.Parameters.UseTestnet = false;
//Body
HashSet<string> tx = new HashSet<string>();
Sync();
Console.Write("Done!");
void Sync()
{
#region SyncBlocks
//Body
string startBlockHash = string.Empty;
startBlockHash = GetStartBlockHash();
if (args.Count() == 1)
{
long blkNumber = Convert.ToInt64(args[0]);
if (blkNumber != 999)
startBlockHash = CoinService.GetBlockHash(blkNumber);
else
{
blkNumber = CoinService.GetBlockCount() - 30;
startBlockHash = CoinService.GetBlockHash(blkNumber);
}
}
else if (args.Count() == 2)
{
long blkNumber = Convert.ToInt64(args[0]);
rescan = Convert.ToBoolean(args[1]);
if (blkNumber != 999)
startBlockHash = CoinService.GetBlockHash(blkNumber);
else
{
blkNumber = CoinService.GetBlockCount() - 30;
startBlockHash = CoinService.GetBlockHash(blkNumber);
}
}
int topBlock = Convert.ToInt32(CoinService.GetBlockCount());
GetBlockResponse curBlock = new GetBlockResponse();
if (startBlockHash == null || startBlockHash == "") // Start from scratch
{
startBlockHash = "00000009c4e61bee0e8d6236f847bb1dd23f4c61ca5240b74852184c9bf98c30"; // Block 1
curBlock = GetBlock(startBlockHash);
InsertBlock(curBlock);
foreach (string txid in curBlock.Tx)
{
GetRawTransactionResponse nextTransaction = GetTransaction(txid);
InsertTransaction(nextTransaction);
var countInput = 0;
// Input
foreach (Vin transactionInput in nextTransaction.Vin)
{
InsertTransactionInput(transactionInput, txid, countInput);
countInput++;
}
// Output
foreach (var transactionOutput in nextTransaction.Vout)
{
if (transactionOutput.ScriptPubKey.Addresses != null)
{
if (transactionOutput.ScriptPubKey.Addresses.Count > 1)
{
Debug.WriteLine("2> Address: " + txid);
}
InsertTransactionOutput(transactionOutput, txid);
}
else
{
Debug.WriteLine("No Address: " + txid);
}
}
tx.Add(txid);
}
}
else
{
curBlock = GetBlock(startBlockHash);
}
//Fix Orphan Blocks
if (curBlock.Confirmations == -1)
{
DeleteOrphanBlock(curBlock.Hash);
startBlockHash = GetStartBlockHash();
curBlock = GetBlock(startBlockHash);
}
while (curBlock.NextBlockHash != null)
{
// Block
curBlock = GetBlock(curBlock.NextBlockHash);
ProcessBlock(curBlock, topBlock);
}
FindMissingBlocks();
#endregion
Console.WriteLine("Done");
}
void ProcessBlock(GetBlockResponse curBlock, int topBlock)
{
Console.Write("\r Processing Block {0} of {1}", curBlock.Height.ToString(), topBlock.ToString());
InsertBlock(curBlock);
// Transaction
foreach (string txid in curBlock.Tx)
{
try
{
GetRawTransactionResponse nextTransaction = GetTransaction(txid);
if (!tx.Contains(txid)) //Exclude transactions linked to multiple blocks (Zerocoin Mint/Smartcash Renew)
{
InsertTransaction(nextTransaction);
var countInput = 0;
// Input
foreach (Vin transactionInput in nextTransaction.Vin)
{
InsertTransactionInput(transactionInput, txid, countInput);
countInput++;
}
// Output
foreach (Vout transactionOutput in nextTransaction.Vout)
{
if (transactionOutput.ScriptPubKey.Addresses != null)
{
if (transactionOutput.ScriptPubKey.Addresses.Count > 1)
{
Debug.WriteLine("2> Address: " + txid);
}
InsertTransactionOutput(transactionOutput, txid);
}
else
{
Debug.WriteLine("No Address: " + txid);
}
}
tx.Add(txid);
}
else
{
UpdateTransaction(nextTransaction);
}
}
catch
{
}
}
//Console.WriteLine(curBlock.height);
}
void FindMissingBlocks()
{
string selectString = @"
WITH Missing (missnum, maxid)
AS
(
SELECT (select min(Height) missnum from [Block]) , (select max(Height) from [Block])
UNION ALL
SELECT missnum + 1, maxid FROM Missing
WHERE missnum < maxid
)
SELECT missnum
FROM Missing
LEFT OUTER JOIN [Block] tt on tt.Height = Missing.missnum
WHERE tt.Height is NULL
OPTION (MAXRECURSION 0);";
List<int> missing = new List<int>();
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand(selectString, conn))
{
try
{
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
{
while (dr.Read())
{
missing.Add(Convert.ToInt32(dr["missnum"]));
}
}
}
catch (Exception ex)
{
Console.WriteLine("SQL Error" + ex.Message);
throw;
}
}
}
foreach (var item in missing)
{
var hash = CoinService.GetBlockHash(item);
var block = GetBlock(hash);
ProcessBlock(block, item);
}
}
string GetStartBlockHash()
{
string startBlockHash = "";
if (rescan)
return startBlockHash;
string selectString = "SELECT TOP 1 [Hash] FROM [Block] ORDER BY [Height] DESC";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand(selectString, conn))
{
try
{
conn.Open();
startBlockHash = (string)comm.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine("SQL Error" + ex.Message + " : " + "GetStartBlockHash");
throw;
}
}
}
return startBlockHash;
}
BitcoinLib.Responses.GetBlockResponse GetBlock(string blockHash)
{
return CoinService.GetBlock(blockHash, true);
}
bool InsertBlock(GetBlockResponse block)
{
string cmdString = "INSERT INTO [Block] ([Hash],[Height],[Confirmation],[Size],[Difficulty],[Version],[Time]) VALUES (@Hash, @Height, @Confirmation, @Size, @Difficulty, @Version, @Time)";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("@Hash", block.Hash);
comm.Parameters.AddWithValue("@Height", block.Height);
comm.Parameters.AddWithValue("@Confirmation", block.Confirmations);
comm.Parameters.AddWithValue("@Size", block.Size);
comm.Parameters.AddWithValue("@Difficulty", block.Difficulty);
comm.Parameters.AddWithValue("@Version", block.Version);
comm.Parameters.AddWithValue("@Time", UnixTimeStampToDateTime(block.Time));
try
{
conn.Open();
comm.ExecuteNonQuery();
lastBlock = block.Height;
}
catch (Exception ex)
{
if (!rescan)
Console.WriteLine("SQL Error" + ex.Message + " : " + JsonConvert.SerializeObject(block));
//throw;
}
}
}
return true;
}
GetRawTransactionResponse GetTransaction(string txid)
{
var raw = CoinService.GetRawTransaction(txid, 1);
return raw;
}
bool InsertTransaction(GetRawTransactionResponse transaction)
{
if (!tx.Contains(transaction.TxId)) //Exclude transactions linked to multiple blocks (Zerocoin Mint/Smartcash Renew)
{
string cmdString = "EXEC Transaction_Create @Txid, @BlockHash, @Version, @Time, @IsInstantPay, @IsWebWallet";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("@Txid", transaction.TxId);
comm.Parameters.AddWithValue("@BlockHash", transaction.BlockHash);
comm.Parameters.AddWithValue("@Version", transaction.Version);
comm.Parameters.AddWithValue("@Time", UnixTimeStampToDateTime(transaction.Time));
comm.Parameters.AddWithValue("@IsInstantPay", (transaction.LockTime > 0));
comm.Parameters.AddWithValue("@IsWebWallet", false);
try
{
conn.Open();
comm.ExecuteNonQuery();
tx.Add(transaction.TxId);
}
catch (Exception ex)
{
if (!rescan)
Console.WriteLine("SQL Error" + ex.Message + " : " + JsonConvert.SerializeObject(transaction));
throw;
}
}
}
}
return true;
}
bool UpdateTransaction(GetRawTransactionResponse transaction)
{
string cmdString = "EXEC Transaction_Create @Txid, @BlockHash, @Version, @Time, @IsInstantPay, @IsWebWallet";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("@Txid", transaction.TxId);
comm.Parameters.AddWithValue("@BlockHash", transaction.BlockHash);
comm.Parameters.AddWithValue("@Version", transaction.Version);
comm.Parameters.AddWithValue("@Time", UnixTimeStampToDateTime(transaction.Time));
comm.Parameters.AddWithValue("@IsInstantPay", (transaction.LockTime > 0));
comm.Parameters.AddWithValue("@IsWebWallet", false);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine("SQL Error" + ex.Message + " : " + JsonConvert.SerializeObject(transaction));
throw;
}
}
}
return true;
}
bool InsertTransactionInput(Vin transactionInput, string txid, int index)
{
string coinbase = transactionInput.CoinBase;
string txidOut = transactionInput.TxId;
long indexOut = Convert.ToInt32(transactionInput.Vout);
string sAddress = "";
decimal sValue = 0;
if (coinbase != null)
{
txidOut = "0000000000000000000000000000000000000000000000000000000000000000";
sAddress = "0000000000000000000000000000000000";
}
else if (txidOut == "0000000000000000000000000000000000000000000000000000000000000000")
{
indexOut = 0;
sAddress = "0000000000000000000000000000000001";
}
else
{
string selectString = "SELECT [Address], [Value] FROM [TransactionOutput] WHERE [Txid] = '" + txidOut + "' AND [Index] = " + indexOut;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand(selectString, conn))
{
try
{
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
{
while (dr.Read())
{
sAddress = dr["Address"].ToString();
sValue = decimal.Parse(dr["Value"].ToString());
}
}
}
catch (Exception ex)
{
Console.WriteLine("SQL Error" + ex.Message + " : " + JsonConvert.SerializeObject(transactionInput) + " ; " + txid + " ; " + index.ToString());
throw;
}
}
}
}
string cmdString = "INSERT INTO [TransactionInput] ([TxidIn],[IndexIn],[TxidOut],[IndexOut],[Address],[Value]) VALUES (@TxidIn, @IndexIn, @TxidOut, @IndexOut, @Address, @Value)";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("@TxidIn", txid);
comm.Parameters.AddWithValue("@IndexIn", index);
comm.Parameters.AddWithValue("@TxidOut", txidOut);
comm.Parameters.AddWithValue("@IndexOut", indexOut);
comm.Parameters.AddWithValue("@Address", sAddress);
comm.Parameters.AddWithValue("@Value", sValue);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
if (!rescan)
Console.WriteLine("SQL Error" + ex.Message + " : " + JsonConvert.SerializeObject(transactionInput) + " ; " + txid + " ; " + index.ToString());
}
}
}
return true;
}
bool InsertTransactionOutput(Vout transactionOutput, string txid)
{
string cmdString = "INSERT INTO [TransactionOutput] ([Txid],[Index],[Address],[Value]) VALUES (@Txid, @Index, @Address, @Value)";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("@Txid", txid);
comm.Parameters.AddWithValue("@Index", transactionOutput.N);
comm.Parameters.AddWithValue("@Address", transactionOutput.ScriptPubKey.Addresses[0]);
comm.Parameters.AddWithValue("@Value", transactionOutput.Value);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch (Exception ex)
{
if (!rescan)
Console.WriteLine("SQL Error" + ex.Message + " : " + JsonConvert.SerializeObject(transactionOutput) + " ; " + txid);
}
}
}
return true;
}
bool DeleteOrphanBlock(string blockHash)
{
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
using (SqlCommand comm = new SqlCommand("SELECT [Txid] FROM [Transaction] WHERE [BlockHash] = '" + blockHash + "'", conn))
{
HashSet<string> hTxid = new HashSet<string>();
using (SqlDataReader dr = comm.ExecuteReader())
{
while (dr.Read())
{
hTxid.Add(dr["Txid"].ToString());
}
}
foreach (string txid in hTxid)
{
using (SqlCommand commI = new SqlCommand())
{
commI.Connection = conn;
commI.CommandText = "DELETE FROM [TransactionInput] WHERE [TxidIn] = '" + txid + "'";
commI.ExecuteNonQuery();
}
using (SqlCommand commO = new SqlCommand())
{
commO.Connection = conn;
commO.CommandText = "DELETE FROM [TransactionOutput] WHERE [Txid] = '" + txid + "'";
commO.ExecuteNonQuery();
}
}
}
using (SqlCommand commT = new SqlCommand())
{
commT.Connection = conn;
commT.CommandText = "DELETE FROM [Transaction] WHERE [BlockHash] = '" + blockHash + "'";
commT.ExecuteNonQuery();
}
using (SqlCommand commB = new SqlCommand())
{
commB.Connection = conn;
commB.CommandText = "DELETE FROM [Block] WHERE [Hash] = '" + blockHash + "'";
commB.ExecuteNonQuery();
}
}
catch (Exception ex)
{
if (!rescan)
Console.WriteLine("SQL Error" + ex.Message + " : " + "DeleteOrphanBlock" + " : " + blockHash);
throw;
}
}
return true;
}
//
// Helper Functions
//
DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
// Unix timestamp is seconds past epoch
System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
dtDateTime = dtDateTime.AddSeconds(unixTimeStamp);
return dtDateTime;
}
}
}
}