vuke 0.9.0

Research tool for studying vulnerable Bitcoin key generation practices
Documentation
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
//! GPU-accelerated SHA256 chain brute-force search.
//!
//! Uses GpuHashPipeline for SHA256 computation with batched seed processing.

use super::{GpuContext, GpuError, GpuHashPipeline, HashAlgorithm};
use crate::sha256_chain::Sha256ChainVariant;

pub struct GpuSha256ChainSearchResult {
    pub seeds_tested: u64,
    pub found_seed: Option<u32>,
    pub found_variant: Option<Sha256ChainVariant>,
    pub found_chain_index: Option<u32>,
    pub found_full_key: Option<[u8; 32]>,
}

pub struct GpuSha256ChainPipeline {
    hash_pipeline: GpuHashPipeline,
}

impl GpuSha256ChainPipeline {
    pub fn new(ctx: &GpuContext) -> Result<Self, GpuError> {
        let hash_pipeline = GpuHashPipeline::new(ctx)?;
        Ok(Self { hash_pipeline })
    }

    /// Search for a seed that produces a key matching the target.
    ///
    /// This is a hybrid CPU-GPU approach:
    /// - CPU generates seed candidates and prepares hash inputs
    /// - GPU computes SHA256 hashes in batches
    /// - CPU checks results against target
    ///
    /// For Iterated variant, chains must be computed sequentially per seed.
    /// For Indexed variants, all keys in chain can be computed in parallel.
    pub fn search_exact(
        &self,
        target: &[u8; 32],
        variants: &[Sha256ChainVariant],
        chain_depth: u32,
        batch_size: u32,
        mut callback: impl FnMut(u64, Option<(u32, Sha256ChainVariant, u32)>) -> bool,
    ) -> Result<GpuSha256ChainSearchResult, GpuError> {
        let total_seeds = u32::MAX as u64 + 1;
        let mut seeds_tested: u64 = 0;
        let mut found_seed: Option<u32> = None;
        let mut found_variant: Option<Sha256ChainVariant> = None;
        let mut found_chain_index: Option<u32> = None;
        let mut found_full_key: Option<[u8; 32]> = None;

        let mut current_seed: u64 = 0;

        while current_seed < total_seeds {
            let batch_end = std::cmp::min(current_seed + batch_size as u64, total_seeds);
            let actual_batch_size = (batch_end - current_seed) as u32;

            for variant in variants {
                if found_seed.is_some() {
                    break;
                }

                match variant {
                    Sha256ChainVariant::Iterated => {
                        if let Some((seed, idx, key)) = self.search_batch_iterated(
                            current_seed as u32,
                            actual_batch_size,
                            chain_depth,
                            target,
                        )? {
                            found_seed = Some(seed);
                            found_variant = Some(*variant);
                            found_chain_index = Some(idx);
                            found_full_key = Some(key);
                        }
                    }
                    Sha256ChainVariant::IndexedBinary { big_endian } => {
                        if let Some((seed, idx, key)) = self.search_batch_indexed_binary(
                            current_seed as u32,
                            actual_batch_size,
                            chain_depth,
                            *big_endian,
                            target,
                        )? {
                            found_seed = Some(seed);
                            found_variant = Some(*variant);
                            found_chain_index = Some(idx);
                            found_full_key = Some(key);
                        }
                    }
                    Sha256ChainVariant::IndexedString => {
                        if let Some((seed, idx, key)) = self.search_batch_indexed_string(
                            current_seed as u32,
                            actual_batch_size,
                            chain_depth,
                            target,
                        )? {
                            found_seed = Some(seed);
                            found_variant = Some(*variant);
                            found_chain_index = Some(idx);
                            found_full_key = Some(key);
                        }
                    }
                }
            }

            seeds_tested = batch_end;

            let result = found_seed.map(|s| (s, found_variant.unwrap(), found_chain_index.unwrap()));
            if !callback(seeds_tested, result) {
                break;
            }

            if found_seed.is_some() {
                break;
            }

            current_seed = batch_end;
        }

        Ok(GpuSha256ChainSearchResult {
            seeds_tested,
            found_seed,
            found_variant,
            found_chain_index,
            found_full_key,
        })
    }

    fn search_batch_iterated(
        &self,
        start_seed: u32,
        batch_size: u32,
        chain_depth: u32,
        target: &[u8; 32],
    ) -> Result<Option<(u32, u32, [u8; 32])>, GpuError> {
        // For iterated variant: key[0] = SHA256(seed), key[n] = SHA256(key[n-1])
        // Step 1: Hash all seeds to get key[0]
        let mut inputs = Vec::with_capacity(batch_size as usize * 64);
        for i in 0..batch_size {
            let seed = start_seed.wrapping_add(i);
            let seed_bytes = seed.to_be_bytes();
            let block = GpuHashPipeline::pad_input_sha256(&seed_bytes)?;
            inputs.extend_from_slice(&block);
        }

        let mut current_keys = self.hash_pipeline.compute_batch(
            HashAlgorithm::Sha256,
            &inputs,
            batch_size,
        )?;

        // Check key[0] against target
        for (i, key) in current_keys.iter().enumerate() {
            if key == target {
                let seed = start_seed.wrapping_add(i as u32);
                return Ok(Some((seed, 0, *key)));
            }
        }

        // Iterate through chain
        for chain_idx in 1..chain_depth {
            // Prepare inputs: hash each current key
            let mut next_inputs = Vec::with_capacity(batch_size as usize * 64);
            for key in &current_keys {
                let block = GpuHashPipeline::pad_input_sha256(key)?;
                next_inputs.extend_from_slice(&block);
            }

            current_keys = self.hash_pipeline.compute_batch(
                HashAlgorithm::Sha256,
                &next_inputs,
                batch_size,
            )?;

            // Check against target
            for (i, key) in current_keys.iter().enumerate() {
                if key == target {
                    let seed = start_seed.wrapping_add(i as u32);
                    return Ok(Some((seed, chain_idx, *key)));
                }
            }
        }

        Ok(None)
    }

    fn search_batch_indexed_binary(
        &self,
        start_seed: u32,
        batch_size: u32,
        chain_depth: u32,
        big_endian: bool,
        target: &[u8; 32],
    ) -> Result<Option<(u32, u32, [u8; 32])>, GpuError> {
        // For indexed binary: key[n] = SHA256(seed || n as bytes)
        // Each key in chain is independent, can compute all at once per chain index

        for chain_idx in 0..chain_depth {
            let idx_bytes = if big_endian {
                chain_idx.to_be_bytes()
            } else {
                chain_idx.to_le_bytes()
            };

            let mut inputs = Vec::with_capacity(batch_size as usize * 64);
            for i in 0..batch_size {
                let seed = start_seed.wrapping_add(i);
                let seed_bytes = seed.to_be_bytes();

                // Concatenate seed || index (8 bytes total)
                let mut data = [0u8; 8];
                data[..4].copy_from_slice(&seed_bytes);
                data[4..8].copy_from_slice(&idx_bytes);

                let block = GpuHashPipeline::pad_input_sha256(&data)?;
                inputs.extend_from_slice(&block);
            }

            let hashes = self.hash_pipeline.compute_batch(
                HashAlgorithm::Sha256,
                &inputs,
                batch_size,
            )?;

            for (i, key) in hashes.iter().enumerate() {
                if key == target {
                    let seed = start_seed.wrapping_add(i as u32);
                    return Ok(Some((seed, chain_idx, *key)));
                }
            }
        }

        Ok(None)
    }

    fn search_batch_indexed_string(
        &self,
        start_seed: u32,
        batch_size: u32,
        chain_depth: u32,
        target: &[u8; 32],
    ) -> Result<Option<(u32, u32, [u8; 32])>, GpuError> {
        // For indexed string: key[n] = SHA256(seed || "n")
        // Each key in chain is independent

        for chain_idx in 0..chain_depth {
            let idx_str = chain_idx.to_string();
            let idx_bytes = idx_str.as_bytes();

            // Skip if concatenation would be too long for single block
            if 4 + idx_bytes.len() > 55 {
                // Fall back to CPU for this index
                continue;
            }

            let mut inputs = Vec::with_capacity(batch_size as usize * 64);
            for i in 0..batch_size {
                let seed = start_seed.wrapping_add(i);
                let seed_bytes = seed.to_be_bytes();

                // Concatenate seed || index_string
                let mut data = Vec::with_capacity(4 + idx_bytes.len());
                data.extend_from_slice(&seed_bytes);
                data.extend_from_slice(idx_bytes);

                let block = GpuHashPipeline::pad_input_sha256(&data)?;
                inputs.extend_from_slice(&block);
            }

            let hashes = self.hash_pipeline.compute_batch(
                HashAlgorithm::Sha256,
                &inputs,
                batch_size,
            )?;

            for (i, key) in hashes.iter().enumerate() {
                if key == target {
                    let seed = start_seed.wrapping_add(i as u32);
                    return Ok(Some((seed, chain_idx, *key)));
                }
            }
        }

        Ok(None)
    }

    /// Search for a seed that produces keys matching cascade targets.
    pub fn search_cascade(
        &self,
        targets: &[(u8, u64)],
        variants: &[Sha256ChainVariant],
        batch_size: u32,
        mut callback: impl FnMut(u64, Option<(u32, Sha256ChainVariant)>) -> bool,
    ) -> Result<GpuSha256ChainSearchResult, GpuError> {
        // For cascade, we need sequential keys from the same seed
        // This is harder to parallelize efficiently on GPU
        // Use hybrid approach: GPU for hash, CPU for cascade logic

        let total_seeds = u32::MAX as u64 + 1;
        let mut seeds_tested: u64 = 0;
        let mut found_seed: Option<u32> = None;
        let mut found_variant: Option<Sha256ChainVariant> = None;

        let mut current_seed: u64 = 0;

        while current_seed < total_seeds {
            let batch_end = std::cmp::min(current_seed + batch_size as u64, total_seeds);
            let actual_batch_size = (batch_end - current_seed) as u32;

            for variant in variants {
                if found_seed.is_some() {
                    break;
                }

                // Generate first key for all seeds in batch
                if let Some(seed) = self.search_cascade_for_variant(
                    current_seed as u32,
                    actual_batch_size,
                    targets,
                    *variant,
                )? {
                    found_seed = Some(seed);
                    found_variant = Some(*variant);
                }
            }

            seeds_tested = batch_end;

            let result = found_seed.map(|s| (s, found_variant.unwrap()));
            if !callback(seeds_tested, result) {
                break;
            }

            if found_seed.is_some() {
                break;
            }

            current_seed = batch_end;
        }

        Ok(GpuSha256ChainSearchResult {
            seeds_tested,
            found_seed,
            found_variant,
            found_chain_index: None,
            found_full_key: None,
        })
    }

    fn search_cascade_for_variant(
        &self,
        start_seed: u32,
        batch_size: u32,
        targets: &[(u8, u64)],
        variant: Sha256ChainVariant,
    ) -> Result<Option<u32>, GpuError> {
        if targets.is_empty() {
            return Ok(None);
        }

        let _chain_depth = targets.len() as u32;

        // For iterated variant, compute full chains and check cascade
        match variant {
            Sha256ChainVariant::Iterated => {
                self.check_cascade_iterated(start_seed, batch_size, targets)
            }
            Sha256ChainVariant::IndexedBinary { big_endian } => {
                self.check_cascade_indexed_binary(start_seed, batch_size, targets, big_endian)
            }
            Sha256ChainVariant::IndexedString => {
                self.check_cascade_indexed_string(start_seed, batch_size, targets)
            }
        }
    }

    fn check_cascade_iterated(
        &self,
        start_seed: u32,
        batch_size: u32,
        targets: &[(u8, u64)],
    ) -> Result<Option<u32>, GpuError> {
        // Compute key[0] for all seeds
        let mut inputs = Vec::with_capacity(batch_size as usize * 64);
        for i in 0..batch_size {
            let seed = start_seed.wrapping_add(i);
            let seed_bytes = seed.to_be_bytes();
            let block = GpuHashPipeline::pad_input_sha256(&seed_bytes)?;
            inputs.extend_from_slice(&block);
        }

        let mut current_keys = self.hash_pipeline.compute_batch(
            HashAlgorithm::Sha256,
            &inputs,
            batch_size,
        )?;

        // Track which seeds still match cascade
        let mut candidates: Vec<u32> = (0..batch_size).map(|i| start_seed.wrapping_add(i)).collect();

        for (chain_idx, (bits, target)) in targets.iter().enumerate() {
            // Filter candidates by current target
            let mut still_valid = Vec::new();
            let mut still_valid_keys = Vec::new();

            for (i, seed) in candidates.iter().enumerate() {
                let key = &current_keys[i];
                if check_mask(key, *bits, *target) {
                    still_valid.push(*seed);
                    still_valid_keys.push(*key);
                }
            }

            if still_valid.is_empty() {
                return Ok(None);
            }

            // If this is the last target and we have matches, return first
            if chain_idx == targets.len() - 1 {
                return Ok(Some(still_valid[0]));
            }

            // Compute next key for remaining candidates
            candidates = still_valid;
            let mut next_inputs = Vec::with_capacity(candidates.len() * 64);
            for key in &still_valid_keys {
                let block = GpuHashPipeline::pad_input_sha256(key)?;
                next_inputs.extend_from_slice(&block);
            }

            current_keys = self.hash_pipeline.compute_batch(
                HashAlgorithm::Sha256,
                &next_inputs,
                candidates.len() as u32,
            )?;
        }

        Ok(None)
    }

    fn check_cascade_indexed_binary(
        &self,
        start_seed: u32,
        batch_size: u32,
        targets: &[(u8, u64)],
        big_endian: bool,
    ) -> Result<Option<u32>, GpuError> {
        let mut candidates: Vec<u32> = (0..batch_size).map(|i| start_seed.wrapping_add(i)).collect();

        for (chain_idx, (bits, target)) in targets.iter().enumerate() {
            let idx_bytes = if big_endian {
                (chain_idx as u32).to_be_bytes()
            } else {
                (chain_idx as u32).to_le_bytes()
            };

            let mut inputs = Vec::with_capacity(candidates.len() * 64);
            for seed in &candidates {
                let seed_bytes = seed.to_be_bytes();
                let mut data = [0u8; 8];
                data[..4].copy_from_slice(&seed_bytes);
                data[4..8].copy_from_slice(&idx_bytes);
                let block = GpuHashPipeline::pad_input_sha256(&data)?;
                inputs.extend_from_slice(&block);
            }

            let hashes = self.hash_pipeline.compute_batch(
                HashAlgorithm::Sha256,
                &inputs,
                candidates.len() as u32,
            )?;

            let mut still_valid = Vec::new();
            for (i, seed) in candidates.iter().enumerate() {
                if check_mask(&hashes[i], *bits, *target) {
                    still_valid.push(*seed);
                }
            }

            if still_valid.is_empty() {
                return Ok(None);
            }

            if chain_idx == targets.len() - 1 {
                return Ok(Some(still_valid[0]));
            }

            candidates = still_valid;
        }

        Ok(None)
    }

    fn check_cascade_indexed_string(
        &self,
        start_seed: u32,
        batch_size: u32,
        targets: &[(u8, u64)],
    ) -> Result<Option<u32>, GpuError> {
        let mut candidates: Vec<u32> = (0..batch_size).map(|i| start_seed.wrapping_add(i)).collect();

        for (chain_idx, (bits, target)) in targets.iter().enumerate() {
            let idx_str = chain_idx.to_string();
            let idx_bytes = idx_str.as_bytes();

            if 4 + idx_bytes.len() > 55 {
                // Too long for GPU, skip
                return Ok(None);
            }

            let mut inputs = Vec::with_capacity(candidates.len() * 64);
            for seed in &candidates {
                let seed_bytes = seed.to_be_bytes();
                let mut data = Vec::with_capacity(4 + idx_bytes.len());
                data.extend_from_slice(&seed_bytes);
                data.extend_from_slice(idx_bytes);
                let block = GpuHashPipeline::pad_input_sha256(&data)?;
                inputs.extend_from_slice(&block);
            }

            let hashes = self.hash_pipeline.compute_batch(
                HashAlgorithm::Sha256,
                &inputs,
                candidates.len() as u32,
            )?;

            let mut still_valid = Vec::new();
            for (i, seed) in candidates.iter().enumerate() {
                if check_mask(&hashes[i], *bits, *target) {
                    still_valid.push(*seed);
                }
            }

            if still_valid.is_empty() {
                return Ok(None);
            }

            if chain_idx == targets.len() - 1 {
                return Ok(Some(still_valid[0]));
            }

            candidates = still_valid;
        }

        Ok(None)
    }
}

fn check_mask(key: &[u8; 32], bits: u8, target: u64) -> bool {
    if bits == 0 {
        return false;
    }
    let key_u64 = u64::from_be_bytes(key[24..32].try_into().unwrap());
    let mask: u64 = if bits >= 64 {
        u64::MAX
    } else {
        (1u64 << bits) - 1
    };
    let high_bit: u64 = if bits >= 64 {
        1u64 << 63
    } else {
        1u64 << (bits - 1)
    };
    let masked = (key_u64 & mask) | high_bit;
    masked == target
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sha256_chain::generate_chain;

    fn apply_mask(key: &[u8; 32], bits: u8) -> u64 {
        let key_u64 = u64::from_be_bytes(key[24..32].try_into().unwrap());
        let mask: u64 = if bits >= 64 {
            u64::MAX
        } else {
            (1u64 << bits) - 1
        };
        let high_bit: u64 = 1u64 << (bits - 1);
        (key_u64 & mask) | high_bit
    }

    fn generate_test_targets(
        seed: u32,
        variant: Sha256ChainVariant,
        bit_widths: &[u8],
    ) -> Vec<(u8, u64)> {
        let chain = generate_chain(&seed.to_be_bytes(), variant, bit_widths.len() as u32);
        bit_widths
            .iter()
            .zip(chain.iter())
            .map(|(&bits, key)| (bits, apply_mask(key, bits)))
            .collect()
    }

    #[test]
    fn test_check_mask() {
        let mut key = [0u8; 32];
        key[31] = 0x15;

        assert!(check_mask(&key, 5, 0x15));
        assert!(!check_mask(&key, 5, 0x16));
    }

    #[test]
    #[ignore] // Requires GPU
    fn test_gpu_search_exact_iterated() {
        let ctx = match pollster::block_on(GpuContext::new()) {
            Ok(ctx) => ctx,
            Err(_) => return,
        };

        let pipeline = GpuSha256ChainPipeline::new(&ctx).expect("Failed to create pipeline");

        let test_seed = 42u32;
        let variant = Sha256ChainVariant::Iterated;
        let chain = generate_chain(&test_seed.to_be_bytes(), variant, 3);
        let target = chain[1];

        let result = pipeline
            .search_exact(
                &target,
                &[variant],
                3,
                1000,
                |_, _| true,
            )
            .expect("Search failed");

        assert!(result.found_seed.is_some());
        assert_eq!(result.found_seed.unwrap(), test_seed);
        assert_eq!(result.found_chain_index.unwrap(), 1);
    }

    #[test]
    #[ignore] // Requires GPU
    fn test_gpu_cascade_iterated() {
        let ctx = match pollster::block_on(GpuContext::new()) {
            Ok(ctx) => ctx,
            Err(_) => return,
        };

        let pipeline = GpuSha256ChainPipeline::new(&ctx).expect("Failed to create pipeline");

        let test_seed = 100u32;
        let variant = Sha256ChainVariant::Iterated;
        let targets = generate_test_targets(test_seed, variant, &[5, 10, 15]);

        let result = pipeline
            .search_cascade(
                &targets,
                &[variant],
                10000,
                |_, _| true,
            )
            .expect("Search failed");

        assert!(result.found_seed.is_some());
        assert_eq!(result.found_seed.unwrap(), test_seed);
    }
}