Ottimizza batch EC del bruteforce con Jacobiane + batch inversion GMP

Sostituisce le N chiamate a secp256k1_ec_pubkey_combine per batch (una
per chiave, ciascuna con una inversione di campo interna) con addizione
EC in coordinate Jacobiane calcolata a mano (formule madd specializzate
per Z1=1) e un'unica inversione modulare per l'intero batch di 256
chiavi tramite il trucco di Montgomery (GMP, già linkata via -lgmp). Il
matching ora confronta byte grezzi X||Y invece di oggetti
secp256k1_pubkey, eliminando overhead di parse/serialize nel loop caldo.

Corregge inoltre due bug:
- off-by-one nel codice combine-based originale: usava
  precomputed_G[i] invece di precomputed_G[i-1], per cui una chiave
  trovata sarebbe stata riportata con la privkey sbagliata
- add_to_privkey (che tratta l'array a 32 byte come 4 word native a
  64 bit, non big-endian) veniva usata per ricostruire la privkey
  esatta di un match nel batch; sostituita con add_small_be256, la
  cui aritmetica big-endian corrisponde a quella usata da secp256k1
  e dai punti EC precalcolati

Migliora inoltre il reporting a terminale:
- aggiornamento ogni 2s (PROGRESS_INTERVAL_SEC) invece di 10s
- velocità istantanea (tentativi nella finestra trascorsa, via
  gettimeofday) invece della media cumulata dall'avvio, così il
  numero riflette il ritmo reale anche su run lunghe
- corretto il sync dei contatori per-thread: usava una maschera
  bitwise che assumeva SYNC_BATCH potenza di due (100000 non lo è),
  ora un modulo esplicito

Verificato con test standalone (formule EC confrontate con
secp256k1_ec_pubkey_create indipendente), test end-to-end con privkey
nota, e nessun falso positivo su chiavi pubbliche valide casuali.
This commit is contained in:
2026-07-03 15:41:57 +02:00
parent 1a91b81de5
commit adb608df38
+316 -69
View File
@@ -3,11 +3,14 @@
* Versione CPU ottimizzata per massime prestazioni * Versione CPU ottimizzata per massime prestazioni
* *
* OTTIMIZZAZIONI IMPLEMENTATE: * OTTIMIZZAZIONI IMPLEMENTATE:
* - Batch EC point addition (genera N chiavi con 1 moltiplicazione + N addizioni) * - Batch EC point addition in coordinate Jacobiane (1 moltiplicazione scalare
* - Zero-copy: niente serializzazione fino al match * + N addizioni EC affine+affine, tutte con Z1=1) invece di N chiamate a
* - Hash diretto su secp256k1_pubkey raw data * 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 * - SIMD-friendly Bloom filter
* - Precomputed lookup tables
* - Cache-aligned memory * - Cache-aligned memory
* - CPU prefetching hints * - CPU prefetching hints
* *
@@ -22,9 +25,11 @@
#include <signal.h> #include <signal.h>
#include <unistd.h> #include <unistd.h>
#include <secp256k1.h> #include <secp256k1.h>
#include <gmp.h>
#include <pthread.h> #include <pthread.h>
#include <sys/time.h> #include <sys/time.h>
#include <vector> #include <vector>
#include <array>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>
#include <fstream> #include <fstream>
@@ -41,12 +46,14 @@
// CONFIGURAZIONE OTTIMIZZATA // CONFIGURAZIONE OTTIMIZZATA
// ============================================================================ // ============================================================================
#define EC_BATCH_SIZE 256 // Genera 256 chiavi consecutive con EC addition (+25% speed) #define EC_BATCH_SIZE 256 // Genera 256 chiavi consecutive con EC addition
#define SYNC_BATCH 100000 // Sincronizza contatori ogni 100K chiavi #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 MAX_THREADS 256
#define BLOOM_SIZE_BITS 26 // 64MB Bloom filter #define BLOOM_SIZE_BITS 26 // 64MB Bloom filter
#define USE_BLOOM_FILTER 1 #define USE_BLOOM_FILTER 1
#define USE_EC_BATCH 1 // Abilita batch EC point addition #define USE_EC_BATCH 1 // Abilita batch EC point addition
#define PROGRESS_INTERVAL_SEC 2 // Intervallo di aggiornamento statistiche a terminale
// ============================================================================ // ============================================================================
// STRUTTURE DATI OTTIMIZZATE // STRUTTURE DATI OTTIMIZZATE
@@ -58,18 +65,17 @@ struct TargetKey {
char hex[131]; char hex[131];
}; };
// Hash ottimizzato per raw secp256k1_pubkey data (64 bytes) // Hash ottimizzato per chiave grezza X||Y (64 byte, formato non compresso senza il prefisso 04)
struct PubkeyRawHash { struct RawKeyHash {
size_t operator()(const secp256k1_pubkey& key) const { size_t operator()(const std::array<uint8_t, 64>& key) const {
const uint64_t* p = reinterpret_cast<const uint64_t*>(key.data); const uint64_t* p = reinterpret_cast<const uint64_t*>(key.data());
// XOR rapido dei primi 64 bit
return p[0] ^ p[1] ^ p[2]; return p[0] ^ p[1] ^ p[2];
} }
}; };
struct PubkeyRawEqual { struct RawKeyEqual {
bool operator()(const secp256k1_pubkey& a, const secp256k1_pubkey& b) const { bool operator()(const std::array<uint8_t, 64>& a, const std::array<uint8_t, 64>& b) const {
return memcmp(a.data, b.data, 64) == 0; return memcmp(a.data(), b.data(), 64) == 0;
} }
}; };
@@ -82,7 +88,7 @@ private:
size_t size_words; size_t size_words;
size_t mask; size_t mask;
// Hash functions ottimizzate - usa direttamente i 64 bytes interni // Hash functions ottimizzate - usa direttamente i 64 bytes della chiave grezza X||Y
inline uint64_t hash1(const uint8_t* data) const { inline uint64_t hash1(const uint8_t* data) const {
const uint64_t* p = (const uint64_t*)data; const uint64_t* p = (const uint64_t*)data;
return p[0] ^ (p[1] << 7); return p[0] ^ (p[1] << 7);
@@ -117,8 +123,8 @@ public:
free(bits); free(bits);
} }
void add(const secp256k1_pubkey* pubkey) { // data: 64 byte grezzi X||Y (chiave pubblica non compressa senza prefisso 04)
const uint8_t* data = pubkey->data; void add(const uint8_t* data) {
uint64_t h1 = hash1(data) & mask; uint64_t h1 = hash1(data) & mask;
uint64_t h2 = hash2(data) & mask; uint64_t h2 = hash2(data) & mask;
uint64_t h3 = hash3(data) & mask; uint64_t h3 = hash3(data) & mask;
@@ -129,8 +135,7 @@ public:
} }
// Verifica ultra-veloce con prefetching // Verifica ultra-veloce con prefetching
inline bool might_contain(const secp256k1_pubkey* pubkey) const { inline bool might_contain(const uint8_t* data) const {
const uint8_t* data = pubkey->data;
uint64_t h1 = hash1(data) & mask; uint64_t h1 = hash1(data) & mask;
uint64_t h2 = hash2(data) & mask; uint64_t h2 = hash2(data) & mask;
uint64_t h3 = hash3(data) & mask; uint64_t h3 = hash3(data) & mask;
@@ -156,7 +161,7 @@ static BloomFilter* bloom_filter = NULL;
static volatile int keep_running = 1; static volatile int keep_running = 1;
static secp256k1_context* ctx = NULL; static secp256k1_context* ctx = NULL;
static std::vector<TargetKey> target_keys; static std::vector<TargetKey> target_keys;
static std::unordered_map<secp256k1_pubkey, int, PubkeyRawHash, PubkeyRawEqual> target_map; static std::unordered_map<std::array<uint8_t, 64>, int, RawKeyHash, RawKeyEqual> target_map;
static uint64_t attempts_per_thread[MAX_THREADS] = {0}; static uint64_t attempts_per_thread[MAX_THREADS] = {0};
static time_t start_time; static time_t start_time;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
@@ -164,8 +169,13 @@ static FILE* log_file = NULL;
static int num_threads = 0; static int num_threads = 0;
#if USE_EC_BATCH #if USE_EC_BATCH
// Precomputed: G, 2G, 3G, ..., 256G per batch EC addition // Primo campo di secp256k1: p = 2^256 - 2^32 - 977
static secp256k1_pubkey precomputed_G[EC_BATCH_SIZE]; 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 #endif
// ============================================================================ // ============================================================================
@@ -273,15 +283,21 @@ int load_target_keys(const char* filename) {
TargetKey key; TargetKey key;
if (hex_to_bytes(pubkey_hex.c_str(), key.pubkey, 65)) { if (hex_to_bytes(pubkey_hex.c_str(), key.pubkey, 65)) {
strcpy(key.hex, pubkey_hex.c_str()); strcpy(key.hex, pubkey_hex.c_str());
target_keys.push_back(key);
// Converti in secp256k1_pubkey per lookup diretto // Valida che sia un punto valido sulla curva (scarta chiavi corrotte)
secp256k1_pubkey pubkey_obj; secp256k1_pubkey pubkey_obj;
if (secp256k1_ec_pubkey_parse(ctx, &pubkey_obj, key.pubkey, 65)) { if (secp256k1_ec_pubkey_parse(ctx, &pubkey_obj, key.pubkey, 65)) {
target_map[pubkey_obj] = count; 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<uint8_t, 64> raw;
memcpy(raw.data(), key.pubkey + 1, 64);
target_map[raw] = count;
#if USE_BLOOM_FILTER #if USE_BLOOM_FILTER
bloom_filter->add(&pubkey_obj); bloom_filter->add(raw.data());
#endif #endif
count++; count++;
} }
@@ -294,29 +310,132 @@ int load_target_keys(const char* filename) {
return count; 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 // PRECOMPUTE EC GENERATOR MULTIPLES
// ============================================================================ // ============================================================================
#if USE_EC_BATCH #if USE_EC_BATCH
void precompute_generator_multiples() { void precompute_generator_multiples() {
printf("[+] Precomputing EC generator multiples (1G, 2G, ..., %dG)...\n", EC_BATCH_SIZE); printf("[+] Precomputing EC generator multiples (2G, ..., %dG)...\n", EC_BATCH_SIZE);
uint8_t privkey[32]; uint8_t privkey[32];
for (int i = 0; i < EC_BATCH_SIZE; i++) { for (int i = 0; i < EC_BATCH_MULT; i++) {
memset(privkey, 0, 32); memset(privkey, 0, 32);
// Imposta il valore (i+1) come privkey // precomp_g[i] = (i+1)*G, per i=0..EC_BATCH_MULT-1 -> valori 1..EC_BATCH_MULT
// Per i=0: privkey=1, per i=255: privkey=256 (0x0100) uint32_t value = (uint32_t)(i + 1);
uint16_t value = i + 1; privkey[31] = (uint8_t)(value & 0xFF);
privkey[31] = (uint8_t)(value & 0xFF); // byte basso privkey[30] = (uint8_t)((value >> 8) & 0xFF);
privkey[30] = (uint8_t)((value >> 8) & 0xFF); // byte alto
if (!secp256k1_ec_pubkey_create(ctx, &precomputed_G[i], privkey)) { secp256k1_pubkey pk;
if (!secp256k1_ec_pubkey_create(ctx, &pk, privkey)) {
fprintf(stderr, "[ERROR] Failed to precompute %dG\n", i + 1); fprintf(stderr, "[ERROR] Failed to precompute %dG\n", i + 1);
exit(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"); printf("[+] Precomputation complete!\n");
@@ -368,20 +487,40 @@ static inline void add_to_privkey(uint8_t* privkey, uint64_t n) {
} }
} }
// 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 // MATCH CHECKING OTTIMIZZATO
// ============================================================================ // ============================================================================
static inline int check_match_fast(const secp256k1_pubkey* pubkey) { // 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 #if USE_BLOOM_FILTER
// Prima passa: Bloom filter // Prima passa: Bloom filter
if (!bloom_filter->might_contain(pubkey)) { if (!bloom_filter->might_contain(data)) {
return -1; // Sicuramente non presente return -1; // Sicuramente non presente
} }
#endif #endif
// Lookup diretto nella hash map (zero copy!) std::array<uint8_t, 64> key;
auto it = target_map.find(*pubkey); memcpy(key.data(), data, 64);
auto it = target_map.find(key);
if (it != target_map.end()) { if (it != target_map.end()) {
return it->second; // Indice nella lista target_keys return it->second; // Indice nella lista target_keys
} }
@@ -438,33 +577,56 @@ void format_number(uint64_t num, char* buffer) {
} }
} }
// 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() { void log_progress() {
pthread_mutex_lock(&mutex); 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); time_t now = time(NULL);
double elapsed = difftime(now, start_time); double elapsed_total = difftime(now, start_time);
if (elapsed < 1) elapsed = 1; if (elapsed_total < 1) elapsed_total = 1;
uint64_t total = 0; uint64_t total = 0;
for (int i = 0; i < num_threads; i++) { for (int i = 0; i < num_threads; i++) {
total += attempts_per_thread[i]; total += attempts_per_thread[i];
} }
double rate = total / elapsed; 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 total_str[32];
char rate_str[32]; char rate_str[32];
format_number(total, total_str); format_number(total, total_str);
format_number((uint64_t)rate, rate_str); format_number((uint64_t)instant_rate, rate_str);
printf("[INFO] Tentativi: %s | Velocità: %s keys/sec | Tempo: %.0fs\n", printf("[INFO] Tentativi totali: %s | Velocità: %s keys/sec (tutti i core) | Tempo: %.0fs\n",
total_str, rate_str, elapsed); total_str, rate_str, elapsed_total);
if (log_file) { if (log_file) {
fprintf(log_file, "%ld,%lu,%.2f\n", now, total, rate); fprintf(log_file, "%ld,%lu,%.2f\n", now, total, instant_rate);
fflush(log_file); fflush(log_file);
} }
last_total = total;
last_tv = now_tv;
pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex);
} }
@@ -481,7 +643,6 @@ void* worker_thread(void* arg) {
// Pre-alloca buffer // Pre-alloca buffer
uint8_t privkey[32]; uint8_t privkey[32];
secp256k1_pubkey pubkey_batch[EC_BATCH_SIZE];
uint64_t local_attempts = 0; uint64_t local_attempts = 0;
init_random_privkey_in_range(privkey, &seed, data->range_start, data->range_end); init_random_privkey_in_range(privkey, &seed, data->range_start, data->range_end);
@@ -492,41 +653,113 @@ void* worker_thread(void* arg) {
printf(" Privkey iniziale: %s\n", privkey_start_hex); printf(" Privkey iniziale: %s\n", privkey_start_hex);
// ======================================================================== // ========================================================================
// LOOP PRINCIPALE CON EC BATCH PROCESSING // LOOP PRINCIPALE CON EC BATCH PROCESSING (Jacobian + batch inversion)
// ======================================================================== // ========================================================================
#if USE_EC_BATCH #if USE_EC_BATCH
// VERSIONE CON BATCH EC POINT ADDITION // 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) { while (keep_running) {
// Step 1: Genera la prima pubkey del batch (P = privkey * G) secp256k1_pubkey pubkey0;
if (!secp256k1_ec_pubkey_create(ctx, &pubkey_batch[0], privkey)) { if (!secp256k1_ec_pubkey_create(ctx, &pubkey0, privkey)) {
increment_privkey(privkey); increment_privkey(privkey);
continue; continue;
} }
// Step 2: Check prima chiave unsigned char buf65[65];
int match_idx = check_match_fast(&pubkey_batch[0]); 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)) { if (__builtin_expect(match_idx >= 0, 0)) {
save_found_key(privkey, match_idx); save_found_key(privkey, match_idx);
} }
// Step 3: Genera le restanti (EC_BATCH_SIZE - 1) chiavi usando EC addition // Genera le restanti EC_BATCH_MULT chiavi: batch[i] = P0 + (i+1)*G, in Jacobiane
// P1 = P + G, P2 = P + 2G, P3 = P + 3G, ... int valid_count = 0;
// Questo è MOLTO più veloce di fare EC_BATCH_SIZE moltiplicazioni! bool valid[EC_BATCH_MULT];
uint8_t temp_privkey[32]; for (int i = 0; i < EC_BATCH_MULT; i++) {
memcpy(temp_privkey, privkey, 32); 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++;
}
for (int i = 1; i < EC_BATCH_SIZE && keep_running; i++) { // Batch inversion (trucco di Montgomery): una sola mpz_invert per l'intero batch
increment_privkey(temp_privkey); 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;
}
// EC point addition: pubkey_batch[i] = pubkey_batch[0] + precomputed_G[i-1] mpz_invert(inv_tmp, prefix[last], field_p); // inv_tmp = 1 / prodotto totale
// Usa EC pubkey combine (somma di due punti)
const secp256k1_pubkey* pubkeys_to_add[2] = {&pubkey_batch[0], &precomputed_G[i]};
if (secp256k1_ec_pubkey_combine(ctx, &pubkey_batch[i], pubkeys_to_add, 2)) { for (int i = last; i >= 0; i--) {
match_idx = check_match_fast(&pubkey_batch[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)) { if (__builtin_expect(match_idx >= 0, 0)) {
save_found_key(temp_privkey, match_idx); 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);
} }
} }
} }
@@ -535,10 +768,17 @@ void* worker_thread(void* arg) {
add_to_privkey(privkey, EC_BATCH_SIZE); add_to_privkey(privkey, EC_BATCH_SIZE);
// Aggiorna contatore globale periodicamente // Aggiorna contatore globale periodicamente
if ((local_attempts & (SYNC_BATCH - 1)) == 0) { // (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; 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 #else
// VERSIONE STANDARD (fallback senza batch) // VERSIONE STANDARD (fallback senza batch)
while (keep_running) { while (keep_running) {
@@ -546,7 +786,10 @@ void* worker_thread(void* arg) {
for (int batch = 0; batch < SYNC_BATCH; batch++) { for (int batch = 0; batch < SYNC_BATCH; batch++) {
if (__builtin_expect(secp256k1_ec_pubkey_create(ctx, &pubkey_obj, privkey), 1)) { if (__builtin_expect(secp256k1_ec_pubkey_create(ctx, &pubkey_obj, privkey), 1)) {
int match_idx = check_match_fast(&pubkey_obj); 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)) { if (__builtin_expect(match_idx >= 0, 0)) {
save_found_key(privkey, match_idx); save_found_key(privkey, match_idx);
} }
@@ -602,8 +845,12 @@ int main(int argc, char** argv) {
} }
} }
// Precompute EC multiples
#if USE_EC_BATCH #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(); precompute_generator_multiples();
#endif #endif
@@ -662,7 +909,7 @@ int main(int argc, char** argv) {
// Loop principale // Loop principale
while (keep_running) { while (keep_running) {
sleep(10); sleep(PROGRESS_INTERVAL_SEC);
log_progress(); log_progress();
} }