/* * Bitcoin P2PK Bruteforce ULTRA-OPTIMIZED * Versione CPU ottimizzata per massime prestazioni * * OTTIMIZZAZIONI IMPLEMENTATE: * - Batch EC point addition in coordinate Jacobiane (1 moltiplicazione scalare * + N addizioni EC affine+affine, tutte con Z1=1) invece di N chiamate a * secp256k1_ec_pubkey_combine * - Batch modular inversion (trucco di Montgomery): 1 sola inversione di campo * per batch di N chiavi invece di N inversioni separate * - Zero-copy: matching diretto sui byte grezzi X||Y, niente oggetti * secp256k1_pubkey nel loop caldo * - SIMD-friendly Bloom filter * - Cache-aligned memory * - CPU prefetching hints * * DISCLAIMER: Solo per scopi educativi e di ricerca */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(__x86_64__) || defined(__i386__) || defined(_M_X64) || defined(_M_IX86) #include // Per SIMD intrinsics (SSE/AVX) su x86 #endif // ============================================================================ // CONFIGURAZIONE OTTIMIZZATA // ============================================================================ #define EC_BATCH_SIZE 256 // Genera 256 chiavi consecutive con EC addition #define EC_BATCH_MULT (EC_BATCH_SIZE - 1) // Multipli di G precalcolati necessari (2G..256G) #define SYNC_BATCH 50000 // Sincronizza contatori ogni 50K chiavi (aggiornamento terminale fluido) #define MAX_THREADS 256 #define BLOOM_SIZE_BITS 26 // 64MB Bloom filter #define USE_BLOOM_FILTER 1 #define USE_EC_BATCH 1 // Abilita batch EC point addition #define PROGRESS_INTERVAL_SEC 2 // Intervallo di aggiornamento statistiche a terminale // ============================================================================ // STRUTTURE DATI OTTIMIZZATE // ============================================================================ // Struttura per memorizzare chiavi target struct TargetKey { uint8_t pubkey[65]; char hex[131]; }; // Hash ottimizzato per chiave grezza X||Y (64 byte, formato non compresso senza il prefisso 04) struct RawKeyHash { size_t operator()(const std::array& key) const { const uint64_t* p = reinterpret_cast(key.data()); return p[0] ^ p[1] ^ p[2]; } }; struct RawKeyEqual { bool operator()(const std::array& a, const std::array& b) const { return memcmp(a.data(), b.data(), 64) == 0; } }; #if USE_BLOOM_FILTER // Bloom Filter ottimizzato con prefetching e cache alignment class __attribute__((aligned(64))) BloomFilter { private: uint64_t* bits; size_t size_bits; size_t size_words; size_t mask; // Hash functions ottimizzate - usa direttamente i 64 bytes della chiave grezza X||Y inline uint64_t hash1(const uint8_t* data) const { const uint64_t* p = (const uint64_t*)data; return p[0] ^ (p[1] << 7); } inline uint64_t hash2(const uint8_t* data) const { const uint64_t* p = (const uint64_t*)data; return p[2] ^ (p[3] << 13); } inline uint64_t hash3(const uint8_t* data) const { const uint64_t* p = (const uint64_t*)data; return p[4] ^ (p[5] << 19); } public: BloomFilter(size_t bits_exponent) { size_bits = 1ULL << bits_exponent; size_words = size_bits / 64; mask = size_bits - 1; // Alloca memoria allineata per cache lines (64 bytes) int ret = posix_memalign((void**)&bits, 64, size_words * sizeof(uint64_t)); if (ret != 0) { fprintf(stderr, "[ERROR] posix_memalign failed\n"); exit(1); } memset(bits, 0, size_words * sizeof(uint64_t)); } ~BloomFilter() { free(bits); } // data: 64 byte grezzi X||Y (chiave pubblica non compressa senza prefisso 04) void add(const uint8_t* data) { uint64_t h1 = hash1(data) & mask; uint64_t h2 = hash2(data) & mask; uint64_t h3 = hash3(data) & mask; bits[h1 >> 6] |= (1ULL << (h1 & 63)); bits[h2 >> 6] |= (1ULL << (h2 & 63)); bits[h3 >> 6] |= (1ULL << (h3 & 63)); } // Verifica ultra-veloce con prefetching inline bool might_contain(const uint8_t* data) const { uint64_t h1 = hash1(data) & mask; uint64_t h2 = hash2(data) & mask; uint64_t h3 = hash3(data) & mask; // Prefetch delle cache lines __builtin_prefetch(&bits[h1 >> 6], 0, 3); __builtin_prefetch(&bits[h2 >> 6], 0, 3); __builtin_prefetch(&bits[h3 >> 6], 0, 3); return (bits[h1 >> 6] & (1ULL << (h1 & 63))) && (bits[h2 >> 6] & (1ULL << (h2 & 63))) && (bits[h3 >> 6] & (1ULL << (h3 & 63))); } }; static BloomFilter* bloom_filter = NULL; #endif // ============================================================================ // VARIABILI GLOBALI // ============================================================================ static volatile int keep_running = 1; static secp256k1_context* ctx = NULL; static std::vector target_keys; static std::unordered_map, int, RawKeyHash, RawKeyEqual> target_map; static uint64_t attempts_per_thread[MAX_THREADS] = {0}; static time_t start_time; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static FILE* log_file = NULL; static int num_threads = 0; #if USE_EC_BATCH // Primo campo di secp256k1: p = 2^256 - 2^32 - 977 static mpz_t field_p; // Multipli precalcolati del generatore: precomp_g[i] = (i+1)*G, per i = 0..EC_BATCH_MULT-1 // (coordinate affini, condivisi in sola lettura tra i thread dopo l'inizializzazione) static mpz_t precomp_gx[EC_BATCH_MULT]; static mpz_t precomp_gy[EC_BATCH_MULT]; #endif // ============================================================================ // STRUTTURA THREAD // ============================================================================ struct ThreadData { int thread_id; uint64_t seed; uint8_t range_start[32]; uint8_t range_end[32]; }; // ============================================================================ // UTILITY FUNCTIONS // ============================================================================ int get_num_threads() { int num = (int)sysconf(_SC_NPROCESSORS_ONLN); if (num < 1) num = 1; if (num > 1) num--; if (num > MAX_THREADS) num = MAX_THREADS; return num; } void set_thread_affinity(int core_id) { cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core_id, &cpuset); pthread_t current_thread = pthread_self(); pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset); } void partition_keyspace(int thread_id, int total_threads, uint8_t* range_start, uint8_t* range_end) { memset(range_start, 0, 32); memset(range_end, 0xFF, 32); uint64_t partition_size = UINT64_MAX / total_threads; uint64_t start = partition_size * thread_id; uint64_t end = (thread_id == total_threads - 1) ? UINT64_MAX : (partition_size * (thread_id + 1) - 1); for (int i = 0; i < 8; i++) { range_start[i] = (uint8_t)(start >> (56 - i * 8)); range_end[i] = (uint8_t)(end >> (56 - i * 8)); } } void sigint_handler(int sig) { (void)sig; keep_running = 0; printf("\n\n[!] Interruzione rilevata, chiusura in corso...\n"); } void bytes_to_hex(const uint8_t* bytes, size_t len, char* hex) { for (size_t i = 0; i < len; i++) { sprintf(hex + (i * 2), "%02x", bytes[i]); } hex[len * 2] = '\0'; } int hex_to_bytes(const char* hex, uint8_t* bytes, size_t len) { if (strlen(hex) != len * 2) return 0; for (size_t i = 0; i < len; i++) { sscanf(hex + (i * 2), "%2hhx", &bytes[i]); } return 1; } // ============================================================================ // CARICAMENTO TARGET KEYS // ============================================================================ int load_target_keys(const char* filename) { #if USE_BLOOM_FILTER bloom_filter = new BloomFilter(BLOOM_SIZE_BITS); printf("[+] Bloom filter inizializzato: %llu MB\n", (unsigned long long)((1ULL << BLOOM_SIZE_BITS) / 8 / 1024 / 1024)); #endif std::ifstream file(filename); if (!file.is_open()) { fprintf(stderr, "[ERROR] Impossibile aprire %s\n", filename); return 0; } std::string line; int count = 0; std::getline(file, line); // Skip header while (std::getline(file, line)) { if (line.empty()) continue; std::string pubkey_hex = line; pubkey_hex.erase(remove_if(pubkey_hex.begin(), pubkey_hex.end(), isspace), pubkey_hex.end()); if (pubkey_hex.length() != 130 && pubkey_hex.length() != 128) { continue; } if (pubkey_hex.length() == 128) { pubkey_hex = "04" + pubkey_hex; } TargetKey key; if (hex_to_bytes(pubkey_hex.c_str(), key.pubkey, 65)) { strcpy(key.hex, pubkey_hex.c_str()); // Valida che sia un punto valido sulla curva (scarta chiavi corrotte) secp256k1_pubkey pubkey_obj; if (secp256k1_ec_pubkey_parse(ctx, &pubkey_obj, key.pubkey, 65)) { target_keys.push_back(key); // Chiave di lookup: X||Y grezzi (64 byte), senza il prefisso 04. // È lo stesso formato prodotto dal loop di generazione, quindi il // confronto è un memcmp diretto, senza passare da secp256k1_pubkey. std::array raw; memcpy(raw.data(), key.pubkey + 1, 64); target_map[raw] = count; #if USE_BLOOM_FILTER bloom_filter->add(raw.data()); #endif count++; } } } file.close(); printf("[+] Caricate %d chiavi pubbliche target\n", count); printf("[+] Target map size: %zu entries\n", target_map.size()); return count; } // ============================================================================ // ARITMETICA DI CAMPO (GMP) PER BATCH EC POINT ADDITION // ============================================================================ #if USE_EC_BATCH // Converte un intero mod p in 32 byte big-endian (con zero-padding) static inline void mpz_to_be32(const mpz_t x, uint8_t out[32]) { memset(out, 0, 32); size_t count = 0; mpz_export(out, &count, 1, 1, 1, 0, x); if (count > 0 && count < 32) { memmove(out + (32 - count), out, count); memset(out, 0, 32 - count); } } // Converte 32 byte big-endian in un intero GMP static inline void be32_to_mpz(mpz_t x, const uint8_t in[32]) { mpz_import(x, 32, 1, 1, 1, 0, in); } // Buffer di scratch riutilizzabili per l'addizione EC (evita alloc/dealloc per ogni chiave) struct EcScratch { mpz_t H, HH, HHH, r, t1, t2; void init() { mpz_inits(H, HH, HHH, r, t1, t2, (mpz_ptr)0); } void clear_all() { mpz_clears(H, HH, HHH, r, t1, t2, (mpz_ptr)0); } }; // Addizione di due punti affini (a=0, curva secp256k1), risultato in Jacobiane. // Formule "madd" specializzate per Z1=1 (il primo punto è sempre P0, appena // generato con una singola moltiplicazione scalare via libsecp256k1): // H = x2 - x1 // HH = H^2 // HHH = H*HH // r = y2 - y1 // X3 = r^2 - HHH - 2*x1*HH // Y3 = r*(x1*HH - X3) - y1*HHH // Z3 = H // // NOTA: se H == 0 (x1 == x2 mod p, evento con probabilità ~2^-256 per punti // indipendenti) il risultato non è definito da queste formule; in quel caso // impostiamo Z3 = 0 per marcare il punto come "da ignorare" nel batch. static inline void ec_add_affine_affine(const mpz_t x1, const mpz_t y1, const mpz_t x2, const mpz_t y2, mpz_t X3, mpz_t Y3, mpz_t Z3, EcScratch& s) { mpz_sub(s.H, x2, x1); mpz_mod(s.H, s.H, field_p); if (mpz_sgn(s.H) == 0) { mpz_set_ui(Z3, 0); return; } mpz_mul(s.HH, s.H, s.H); mpz_mod(s.HH, s.HH, field_p); mpz_mul(s.HHH, s.H, s.HH); mpz_mod(s.HHH, s.HHH, field_p); mpz_sub(s.r, y2, y1); mpz_mod(s.r, s.r, field_p); // X3 = r^2 - HHH - 2*x1*HH mpz_mul(X3, s.r, s.r); mpz_sub(X3, X3, s.HHH); mpz_mul(s.t1, x1, s.HH); mpz_mul_2exp(s.t1, s.t1, 1); mpz_sub(X3, X3, s.t1); mpz_mod(X3, X3, field_p); // Y3 = r*(x1*HH - X3) - y1*HHH mpz_mul(s.t1, x1, s.HH); mpz_sub(s.t1, s.t1, X3); mpz_mul(Y3, s.r, s.t1); mpz_mul(s.t2, y1, s.HHH); mpz_sub(Y3, Y3, s.t2); mpz_mod(Y3, Y3, field_p); mpz_set(Z3, s.H); } // La batch inversion vera e propria (trucco di Montgomery: 1 sola mpz_invert // per l'intero batch, saltando gli eventuali punti non validi) è inline in // worker_thread, perché deve intrecciarsi con il vettore `valid[]`. #endif // USE_EC_BATCH // ============================================================================ // PRECOMPUTE EC GENERATOR MULTIPLES // ============================================================================ #if USE_EC_BATCH void precompute_generator_multiples() { printf("[+] Precomputing EC generator multiples (2G, ..., %dG)...\n", EC_BATCH_SIZE); uint8_t privkey[32]; for (int i = 0; i < EC_BATCH_MULT; i++) { memset(privkey, 0, 32); // precomp_g[i] = (i+1)*G, per i=0..EC_BATCH_MULT-1 -> valori 1..EC_BATCH_MULT uint32_t value = (uint32_t)(i + 1); privkey[31] = (uint8_t)(value & 0xFF); privkey[30] = (uint8_t)((value >> 8) & 0xFF); secp256k1_pubkey pk; if (!secp256k1_ec_pubkey_create(ctx, &pk, privkey)) { fprintf(stderr, "[ERROR] Failed to precompute %dG\n", i + 1); exit(1); } unsigned char buf[65]; size_t outlen = 65; secp256k1_ec_pubkey_serialize(ctx, buf, &outlen, &pk, SECP256K1_EC_UNCOMPRESSED); mpz_init(precomp_gx[i]); mpz_init(precomp_gy[i]); be32_to_mpz(precomp_gx[i], buf + 1); be32_to_mpz(precomp_gy[i], buf + 33); } printf("[+] Precomputation complete!\n"); } #endif // ============================================================================ // CHIAVE PRIVATA RANDOMIZZATA // ============================================================================ void init_random_privkey_in_range(uint8_t* privkey, uint64_t* seed, const uint8_t* range_start, const uint8_t* /*range_end*/) { for (int i = 0; i < 32; i++) { *seed ^= *seed << 13; *seed ^= *seed >> 7; *seed ^= *seed << 17; privkey[i] = (uint8_t)(*seed & 0xFF); } for (int i = 0; i < 8; i++) { privkey[i] = range_start[i]; } } // Incremento ottimizzato a 64-bit static inline void increment_privkey(uint8_t* privkey) { uint64_t* p64 = (uint64_t*)privkey; if (++p64[3]) return; if (++p64[2]) return; if (++p64[1]) return; ++p64[0]; } // Incremento di N static inline void add_to_privkey(uint8_t* privkey, uint64_t n) { uint64_t* p64 = (uint64_t*)privkey; // Add to least significant word (little-endian) uint64_t old = p64[3]; p64[3] += n; // Handle carry if (p64[3] < old) { if (++p64[2] == 0) { if (++p64[1] == 0) { ++p64[0]; } } } } // Somma un piccolo intero a un array di 32 byte interpretato come intero // big-endian standard (byte[31] = LSB), lo stesso formato che secp256k1 si // aspetta per una private key. NON intercambiabile con add_to_privkey/ // increment_privkey sopra: quelle due, per velocità, trattano l'array come // 4 word a 64 bit in ordine nativo (little-endian sulle CPU x86), quindi // avanzano la ricerca in un ordine "rimescolato" ma comunque bigettivo sullo // spazio delle chiavi — va benissimo per iterare, ma NON per ricostruire lo // scalare esatto corrispondente a un punto EC calcolato con aritmetica reale // (come batch[i] = P0 + (i+1)*G). Per quello serve questa versione corretta. static inline void add_small_be256(uint8_t* be, uint32_t n) { for (int i = 31; i >= 0 && n; i--) { uint32_t sum = be[i] + (n & 0xFF); be[i] = (uint8_t)sum; n = (n >> 8) + (sum >> 8); } } // ============================================================================ // MATCH CHECKING OTTIMIZZATO // ============================================================================ // data: 64 byte grezzi X||Y (chiave pubblica non compressa senza prefisso 04) static inline int check_match_fast_raw(const uint8_t* data) { #if USE_BLOOM_FILTER // Prima passa: Bloom filter if (!bloom_filter->might_contain(data)) { return -1; // Sicuramente non presente } #endif std::array key; memcpy(key.data(), data, 64); auto it = target_map.find(key); if (it != target_map.end()) { return it->second; // Indice nella lista target_keys } return -1; } // ============================================================================ // SALVATAGGIO CHIAVE TROVATA // ============================================================================ void save_found_key(const uint8_t* privkey, int target_index) { pthread_mutex_lock(&mutex); char priv_hex[65]; bytes_to_hex(privkey, 32, priv_hex); printf("\n\n"); printf("========================================\n"); printf("🎯 CHIAVE TROVATA! 🎯\n"); printf("========================================\n"); printf("Private Key: %s\n", priv_hex); printf("Public Key: %s\n", target_keys[target_index].hex); printf("========================================\n\n"); FILE* found_file = fopen("found_keys.txt", "a"); if (found_file) { time_t now = time(NULL); fprintf(found_file, "\n=== FOUND at %s", ctime(&now)); fprintf(found_file, "Private Key: %s\n", priv_hex); fprintf(found_file, "Public Key: %s\n", target_keys[target_index].hex); fprintf(found_file, "========================================\n"); fclose(found_file); } pthread_mutex_unlock(&mutex); } // ============================================================================ // LOGGING // ============================================================================ void format_number(uint64_t num, char* buffer) { if (num >= 1000000000000ULL) { sprintf(buffer, "%.2fT", num / 1000000000000.0); } else if (num >= 1000000000ULL) { sprintf(buffer, "%.2fG", num / 1000000000.0); } else if (num >= 1000000ULL) { sprintf(buffer, "%.2fM", num / 1000000.0); } else if (num >= 1000ULL) { sprintf(buffer, "%.2fK", num / 1000.0); } else { sprintf(buffer, "%lu", num); } } // Velocità istantanea: somma dei tentativi di tutti i thread nella finestra // trascorsa dall'ultima chiamata (non media cumulata dall'avvio), così il // numero mostrato riflette il ritmo REALE corrente anche su run lunghe. void log_progress() { pthread_mutex_lock(&mutex); static uint64_t last_total = 0; static struct timeval last_tv = {0, 0}; struct timeval now_tv; gettimeofday(&now_tv, NULL); if (last_tv.tv_sec == 0 && last_tv.tv_usec == 0) { // Prima chiamata: usa l'avvio dei thread come inizio finestra, non "adesso" // (altrimenti la finestra sarebbe ~0s e il rate esploderebbe verso l'infinito) last_tv.tv_sec = start_time; last_tv.tv_usec = 0; } time_t now = time(NULL); double elapsed_total = difftime(now, start_time); if (elapsed_total < 1) elapsed_total = 1; uint64_t total = 0; for (int i = 0; i < num_threads; i++) { total += attempts_per_thread[i]; } double window_sec = (now_tv.tv_sec - last_tv.tv_sec) + (now_tv.tv_usec - last_tv.tv_usec) / 1e6; if (window_sec < 0.001) window_sec = 0.001; uint64_t delta = total - last_total; double instant_rate = delta / window_sec; char total_str[32]; char rate_str[32]; format_number(total, total_str); format_number((uint64_t)instant_rate, rate_str); printf("[INFO] Tentativi totali: %s | Velocità: %s keys/sec (tutti i core) | Tempo: %.0fs\n", total_str, rate_str, elapsed_total); if (log_file) { fprintf(log_file, "%ld,%lu,%.2f\n", now, total, instant_rate); fflush(log_file); } last_total = total; last_tv = now_tv; pthread_mutex_unlock(&mutex); } // ============================================================================ // WORKER THREAD - VERSIONE ULTRA-OTTIMIZZATA // ============================================================================ void* worker_thread(void* arg) { ThreadData* data = (ThreadData*)arg; int thread_id = data->thread_id; uint64_t seed = data->seed; set_thread_affinity(thread_id); // Pre-alloca buffer uint8_t privkey[32]; uint64_t local_attempts = 0; init_random_privkey_in_range(privkey, &seed, data->range_start, data->range_end); char privkey_start_hex[65]; bytes_to_hex(privkey, 32, privkey_start_hex); printf("[+] Thread %d avviato su core %d\n", thread_id, thread_id); printf(" Privkey iniziale: %s\n", privkey_start_hex); // ======================================================================== // LOOP PRINCIPALE CON EC BATCH PROCESSING (Jacobian + batch inversion) // ======================================================================== #if USE_EC_BATCH // Buffer persistenti per thread: X/Y/Z Jacobiani dei punti P0 + iG (i=1..EC_BATCH_MULT) mpz_t x0, y0; mpz_t Xj[EC_BATCH_MULT], Yj[EC_BATCH_MULT], Zj[EC_BATCH_MULT]; mpz_t invZ[EC_BATCH_MULT], prefix[EC_BATCH_MULT]; mpz_t inv_tmp, zinv2, zinv3, ax, ay; EcScratch scratch; mpz_inits(x0, y0, inv_tmp, zinv2, zinv3, ax, ay, (mpz_ptr)0); for (int i = 0; i < EC_BATCH_MULT; i++) { mpz_inits(Xj[i], Yj[i], Zj[i], invZ[i], prefix[i], (mpz_ptr)0); } scratch.init(); uint8_t rawkey[64]; uint8_t found_privkey[32]; while (keep_running) { secp256k1_pubkey pubkey0; if (!secp256k1_ec_pubkey_create(ctx, &pubkey0, privkey)) { increment_privkey(privkey); continue; } unsigned char buf65[65]; size_t outlen = 65; secp256k1_ec_pubkey_serialize(ctx, buf65, &outlen, &pubkey0, SECP256K1_EC_UNCOMPRESSED); be32_to_mpz(x0, buf65 + 1); be32_to_mpz(y0, buf65 + 33); // Chiave 0 del batch: è P0 stesso, nessuna conversione affine necessaria int match_idx = check_match_fast_raw(buf65 + 1); if (__builtin_expect(match_idx >= 0, 0)) { save_found_key(privkey, match_idx); } // Genera le restanti EC_BATCH_MULT chiavi: batch[i] = P0 + (i+1)*G, in Jacobiane int valid_count = 0; bool valid[EC_BATCH_MULT]; for (int i = 0; i < EC_BATCH_MULT; i++) { ec_add_affine_affine(x0, y0, precomp_gx[i], precomp_gy[i], Xj[i], Yj[i], Zj[i], scratch); valid[i] = (mpz_sgn(Zj[i]) != 0); if (valid[i]) valid_count++; } // Batch inversion (trucco di Montgomery): una sola mpz_invert per l'intero batch if (valid_count > 0) { int last = -1; for (int i = 0; i < EC_BATCH_MULT; i++) { if (!valid[i]) continue; if (last < 0) { mpz_set(prefix[i], Zj[i]); } else { mpz_mul(prefix[i], prefix[last], Zj[i]); mpz_mod(prefix[i], prefix[i], field_p); } last = i; } mpz_invert(inv_tmp, prefix[last], field_p); // inv_tmp = 1 / prodotto totale for (int i = last; i >= 0; i--) { if (!valid[i]) continue; int prev = -1; for (int j = i - 1; j >= 0; j--) { if (valid[j]) { prev = j; break; } } if (prev >= 0) { mpz_mul(invZ[i], inv_tmp, prefix[prev]); mpz_mod(invZ[i], invZ[i], field_p); } else { mpz_set(invZ[i], inv_tmp); } mpz_mul(inv_tmp, inv_tmp, Zj[i]); mpz_mod(inv_tmp, inv_tmp, field_p); } // Converte ogni punto Jacobiano in affine e verifica il match for (int i = 0; i < EC_BATCH_MULT && keep_running; i++) { if (!valid[i]) continue; mpz_mul(zinv2, invZ[i], invZ[i]); mpz_mod(zinv2, zinv2, field_p); mpz_mul(zinv3, zinv2, invZ[i]); mpz_mod(zinv3, zinv3, field_p); mpz_mul(ax, Xj[i], zinv2); mpz_mod(ax, ax, field_p); mpz_mul(ay, Yj[i], zinv3); mpz_mod(ay, ay, field_p); mpz_to_be32(ax, rawkey); mpz_to_be32(ay, rawkey + 32); match_idx = check_match_fast_raw(rawkey); if (__builtin_expect(match_idx >= 0, 0)) { memcpy(found_privkey, privkey, 32); add_small_be256(found_privkey, (uint32_t)(i + 1)); // batch[i] = privkey + (i+1) save_found_key(found_privkey, match_idx); } } } local_attempts += EC_BATCH_SIZE; add_to_privkey(privkey, EC_BATCH_SIZE); // Aggiorna contatore globale periodicamente // (modulo, non maschera bitwise: SYNC_BATCH non è una potenza di due) if (local_attempts % SYNC_BATCH < EC_BATCH_SIZE) { attempts_per_thread[thread_id] = local_attempts; } } scratch.clear_all(); mpz_clears(x0, y0, inv_tmp, zinv2, zinv3, ax, ay, (mpz_ptr)0); for (int i = 0; i < EC_BATCH_MULT; i++) { mpz_clears(Xj[i], Yj[i], Zj[i], invZ[i], prefix[i], (mpz_ptr)0); } #else // VERSIONE STANDARD (fallback senza batch) while (keep_running) { secp256k1_pubkey pubkey_obj; for (int batch = 0; batch < SYNC_BATCH; batch++) { if (__builtin_expect(secp256k1_ec_pubkey_create(ctx, &pubkey_obj, privkey), 1)) { unsigned char buf65[65]; size_t outlen = 65; secp256k1_ec_pubkey_serialize(ctx, buf65, &outlen, &pubkey_obj, SECP256K1_EC_UNCOMPRESSED); int match_idx = check_match_fast_raw(buf65 + 1); if (__builtin_expect(match_idx >= 0, 0)) { save_found_key(privkey, match_idx); } } increment_privkey(privkey); } local_attempts += SYNC_BATCH; attempts_per_thread[thread_id] = local_attempts; if (__builtin_expect(!keep_running, 0)) break; } #endif printf("[+] Thread %d terminato (%lu tentativi)\n", thread_id, local_attempts); return NULL; } // ============================================================================ // MAIN // ============================================================================ int main(int argc, char** argv) { printf("========================================\n"); printf(" Bitcoin P2PK Bruteforce v2.0 ULTRA\n"); printf(" CPU-Optimized Edition\n"); printf(" SOLO PER SCOPI EDUCATIVI\n"); printf("========================================\n\n"); const char* target_file = "target_keys.txt"; if (argc > 1) { target_file = argv[1]; } // Inizializza secp256k1 printf("[+] Inizializzazione secp256k1...\n"); ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); if (!ctx) { fprintf(stderr, "[ERROR] Impossibile creare contesto secp256k1\n"); return 1; } // Randomizza contesto unsigned char random_seed[32]; FILE* urandom = fopen("/dev/urandom", "rb"); if (urandom) { size_t bytes_read = fread(random_seed, 1, 32, urandom); fclose(urandom); if (bytes_read == 32) { if (secp256k1_context_randomize(ctx, random_seed) != 1) { fprintf(stderr, "[WARNING] secp256k1_context_randomize failed\n"); } } } #if USE_EC_BATCH // Inizializza il primo campo di secp256k1: p = 2^256 - 2^32 - 977 mpz_init_set_str(field_p, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", 16); // Precompute EC multiples precompute_generator_multiples(); #endif // Carica target keys printf("[+] Caricamento chiavi target da %s...\n", target_file); if (load_target_keys(target_file) == 0) { fprintf(stderr, "[ERROR] Nessuna chiave target caricata\n"); secp256k1_context_destroy(ctx); return 1; } // Setup signal handler signal(SIGINT, sigint_handler); signal(SIGTERM, sigint_handler); // Apri file di log log_file = fopen("progress.csv", "w"); if (log_file) { fprintf(log_file, "timestamp,attempts,keys_per_sec\n"); } // Rileva numero di thread num_threads = get_num_threads(); printf("[+] CPU rilevata: %d thread disponibili\n", num_threads); printf("[+] Batch size: %d keys per iteration\n", EC_BATCH_SIZE); start_time = time(NULL); srand(time(NULL)); // Crea threads pthread_t threads[MAX_THREADS]; ThreadData thread_data[MAX_THREADS]; printf("[+] Avvio %d thread worker...\n", num_threads); for (int i = 0; i < num_threads; i++) { thread_data[i].thread_id = i; uint64_t base_seed = (uint64_t)time(NULL); uint64_t thread_offset = ((uint64_t)i << 48); uint64_t random_part = ((uint64_t)rand() << 32) | rand(); thread_data[i].seed = base_seed ^ thread_offset ^ random_part; partition_keyspace(i, num_threads, thread_data[i].range_start, thread_data[i].range_end); printf(" Thread %d: range 0x%02x%02x%02x%02x... (seed: %016lx)\n", i, thread_data[i].range_start[0], thread_data[i].range_start[1], thread_data[i].range_start[2], thread_data[i].range_start[3], thread_data[i].seed); pthread_create(&threads[i], NULL, worker_thread, &thread_data[i]); } printf("\n"); // Loop principale while (keep_running) { sleep(PROGRESS_INTERVAL_SEC); log_progress(); } // Attendi terminazione threads printf("[+] Attesa terminazione threads...\n"); for (int i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } // Statistiche finali printf("\n========================================\n"); printf(" STATISTICHE FINALI\n"); printf("========================================\n"); uint64_t total = 0; char thread_str[32]; for (int i = 0; i < num_threads; i++) { total += attempts_per_thread[i]; format_number(attempts_per_thread[i], thread_str); printf("Thread %d: %s tentativi\n", i, thread_str); } time_t end_time = time(NULL); double elapsed = difftime(end_time, start_time); if (elapsed < 1) elapsed = 1; char total_str[32]; char rate_str[32]; format_number(total, total_str); format_number((uint64_t)(total / elapsed), rate_str); printf("----------------------------------------\n"); printf("Totale tentativi: %s\n", total_str); printf("Tempo totale: %.0f secondi\n", elapsed); printf("Velocità media: %s keys/sec\n", rate_str); printf("========================================\n\n"); // Cleanup if (log_file) fclose(log_file); secp256k1_context_destroy(ctx); #if USE_BLOOM_FILTER delete bloom_filter; #endif printf("[+] Programma terminato\n"); return 0; }