-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
214 lines (188 loc) · 9 KB
/
Copy pathProgram.cs
File metadata and controls
214 lines (188 loc) · 9 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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using ClosedXML.Excel;
using Newtonsoft.Json;
using NBitcoin;
using System.Security.Cryptography.X509Certificates;
public class BtcScannerEsplora
{
private const string BaseUrl = "https://btcscan.org/api";
private const string ProgressFile = "scan_progress.txt";
private const string ExcelFile = "Vulnerable_P2PK_Coins.xlsx";
private static readonly HttpClient client;
private static List<CoinInfo> foundCoins = new List<CoinInfo>();
static BtcScannerEsplora()
{
var handler = new HttpClientHandler { UseCookies = true };
client = new HttpClient(handler);
// Заголовки для обхода защиты (подставь свои актуальные куки, если выдаст 403)
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36");
client.DefaultRequestHeaders.Add("accept", "*/*");
client.DefaultRequestHeaders.Add("Cookie", "cf_clearance=itU7mLfm9RAhN1Nm8fgnhR.XgoeFwTamQ6gfSPo44mg-1771482456-1.2.1.1-S4bnE_LPPLgPHg3pGtENH5F4e56jfp21RxMQ4LJ6N4p6VE7UEI2xWIvNByZ3m7GpLF5E2cPzjZ6X.5oxY_ODkJDs32J7MrMKkSqGIPNR7NBCNbttJVAGA5ny6sXzyLUKUjKW2uHfXM6xxog6itv19h7aq_hyCEmLBNuQhF5fc_VZZbaXgqM7cCt0intbRrMk0SEyO.KmetolBt5BJplUsNLMMB7x9ZTzRO1HrRf2nP8");
}
public static async Task Main()
{
// 1. Загрузка прогресса из файла
int currentBlock = LoadProgress();
int endBlock = 1000000;
Console.WriteLine($"[INFO] Продолжаем сканирование с блока: {currentBlock}");
using var cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) => {
e.Cancel = true;
cts.Cancel();
Console.WriteLine("\n[WAIT] Сохраняю всё и выхожу...");
};
try
{
for (int i = currentBlock; i <= endBlock; i++)
{
if (cts.Token.IsCancellationRequested) break;
// Обрабатываем блок
bool blockProcessed = await ProcessFullBlock(i, cts.Token);
if (blockProcessed)
{
// 2. Сохраняем прогресс после каждого блока
SaveProgress(i);
if (i % 10 == 0)
Console.WriteLine($"[PROGRESS] Проверено до блока {i}. Найдено P2PK: {foundCoins.Count}");
// Периодически сбрасываем Excel на диск
if (i % 100 == 0 && foundCoins.Count > 0) SaveToExcel();
}
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
Console.WriteLine($"[CRITICAL ERROR] {ex.Message}");
}
finally
{
// 3. Финальное сохранение
SaveToExcel();
Console.WriteLine($"[DONE] Работа остановлена на блоке {LoadProgress()}. Данные в {ExcelFile}");
}
}
private static async Task<bool> ProcessFullBlock(int height, CancellationToken token)
{
try
{
string blockHash = await GetWithRetry($"{BaseUrl}/block-height/{height}", token);
int startIndex = 0;
while (!token.IsCancellationRequested)
{
string txUrl = $"{BaseUrl}/block/{blockHash}/txs/{startIndex}";
string json = await GetWithRetry(txUrl, token);
var txs = JsonConvert.DeserializeObject<List<EsploraTx>>(json);
if (txs == null || txs.Count == 0) break;
foreach (var tx in txs)
{
for (int j = 0; j < tx.vout.Count; j++)
{
var vout = tx.vout[j];
if (vout.scriptpubkey_type == "p2pk")
{
bool isSpent = await CheckIfSpent(tx.txid, j, token);
if (!isSpent)
{
Console.WriteLine($"[FOUND!] Блок {height}: {vout.value / 100000000.0} BTC");
foundCoins.Add(new CoinInfo
{
BlockHeight = height,
TxId = tx.txid,
Amount = vout.value / 100000000.0,
// Сохраняем PubKey целиком для будущей генерации ключей
PublicKey = vout.scriptpubkey.StartsWith("4104") ? vout.scriptpubkey.Substring(2, vout.scriptpubkey.Length - 4) : vout.scriptpubkey,
Address = GetAddressFromPubKey(vout.scriptpubkey.StartsWith("4104") ? vout.scriptpubkey.Substring(2, vout.scriptpubkey.Length - 4) : vout.scriptpubkey)
});
}
}
}
}
if (txs.Count < 25) break;
startIndex += 25;
}
return true;
}
catch { return false; }
}
private static async Task<bool> CheckIfSpent(string txid, int index, CancellationToken token)
{
string url = $"{BaseUrl}/tx/{txid}/outspend/{index}";
string json = await GetWithRetry(url, token);
var status = JsonConvert.DeserializeObject<OutspendStatus>(json);
return status.spent;
}
private static async Task<string> GetWithRetry(string url, CancellationToken token)
{
while (!token.IsCancellationRequested)
{
try
{
var response = await client.GetAsync(url, token);
if (response.StatusCode == (HttpStatusCode)429)
{
await Task.Delay(30000, token); // Пауза 30 сек
continue;
}
if (response.StatusCode == HttpStatusCode.Forbidden)
throw new Exception("403 Forbidden - обнови куки cf_clearance!");
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException) { await Task.Delay(5000, token); }
}
return string.Empty;
}
public static string GetAddressFromPubKey(string pubKeyHex)
{
// Создаем объект публичного ключа из HEX-строки
PubKey pubKey = new PubKey(pubKeyHex);
// Получаем стандартный Legacy адрес (P2PKH)
// Хотя монеты лежат на P2PK, их эквивалентный адрес считается так:
return pubKey.GetAddress(ScriptPubKeyType.Legacy, Network.Main).ToString();
}
private static int LoadProgress()
{
if (File.Exists(ProgressFile))
{
if (int.TryParse(File.ReadAllText(ProgressFile), out int lastBlock))
return lastBlock + 1; // Начинаем со следующего
}
return 0;
}
private static void SaveProgress(int block) => File.WriteAllText(ProgressFile, block.ToString());
private static void SaveToExcel()
{
if (foundCoins.Count == 0) return;
try
{
using var workbook = new XLWorkbook();
var ws = workbook.Worksheets.Add("Vulnerable");
ws.Cell(1, 1).Value = "Block";
ws.Cell(1, 2).Value = "TxID";
ws.Cell(1, 3).Value = "BTC";
ws.Cell(1, 4).Value = "PublicKey";
ws.Cell(1, 5).Value = "Wallett Address";
for (int i = 0; i < foundCoins.Count; i++)
{
ws.Cell(i + 2, 1).Value = foundCoins[i].BlockHeight;
ws.Cell(i + 2, 2).Value = foundCoins[i].TxId;
ws.Cell(i + 2, 3).Value = foundCoins[i].Amount;
ws.Cell(i + 2, 4).Value = foundCoins[i].PublicKey;
ws.Cell(i + 2, 5).Value = foundCoins[i].Address;
}
workbook.SaveAs(ExcelFile);
}
catch (Exception ex) { Console.WriteLine($"Ошибка записи Excel: {ex.Message}"); }
}
}
public class CoinInfo { public int BlockHeight { get; set; } public string TxId { get; set; } public double Amount { get; set; } public string PublicKey { get; set; } public string Address { get; set; } }
public class EsploraTx { public string txid { get; set; } public List<Vout> vout { get; set; } }
public class Vout { public string scriptpubkey { get; set; } public string scriptpubkey_type { get; set; } public long value { get; set; } }
public class OutspendStatus { public bool spent { get; set; } }