-
Notifications
You must be signed in to change notification settings - Fork 483
/
main.cpp
680 lines (550 loc) · 19.9 KB
/
main.cpp
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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
#include <stdio.h>
#include <fstream>
#include <iostream>
#include "KeyFinder.h"
#include "AddressUtil.h"
#include "util.h"
#include "secp256k1.h"
#include "CmdParse.h"
#include "Logger.h"
#include "ConfigFile.h"
#include "DeviceManager.h"
#ifdef BUILD_CUDA
#include "CudaKeySearchDevice.h"
#endif
#ifdef BUILD_OPENCL
#include "CLKeySearchDevice.h"
#endif
typedef struct {
// startKey is the first key. We store it so that if the --continue
// option is used, the correct progress is displayed. startKey and
// nextKey are only equal at the very beginning. nextKey gets saved
// in the checkpoint file.
secp256k1::uint256 startKey = 1;
secp256k1::uint256 nextKey = 1;
// The last key to be checked
secp256k1::uint256 endKey = secp256k1::N - 1;
uint64_t statusInterval = 1800;
uint64_t checkpointInterval = 60000;
unsigned int threads = 0;
unsigned int blocks = 0;
unsigned int pointsPerThread = 0;
int compression = PointCompressionType::COMPRESSED;
std::vector<std::string> targets;
std::string targetsFile = "";
std::string checkpointFile = "";
int device = 0;
std::string resultsFile = "";
uint64_t totalkeys = 0;
unsigned int elapsed = 0;
secp256k1::uint256 stride = 1;
bool follow = false;
}RunConfig;
static RunConfig _config;
std::vector<DeviceManager::DeviceInfo> _devices;
void writeCheckpoint(secp256k1::uint256 nextKey);
static uint64_t _lastUpdate = 0;
static uint64_t _runningTime = 0;
static uint64_t _startTime = 0;
/**
* Callback to display the private key
*/
void resultCallback(KeySearchResult info)
{
if(_config.resultsFile.length() != 0) {
Logger::log(LogLevel::Info, "Found key for address '" + info.address + "'. Written to '" + _config.resultsFile + "'");
std::string s = info.address + " " + info.privateKey.toString(16) + " " + info.publicKey.toString(info.compressed);
util::appendToFile(_config.resultsFile, s);
return;
}
std::string logStr = "Address: " + info.address + "\n";
logStr += "Private key: " + info.privateKey.toString(16) + "\n";
logStr += "Compressed: ";
if(info.compressed) {
logStr += "yes\n";
} else {
logStr += "no\n";
}
logStr += "Public key: \n";
if(info.compressed) {
logStr += info.publicKey.toString(true) + "\n";
} else {
logStr += info.publicKey.x.toString(16) + "\n";
logStr += info.publicKey.y.toString(16) + "\n";
}
Logger::log(LogLevel::Info, logStr);
}
/**
Callback to display progress
*/
void statusCallback(KeySearchStatus info)
{
std::string speedStr;
if(info.speed < 0.01) {
speedStr = "< 0.01 MKey/s";
} else {
speedStr = util::format("%.2f", info.speed) + " MKey/s";
}
std::string totalStr = "(" + util::formatThousands(_config.totalkeys + info.total) + " total)";
std::string timeStr = "[" + util::formatSeconds((unsigned int)((_config.elapsed + info.totalTime) / 1000)) + "]";
std::string usedMemStr = util::format((info.deviceMemory - info.freeMemory) /(1024 * 1024));
std::string totalMemStr = util::format(info.deviceMemory / (1024 * 1024));
std::string targetStr = util::format(info.targets) + " target" + (info.targets > 1 ? "s" : "");
// Fit device name in 16 characters, pad with spaces if less
std::string devName = info.deviceName.substr(0, 16);
devName += std::string(16 - devName.length(), ' ');
const char *formatStr = NULL;
if(_config.follow) {
formatStr = "%s %s/%sMB | %s %s %s %s\n";
} else {
formatStr = "\r%s %s / %sMB | %s %s %s %s";
}
printf(formatStr, devName.c_str(), usedMemStr.c_str(), totalMemStr.c_str(), targetStr.c_str(), speedStr.c_str(), totalStr.c_str(), timeStr.c_str());
if(_config.checkpointFile.length() > 0) {
uint64_t t = util::getSystemTime();
if(t - _lastUpdate >= _config.checkpointInterval) {
Logger::log(LogLevel::Info, "Checkpoint");
writeCheckpoint(info.nextKey);
_lastUpdate = t;
}
}
}
/**
* Parses the start:end key pair. Possible values are:
start
start:end
start:+offset
:end
:+offset
*/
bool parseKeyspace(const std::string &s, secp256k1::uint256 &start, secp256k1::uint256 &end)
{
size_t pos = s.find(':');
if(pos == std::string::npos) {
start = secp256k1::uint256(s);
end = secp256k1::N - 1;
} else {
std::string left = s.substr(0, pos);
if(left.length() == 0) {
start = secp256k1::uint256(1);
} else {
start = secp256k1::uint256(left);
}
std::string right = s.substr(pos + 1);
if(right[0] == '+') {
end = start + secp256k1::uint256(right.substr(1));
} else {
end = secp256k1::uint256(right);
}
}
return true;
}
void usage()
{
printf("BitCrack OPTIONS [TARGETS]\n");
printf("Where TARGETS is one or more addresses\n\n");
printf("--help Display this message\n");
printf("-c, --compressed Use compressed points\n");
printf("-u, --uncompressed Use Uncompressed points\n");
printf("--compression MODE Specify compression where MODE is\n");
printf(" COMPRESSED or UNCOMPRESSED or BOTH\n");
printf("-d, --device ID Use device ID\n");
printf("-b, --blocks N N blocks\n");
printf("-t, --threads N N threads per block\n");
printf("-p, --points N N points per thread\n");
printf("-i, --in FILE Read addresses from FILE, one per line\n");
printf("-o, --out FILE Write keys to FILE\n");
printf("-f, --follow Follow text output\n");
printf("--list-devices List available devices\n");
printf("--keyspace KEYSPACE Specify the keyspace:\n");
printf(" START:END\n");
printf(" START:+COUNT\n");
printf(" START\n");
printf(" :END\n");
printf(" :+COUNT\n");
printf(" Where START, END, COUNT are in hex format\n");
printf("--stride N Increment by N keys at a time\n");
printf("--share M/N Divide the keyspace into N equal shares, process the Mth share\n");
printf("--continue FILE Save/load progress from FILE\n");
}
/**
Finds default parameters depending on the device
*/
typedef struct {
int threads;
int blocks;
int pointsPerThread;
}DeviceParameters;
DeviceParameters getDefaultParameters(const DeviceManager::DeviceInfo &device)
{
DeviceParameters p;
p.threads = 256;
p.blocks = 32;
p.pointsPerThread = 32;
return p;
}
static KeySearchDevice *getDeviceContext(DeviceManager::DeviceInfo &device, int blocks, int threads, int pointsPerThread)
{
#ifdef BUILD_CUDA
if(device.type == DeviceManager::DeviceType::CUDA) {
return new CudaKeySearchDevice((int)device.physicalId, threads, pointsPerThread, blocks);
}
#endif
#ifdef BUILD_OPENCL
if(device.type == DeviceManager::DeviceType::OpenCL) {
return new CLKeySearchDevice(device.physicalId, threads, pointsPerThread, blocks);
}
#endif
return NULL;
}
static void printDeviceList(const std::vector<DeviceManager::DeviceInfo> &devices)
{
for(int i = 0; i < devices.size(); i++) {
printf("ID: %d\n", devices[i].id);
printf("Name: %s\n", devices[i].name.c_str());
printf("Memory: %lldMB\n", devices[i].memory / ((uint64_t)1024 * 1024));
printf("Compute units: %d\n", devices[i].computeUnits);
printf("\n");
}
}
bool readAddressesFromFile(const std::string &fileName, std::vector<std::string> &lines)
{
if(fileName == "-") {
return util::readLinesFromStream(std::cin, lines);
} else {
return util::readLinesFromStream(fileName, lines);
}
}
int parseCompressionString(const std::string &s)
{
std::string comp = util::toLower(s);
if(comp == "both") {
return PointCompressionType::BOTH;
}
if(comp == "compressed") {
return PointCompressionType::COMPRESSED;
}
if(comp == "uncompressed") {
return PointCompressionType::UNCOMPRESSED;
}
throw std::string("Invalid compression format: '" + s + "'");
}
static std::string getCompressionString(int mode)
{
switch(mode) {
case PointCompressionType::BOTH:
return "both";
case PointCompressionType::UNCOMPRESSED:
return "uncompressed";
case PointCompressionType::COMPRESSED:
return "compressed";
}
throw std::string("Invalid compression setting '" + util::format(mode) + "'");
}
void writeCheckpoint(secp256k1::uint256 nextKey)
{
std::ofstream tmp(_config.checkpointFile, std::ios::out);
tmp << "start=" << _config.startKey.toString() << std::endl;
tmp << "next=" << nextKey.toString() << std::endl;
tmp << "end=" << _config.endKey.toString() << std::endl;
tmp << "blocks=" << _config.blocks << std::endl;
tmp << "threads=" << _config.threads << std::endl;
tmp << "points=" << _config.pointsPerThread << std::endl;
tmp << "compression=" << getCompressionString(_config.compression) << std::endl;
tmp << "device=" << _config.device << std::endl;
tmp << "elapsed=" << (_config.elapsed + util::getSystemTime() - _startTime) << std::endl;
tmp << "stride=" << _config.stride.toString();
tmp.close();
}
void readCheckpointFile()
{
if(_config.checkpointFile.length() == 0) {
return;
}
ConfigFileReader reader(_config.checkpointFile);
if(!reader.exists()) {
return;
}
Logger::log(LogLevel::Info, "Loading ' " + _config.checkpointFile + "'");
std::map<std::string, ConfigFileEntry> entries = reader.read();
_config.startKey = secp256k1::uint256(entries["start"].value);
_config.nextKey = secp256k1::uint256(entries["next"].value);
_config.endKey = secp256k1::uint256(entries["end"].value);
if(_config.threads == 0 && entries.find("threads") != entries.end()) {
_config.threads = util::parseUInt32(entries["threads"].value);
}
if(_config.blocks == 0 && entries.find("blocks") != entries.end()) {
_config.blocks = util::parseUInt32(entries["blocks"].value);
}
if(_config.pointsPerThread == 0 && entries.find("points") != entries.end()) {
_config.pointsPerThread = util::parseUInt32(entries["points"].value);
}
if(entries.find("compression") != entries.end()) {
_config.compression = parseCompressionString(entries["compression"].value);
}
if(entries.find("elapsed") != entries.end()) {
_config.elapsed = util::parseUInt32(entries["elapsed"].value);
}
if(entries.find("stride") != entries.end()) {
_config.stride = util::parseUInt64(entries["stride"].value);
}
_config.totalkeys = (_config.nextKey - _config.startKey).toUint64();
}
int run()
{
if(_config.device < 0 || _config.device >= _devices.size()) {
Logger::log(LogLevel::Error, "device " + util::format(_config.device) + " does not exist");
return 1;
}
Logger::log(LogLevel::Info, "Compression: " + getCompressionString(_config.compression));
Logger::log(LogLevel::Info, "Starting at: " + _config.nextKey.toString());
Logger::log(LogLevel::Info, "Ending at: " + _config.endKey.toString());
Logger::log(LogLevel::Info, "Counting by: " + _config.stride.toString());
try {
_lastUpdate = util::getSystemTime();
_startTime = util::getSystemTime();
// Use default parameters if they have not been set
DeviceParameters params = getDefaultParameters(_devices[_config.device]);
if(_config.blocks == 0) {
_config.blocks = params.blocks;
}
if(_config.threads == 0) {
_config.threads = params.threads;
}
if(_config.pointsPerThread == 0) {
_config.pointsPerThread = params.pointsPerThread;
}
// Get device context
KeySearchDevice *d = getDeviceContext(_devices[_config.device], _config.blocks, _config.threads, _config.pointsPerThread);
KeyFinder f(_config.nextKey, _config.endKey, _config.compression, d, _config.stride);
f.setResultCallback(resultCallback);
f.setStatusInterval(_config.statusInterval);
f.setStatusCallback(statusCallback);
f.init();
if(!_config.targetsFile.empty()) {
f.setTargets(_config.targetsFile);
} else {
f.setTargets(_config.targets);
}
f.run();
delete d;
} catch(KeySearchException ex) {
Logger::log(LogLevel::Info, "Error: " + ex.msg);
return 1;
}
return 0;
}
/**
* Parses a string in the form of x/y
*/
bool parseShare(const std::string &s, uint32_t &idx, uint32_t &total)
{
size_t pos = s.find('/');
if(pos == std::string::npos) {
return false;
}
try {
idx = util::parseUInt32(s.substr(0, pos));
} catch(...) {
return false;
}
try {
total = util::parseUInt32(s.substr(pos + 1));
} catch(...) {
return false;
}
if(idx == 0 || total == 0) {
return false;
}
if(idx > total) {
return false;
}
return true;
}
int main(int argc, char **argv)
{
bool optCompressed = false;
bool optUncompressed = false;
bool listDevices = false;
bool optShares = false;
bool optThreads = false;
bool optBlocks = false;
bool optPoints = false;
uint32_t shareIdx = 0;
uint32_t numShares = 0;
// Catch --help first
for(int i = 1; i < argc; i++) {
if(std::string(argv[i]) == "--help") {
usage();
return 0;
}
}
// Check for supported devices
try {
_devices = DeviceManager::getDevices();
if(_devices.size() == 0) {
Logger::log(LogLevel::Error, "No devices available");
return 1;
}
} catch(DeviceManager::DeviceManagerException ex) {
Logger::log(LogLevel::Error, "Error detecting devices: " + ex.msg);
return 1;
}
// Check for arguments
if(argc == 1) {
usage();
return 0;
}
CmdParse parser;
parser.add("-d", "--device", true);
parser.add("-t", "--threads", true);
parser.add("-b", "--blocks", true);
parser.add("-p", "--points", true);
parser.add("-d", "--device", true);
parser.add("-c", "--compressed", false);
parser.add("-u", "--uncompressed", false);
parser.add("", "--compression", true);
parser.add("-i", "--in", true);
parser.add("-o", "--out", true);
parser.add("-f", "--follow", false);
parser.add("", "--list-devices", false);
parser.add("", "--keyspace", true);
parser.add("", "--continue", true);
parser.add("", "--share", true);
parser.add("", "--stride", true);
try {
parser.parse(argc, argv);
} catch(std::string err) {
Logger::log(LogLevel::Error, "Error: " + err);
return 1;
}
std::vector<OptArg> args = parser.getArgs();
for(unsigned int i = 0; i < args.size(); i++) {
OptArg optArg = args[i];
std::string opt = args[i].option;
try {
if(optArg.equals("-t", "--threads")) {
_config.threads = util::parseUInt32(optArg.arg);
optThreads = true;
} else if(optArg.equals("-b", "--blocks")) {
_config.blocks = util::parseUInt32(optArg.arg);
optBlocks = true;
} else if(optArg.equals("-p", "--points")) {
_config.pointsPerThread = util::parseUInt32(optArg.arg);
optPoints = true;
} else if(optArg.equals("-d", "--device")) {
_config.device = util::parseUInt32(optArg.arg);
} else if(optArg.equals("-c", "--compressed")) {
optCompressed = true;
} else if(optArg.equals("-u", "--uncompressed")) {
optUncompressed = true;
} else if(optArg.equals("", "--compression")) {
_config.compression = parseCompressionString(optArg.arg);
} else if(optArg.equals("-i", "--in")) {
_config.targetsFile = optArg.arg;
} else if(optArg.equals("-o", "--out")) {
_config.resultsFile = optArg.arg;
} else if(optArg.equals("", "--list-devices")) {
listDevices = true;
} else if(optArg.equals("", "--continue")) {
_config.checkpointFile = optArg.arg;
} else if(optArg.equals("", "--keyspace")) {
secp256k1::uint256 start;
secp256k1::uint256 end;
parseKeyspace(optArg.arg, start, end);
if(start.cmp(secp256k1::N) > 0) {
throw std::string("argument is out of range");
}
if(start.isZero()) {
throw std::string("argument is out of range");
}
if(end.cmp(secp256k1::N) > 0) {
throw std::string("argument is out of range");
}
if(start.cmp(end) > 0) {
throw std::string("Invalid argument");
}
_config.startKey = start;
_config.nextKey = start;
_config.endKey = end;
} else if(optArg.equals("", "--share")) {
if(!parseShare(optArg.arg, shareIdx, numShares)) {
throw std::string("Invalid argument");
}
optShares = true;
} else if(optArg.equals("", "--stride")) {
try {
_config.stride = secp256k1::uint256(optArg.arg);
} catch(...) {
throw std::string("invalid argument: : expected hex string");
}
if(_config.stride.cmp(secp256k1::N) >= 0) {
throw std::string("argument is out of range");
}
if(_config.stride.cmp(0) == 0) {
throw std::string("argument is out of range");
}
} else if(optArg.equals("-f", "--follow")) {
_config.follow = true;
}
} catch(std::string err) {
Logger::log(LogLevel::Error, "Error " + opt + ": " + err);
return 1;
}
}
if(listDevices) {
printDeviceList(_devices);
return 0;
}
// Verify device exists
if(_config.device < 0 || _config.device >= _devices.size()) {
Logger::log(LogLevel::Error, "device " + util::format(_config.device) + " does not exist");
return 1;
}
// Parse operands
std::vector<std::string> ops = parser.getOperands();
// If there are no operands, then we must be reading from a file, otherwise
// expect addresses on the commandline
if(ops.size() == 0) {
if(_config.targetsFile.length() == 0) {
Logger::log(LogLevel::Error, "Missing arguments");
usage();
return 1;
}
} else {
for(unsigned int i = 0; i < ops.size(); i++) {
if(!Address::verifyAddress(ops[i])) {
Logger::log(LogLevel::Error, "Invalid address '" + ops[i] + "'");
return 1;
}
_config.targets.push_back(ops[i]);
}
}
// Calculate where to start and end in the keyspace when the --share option is used
if(optShares) {
Logger::log(LogLevel::Info, "Share " + util::format(shareIdx) + " of " + util::format(numShares));
secp256k1::uint256 numKeys = _config.endKey - _config.nextKey + 1;
secp256k1::uint256 diff = numKeys.mod(numShares);
numKeys = numKeys - diff;
secp256k1::uint256 shareSize = numKeys.div(numShares);
secp256k1::uint256 startPos = _config.nextKey + (shareSize * (shareIdx - 1));
if(shareIdx < numShares) {
secp256k1::uint256 endPos = _config.nextKey + (shareSize * (shareIdx)) - 1;
_config.endKey = endPos;
}
_config.nextKey = startPos;
_config.startKey = startPos;
}
// Check option for compressed, uncompressed, or both
if(optCompressed && optUncompressed) {
_config.compression = PointCompressionType::BOTH;
} else if(optCompressed) {
_config.compression = PointCompressionType::COMPRESSED;
} else if(optUncompressed) {
_config.compression = PointCompressionType::UNCOMPRESSED;
}
if(_config.checkpointFile.length() > 0) {
readCheckpointFile();
}
return run();
}