harmoniis-wallet 0.1.85

Smart-contract wallet for the Harmoniis marketplace for agents and robots (RGB contracts, Witness-backed bearer state, Webcash fees)
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
//! GPU mining backend using wgpu compute shaders.
//!
//! Supports range-based mining over the fixed 1M nonce space using dynamic
//! dispatch sizing and adapter capability limits.
//!
//! The shader outputs only (best_difficulty, nonce_id).  The host re-computes
//! the full hash from the winning nonce to guarantee correctness — the same
//! approach used by the CUDA backend.

use async_trait::async_trait;
use wgpu::util::DeviceExt;

use super::sha256::{leading_zero_bits_words, state_words_to_bytes, Sha256Midstate};
use super::nonce_table::NonceTable;
use super::{CancelFlag, MinerBackend, MiningChunkResult, MiningResult, NONCE_SPACE_SIZE};

/// Default workgroup size (must match `@workgroup_size` in shader).
const WORKGROUP_SIZE: u32 = 256;

/// Input buffer words:
/// [0..8] = midstate words
/// [8] = difficulty
/// [9] = prefix_len
/// [10] = nonce_offset
/// [11] = nonce_count
const INPUT_WORDS: usize = 12;

/// Result buffer words:
/// [0] = best difficulty found (0 = no valid solution)
/// [1] = flat nonce id of the winner
/// [2] = reserved
const RESULT_WORDS: usize = 3;
const RESULT_BUFFER_SIZE: u64 = (RESULT_WORDS * 4) as u64;

/// Platform-native compute backend. One backend per platform, no mixing.
/// Linux = Vulkan, Windows = DX12, macOS = Metal.
pub fn platform_backend() -> wgpu::Backends {
    #[cfg(target_arch = "wasm32")]
    { wgpu::Backends::BROWSER_WEBGPU }
    #[cfg(not(target_arch = "wasm32"))]
    {
        if cfg!(target_os = "windows") {
            wgpu::Backends::DX12
        } else if cfg!(target_os = "macos") {
            wgpu::Backends::METAL
        } else {
            wgpu::Backends::VULKAN
        }
    }
}

/// Enumerate Vulkan adapters on Windows to detect the true physical GPU
/// topology.  DX12/DXGI has two known bugs with identical GPUs:
///
///   1. `get_adapter_pci_info()` in wgpu-hal matches SetupDi by vendor+device
///      and returns the FIRST hit — so all identical cards share one PCI bus ID.
///   2. `EnumAdapters1` can return the same adapter multiple times or collapse
///      identical headless cards into one "linked adapter".
///
/// Vulkan's `VK_EXT_pci_bus_info` provides a unique PCI bus address per PCIe
/// slot and `vkEnumeratePhysicalDevices` sees all GPUs regardless of monitors.
///
/// Returns `None` if Vulkan is unavailable (no driver) — caller falls back to
/// DX12 as-is, no regression.
#[cfg(all(target_os = "windows", not(target_arch = "wasm32")))]
pub async fn enumerate_vulkan_gpus() -> Option<Vec<wgpu::Adapter>> {
    let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
        backends: wgpu::Backends::VULKAN,
        ..Default::default()
    });
    let adapters: Vec<wgpu::Adapter> = instance
        .enumerate_adapters(wgpu::Backends::VULKAN)
        .await
        .into_iter()
        .filter(|a| a.get_info().device_type != wgpu::DeviceType::Cpu)
        .collect();
    if adapters.is_empty() {
        None
    } else {
        Some(adapters)
    }
}

/// Identity of a physical GPU adapter.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct AdapterIdentity {
    pub name: String,
    pub vendor: u32,
    pub device: u32,
    pub backend: String,
    /// PCI bus address (e.g. "0000:01:00.0"). Empty on Metal/non-PCI.
    pub pci_bus: String,
}

impl AdapterIdentity {
    /// Extract identity from a wgpu AdapterInfo.
    pub fn from_info(info: &wgpu::AdapterInfo) -> Self {
        Self {
            name: info.name.clone(),
            vendor: info.vendor,
            device: info.device,
            backend: format!("{:?}", info.backend).to_lowercase(),
            pci_bus: info.device_pci_bus_id.trim().to_string(),
        }
    }

    /// Check if this identity matches a wgpu AdapterInfo.
    /// Uses PCI bus ID on Vulkan (unique per PCIe slot).
    /// Falls back to vendor+device+name on Metal/DX12.
    pub fn matches(&self, info: &wgpu::AdapterInfo) -> bool {
        let backend_ok = format!("{:?}", info.backend).to_lowercase() == self.backend;
        if !self.pci_bus.is_empty() {
            info.device_pci_bus_id.trim() == self.pci_bus && backend_ok
        } else {
            info.vendor == self.vendor
                && info.device == self.device
                && info.name == self.name
                && backend_ok
        }
    }
}

/// Run a GPU pipeline probe for an adapter identified by vendor+device+backend.
/// Native-only: spawns subprocess to test GPU driver stability.
#[cfg(not(target_arch = "wasm32"))]
pub async fn probe_adapter(identity: &AdapterIdentity) -> anyhow::Result<()> {
    let backend = platform_backend();
    let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
        backends: backend,
        ..Default::default()
    });
    let adapters = instance.enumerate_adapters(backend).await;
    let adapter = adapters
        .into_iter()
        .find(|a| identity.matches(&a.get_info()))
        .ok_or_else(|| {
            anyhow::anyhow!(
                "no adapter matches {} ({})",
                identity.name,
                identity.backend,
            )
        })?;
    let probe_info = adapter.get_info();
    // Probe runs in a subprocess — keep quiet.
    let (device, _queue) = adapter
        .request_device(&wgpu::DeviceDescriptor {
            label: Some("probe"),
            required_features: wgpu::Features::empty(),
            required_limits: wgpu::Limits::downlevel_defaults(),
            ..Default::default()
        })
        .await
        .map_err(|e| anyhow::anyhow!("device request failed: {e}"))?;

    let shader = if probe_info.backend == wgpu::Backend::Vulkan {
        let spirv_bytes: &[u8] = include_bytes!("shader/sha256_mine_opt.spv");
        let spirv_words: Vec<u32> = spirv_bytes
            .chunks_exact(4)
            .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
            .collect();
        unsafe {
            device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough {
                label: Some("probe_shader_spirv"),
                spirv: Some(std::borrow::Cow::Owned(spirv_words)),
                ..Default::default()
            })
        }
    } else {
        device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("probe_shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shader/sha256_mine.wgsl").into()),
        })
    };

    let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
        label: None,
        entries: &[
            wgpu::BindGroupLayoutEntry {
                binding: 0,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: true },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 1,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: true },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
            wgpu::BindGroupLayoutEntry {
                binding: 2,
                visibility: wgpu::ShaderStages::COMPUTE,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Storage { read_only: false },
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            },
        ],
    });
    let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
        label: None,
        bind_group_layouts: &[&bgl],
        immediate_size: 0,
    });
    // This is the call that can segfault on buggy AMD Vulkan drivers.
    let _pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
        label: Some("probe_pipeline"),
        layout: Some(&pl),
        module: &shader,
        entry_point: Some("main"),
        compilation_options: Default::default(),
        cache: None,
    });
    // Success — parent process will use this adapter.
    Ok(())
}

/// Probe an adapter by spawning the current binary with `gpu-probe`.
/// Native-only: uses std::process::Command.
#[cfg(not(target_arch = "wasm32"))]
#[allow(dead_code)]
pub(crate) fn subprocess_probe(identity: &AdapterIdentity) -> bool {
    let exe = match std::env::current_exe() {
        Ok(p) => p,
        Err(e) => {
            eprintln!(
                "GPU probe: cannot find exe for {} ({}) — {e}",
                identity.backend, identity.vendor,
            );
            return false;
        }
    };
    let mut cmd = std::process::Command::new(exe);
    cmd.arg("gpu-probe")
        .arg("--vendor")
        .arg(identity.vendor.to_string())
        .arg("--device")
        .arg(identity.device.to_string())
        .arg("--backend")
        .arg(&identity.backend);
    if !identity.pci_bus.is_empty() {
        cmd.arg("--pci-bus").arg(&identity.pci_bus);
    }
    let status = cmd
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();
    let ok = match status {
        Ok(s) => s.success(),
        Err(e) => {
            eprintln!(
                "GPU probe: failed to spawn for {} ({}) — {e}",
                identity.backend, identity.vendor,
            );
            false
        }
    };
    if !ok {
        eprintln!(
            "GPU probe: adapter {} (vendor={:#x}, device={:#x}) failed — skipping",
            identity.backend, identity.vendor, identity.device,
        );
    }
    ok
}

/// Maximum work units batched per GPU in a single submit (matches CUDA).
const MAX_BATCH: usize = 64;

/// One slot = one concurrent dispatch with its own input/result/staging/bind_group.
struct BatchSlot {
    input_buffer: wgpu::Buffer,
    result_buffer: wgpu::Buffer,
    staging_buffer: wgpu::Buffer,
    bind_group: wgpu::BindGroup,
}

pub struct GpuMiner {
    device: wgpu::Device,
    queue: wgpu::Queue,
    pipeline: wgpu::ComputePipeline,
    slots: Vec<BatchSlot>,
    nonce_words: Vec<u32>,
    adapter_name: String,
    adapter_backend: wgpu::Backend,
    max_dispatch_nonces: u32,
}

impl GpuMiner {
    /// Try to initialize the default high-performance adapter.
    pub async fn try_new() -> Option<Self> {
        let compute_backends = platform_backend();
        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
            backends: compute_backends,
            ..Default::default()
        });

        // Fast path: ask wgpu for a high-performance adapter.
        let preferred = instance
            .request_adapter(&wgpu::RequestAdapterOptions {
                power_preference: wgpu::PowerPreference::HighPerformance,
                compatible_surface: None,
                force_fallback_adapter: false,
            })
            .await;
        if let Ok(adapter) = preferred {
            let info = adapter.get_info();
            eprintln!(
                "GPU: preferred adapter: {} ({:?}, {:?})",
                info.name, info.backend, info.device_type
            );
            if let Some(miner) = Self::try_from_adapter(adapter).await {
                return Some(miner);
            }
        }

        // Fallback: scan all adapters and pick the first one we can open.
        let adapters = instance.enumerate_adapters(wgpu::Backends::all()).await;
        if adapters.is_empty() {
            eprintln!("GPU: no adapters visible to wgpu (enumerate_adapters returned 0)");
            return None;
        }
        eprintln!("GPU: scanning {} adapters for fallback...", adapters.len());
        for adapter in adapters {
            let info = adapter.get_info();
            eprintln!("GPU: trying {} ({:?})", info.name, info.backend);
            if let Some(miner) = Self::try_from_adapter(adapter).await {
                return Some(miner);
            }
        }

        eprintln!("GPU: no compatible adapter could be initialized");
        None
    }

    /// Try to initialize from a specific adapter.
    pub async fn try_from_adapter(adapter: wgpu::Adapter) -> Option<Self> {
        let info = adapter.get_info();
        if info.device_type == wgpu::DeviceType::Cpu {
            eprintln!("GPU: skipping CPU adapter: {}", info.name);
            return None;
        }

        let adapter_name = info.name.clone();
        eprintln!(
            "GPU: initializing {} ({:?}, vendor={:#x}, device={:#x})",
            adapter_name, info.backend, info.vendor, info.device,
        );

        let req_default = adapter
            .request_device(&wgpu::DeviceDescriptor {
                label: Some("webminer"),
                required_features: wgpu::Features::empty(),
                required_limits: wgpu::Limits::default(),
                ..Default::default()
            })
            .await;
        let (device, queue) = match req_default {
            Ok(ok) => ok,
            Err(err_default) => {
                eprintln!(
                    "GPU adapter '{}' failed default limits ({}), retrying with downlevel limits",
                    adapter_name, err_default
                );
                match adapter
                    .request_device(&wgpu::DeviceDescriptor {
                        label: Some("webminer-downlevel"),
                        required_features: wgpu::Features::empty(),
                        required_limits: wgpu::Limits::downlevel_defaults(),
                        ..Default::default()
                    })
                    .await
                {
                    Ok(ok) => ok,
                    Err(e) => {
                        eprintln!(
                            "GPU adapter '{}' failed downlevel limits too: {}",
                            adapter_name, e
                        );
                        return None;
                    }
                }
            }
        };

        // Native Vulkan: load pre-compiled SPIR-V (bypasses naga).
        // All other backends (Metal, DX12, WebGPU): use WGSL.
        #[cfg(all(not(target_arch = "wasm32"), feature = "gpu"))]
        let shader_module = if info.backend == wgpu::Backend::Vulkan {
            let spirv_bytes: &[u8] = include_bytes!("shader/sha256_mine_opt.spv");
            let spirv_words: Vec<u32> = spirv_bytes
                .chunks_exact(4)
                .map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]]))
                .collect();
            eprintln!(
                "GPU: using optimized SPIR-V shader (unrolled, {} words)",
                spirv_words.len()
            );
            unsafe {
                device.create_shader_module_passthrough(wgpu::ShaderModuleDescriptorPassthrough {
                    label: Some("sha256_mine_spirv"),
                    spirv: Some(std::borrow::Cow::Owned(spirv_words)),
                    ..Default::default()
                })
            }
        } else {
            device.create_shader_module(wgpu::ShaderModuleDescriptor {
                label: Some("sha256_mine"),
                source: wgpu::ShaderSource::Wgsl(include_str!("shader/sha256_mine.wgsl").into()),
            })
        };
        #[cfg(any(target_arch = "wasm32", not(feature = "gpu")))]
        let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("sha256_mine"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shader/sha256_mine.wgsl").into()),
        });

        let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("miner_bind_group_layout"),
            entries: &[
                // binding 0: nonce_table (read-only storage)
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                // binding 1: input (midstate + run params, read-only storage)
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: true },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                // binding 2: output (result buffer, read-write storage)
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::COMPUTE,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Storage { read_only: false },
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
            ],
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("miner_pipeline_layout"),
            bind_group_layouts: &[&bind_group_layout],
            immediate_size: 0,
        });

        let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
            label: Some("sha256_mine_pipeline"),
            layout: Some(&pipeline_layout),
            module: &shader_module,
            entry_point: Some("main"),
            compilation_options: Default::default(),
            cache: None,
        });

        let nonce_table = NonceTable::new();
        let nonce_words = nonce_table.as_u32_slice();
        let nonce_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("nonce_table"),
            contents: bytemuck::cast_slice(&nonce_words),
            usage: wgpu::BufferUsages::STORAGE,
        });

        // Pre-allocate MAX_BATCH slots (input + result + staging + bind_group).
        // This enables mine_batch: encode N dispatches in one command buffer,
        // submit once, sync once — matching CUDA's batched sync-once pattern.
        let mut slots = Vec::with_capacity(MAX_BATCH);
        for i in 0..MAX_BATCH {
            let input_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some(&format!("input_{i}")),
                size: (INPUT_WORDS * 4) as u64,
                usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let result_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some(&format!("result_{i}")),
                size: RESULT_BUFFER_SIZE,
                usage: wgpu::BufferUsages::STORAGE
                    | wgpu::BufferUsages::COPY_SRC
                    | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let staging_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some(&format!("staging_{i}")),
                size: RESULT_BUFFER_SIZE,
                usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
                label: Some(&format!("bind_{i}")),
                layout: &bind_group_layout,
                entries: &[
                    wgpu::BindGroupEntry {
                        binding: 0,
                        resource: nonce_buffer.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 1,
                        resource: input_buffer.as_entire_binding(),
                    },
                    wgpu::BindGroupEntry {
                        binding: 2,
                        resource: result_buffer.as_entire_binding(),
                    },
                ],
            });
            slots.push(BatchSlot {
                input_buffer,
                result_buffer,
                staging_buffer,
                bind_group,
            });
        }

        let limits = device.limits();
        let max_dispatch_nonces = limits
            .max_compute_workgroups_per_dimension
            .max(1)
            .saturating_mul(WORKGROUP_SIZE)
            .max(WORKGROUP_SIZE);

        Some(GpuMiner {
            device,
            queue,
            pipeline,
            slots,
            nonce_words,
            adapter_name,
            adapter_backend: info.backend,
            max_dispatch_nonces,
        })
    }

    pub fn adapter_name(&self) -> &str {
        &self.adapter_name
    }

    pub fn max_dispatch_nonces(&self) -> u32 {
        self.max_dispatch_nonces
    }

    /// Mine a batch of midstates with ONE submit + ONE sync (matches CUDA
    /// mine_batch). All dispatches are encoded into a single command buffer.
    pub async fn mine_batch(
        &self,
        midstates: &[Sha256Midstate],
        difficulty: u32,
    ) -> anyhow::Result<Vec<MiningChunkResult>> {
        let batch_size = midstates.len().min(self.slots.len());
        if batch_size == 0 {
            return Ok(Vec::new());
        }

        // Phase 1: write inputs + clear results for all slots.
        for (i, midstate) in midstates[..batch_size].iter().enumerate() {
            let slot = &self.slots[i];
            let mut input_data = [0u32; INPUT_WORDS];
            input_data[..8].copy_from_slice(midstate.state_words());
            input_data[8] = difficulty;
            input_data[9] = midstate.prefix_len as u32;
            input_data[10] = 0; // nonce_offset
            input_data[11] = NONCE_SPACE_SIZE; // nonce_count
            self.queue
                .write_buffer(&slot.input_buffer, 0, bytemuck::cast_slice(&input_data));
            self.queue
                .write_buffer(&slot.result_buffer, 0, &[0u8; RESULT_WORDS * 4]);
        }

        // Phase 2: encode ALL dispatches + copies in ONE command buffer.
        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("batch_encoder"),
            });

        let num_workgroups = NONCE_SPACE_SIZE.div_ceil(WORKGROUP_SIZE);
        for i in 0..batch_size {
            let slot = &self.slots[i];
            {
                let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                    label: None,
                    timestamp_writes: None,
                });
                pass.set_pipeline(&self.pipeline);
                pass.set_bind_group(0, &slot.bind_group, &[]);
                pass.dispatch_workgroups(num_workgroups, 1, 1);
            }
            encoder.copy_buffer_to_buffer(
                &slot.result_buffer,
                0,
                &slot.staging_buffer,
                0,
                RESULT_BUFFER_SIZE,
            );
        }

        // Phase 3: ONE submit, ONE sync.
        #[cfg(not(target_arch = "wasm32"))]
        let submission = self.queue.submit(std::iter::once(encoder.finish()));
        #[cfg(target_arch = "wasm32")]
        self.queue.submit(std::iter::once(encoder.finish()));

        // Map all staging buffers for reading.
        #[cfg(not(target_arch = "wasm32"))]
        {
            let mut receivers = Vec::with_capacity(batch_size);
            for i in 0..batch_size {
                let (tx, rx) = tokio::sync::oneshot::channel();
                self.slots[i]
                    .staging_buffer
                    .slice(..)
                    .map_async(wgpu::MapMode::Read, move |result| {
                        let _ = tx.send(result);
                    });
                receivers.push(rx);
            }
            let _ = self.device.poll(wgpu::PollType::Wait {
                submission_index: Some(submission),
                timeout: None,
            });
            for rx in receivers {
                rx.await??;
            }
        }
        #[cfg(target_arch = "wasm32")]
        {
            for i in 0..batch_size {
                let (sender, receiver) = futures_channel::oneshot::channel::<()>();
                self.slots[i]
                    .staging_buffer
                    .slice(..)
                    .map_async(wgpu::MapMode::Read, move |_| {
                        let _ = sender.send(());
                    });
                let _ = self.device.poll(wgpu::PollType::Poll);
                let _ = receiver.await;
            }
        }

        // Phase 4: read all results.
        #[cfg(not(target_arch = "wasm32"))]
        let started = std::time::Instant::now();
        let mut results = Vec::with_capacity(batch_size);
        for i in 0..batch_size {
            let data = self.slots[i].staging_buffer.slice(..).get_mapped_range();
            let words: &[u32] = bytemuck::cast_slice(&data[..RESULT_BUFFER_SIZE as usize]);
            let best_zeros = words[0];
            let nonce_id = words[1];
            drop(data);
            self.slots[i].staging_buffer.unmap();

            let result = self.verify_result(&midstates[i], difficulty, best_zeros, nonce_id);
            results.push(MiningChunkResult {
                result,
                attempted: NONCE_SPACE_SIZE as u64,
                #[cfg(not(target_arch = "wasm32"))]
                elapsed: started.elapsed(),
                #[cfg(target_arch = "wasm32")]
                elapsed: std::time::Duration::ZERO,
            });
        }
        Ok(results)
    }

    fn verify_result(
        &self,
        midstate: &Sha256Midstate,
        difficulty: u32,
        best_zeros: u32,
        nonce_id: u32,
    ) -> Option<MiningResult> {
        if best_zeros < difficulty || nonce_id >= NONCE_SPACE_SIZE {
            return None;
        }
        let n1 = (nonce_id / 1000) as usize;
        let n2 = (nonce_id % 1000) as usize;
        let state_words =
            midstate.finalize_words_from_nonce_u32(self.nonce_words[n1], self.nonce_words[n2]);
        let achieved = leading_zero_bits_words(&state_words);
        if achieved < difficulty {
            return None;
        }
        Some(MiningResult {
            nonce1_idx: n1 as u16,
            nonce2_idx: n2 as u16,
            hash: state_words_to_bytes(&state_words),
            difficulty_achieved: achieved,
        })
    }

    async fn dispatch_range(
        &self,
        midstate: &Sha256Midstate,
        difficulty: u32,
        nonce_offset: u32,
        nonce_count: u32,
    ) -> anyhow::Result<Option<MiningResult>> {
        let slot = &self.slots[0];
        let mut input_data = [0u32; INPUT_WORDS];
        input_data[..8].copy_from_slice(midstate.state_words());
        input_data[8] = difficulty;
        input_data[9] = midstate.prefix_len as u32;
        input_data[10] = nonce_offset;
        input_data[11] = nonce_count;
        self.queue
            .write_buffer(&slot.input_buffer, 0, bytemuck::cast_slice(&input_data));
        self.queue
            .write_buffer(&slot.result_buffer, 0, &[0u8; RESULT_WORDS * 4]);

        let mut encoder = self
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("miner_encoder"),
            });
        {
            let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
                label: Some("sha256_mine"),
                timestamp_writes: None,
            });
            pass.set_pipeline(&self.pipeline);
            pass.set_bind_group(0, &slot.bind_group, &[]);
            pass.dispatch_workgroups(nonce_count.div_ceil(WORKGROUP_SIZE), 1, 1);
        }
        encoder.copy_buffer_to_buffer(
            &slot.result_buffer,
            0,
            &slot.staging_buffer,
            0,
            RESULT_BUFFER_SIZE,
        );
        #[cfg(not(target_arch = "wasm32"))]
        let submission = self.queue.submit(std::iter::once(encoder.finish()));
        #[cfg(target_arch = "wasm32")]
        self.queue.submit(std::iter::once(encoder.finish()));

        let buffer_slice = slot.staging_buffer.slice(..);
        #[cfg(not(target_arch = "wasm32"))]
        {
            let (tx, rx) = tokio::sync::oneshot::channel();
            buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
                let _ = tx.send(result);
            });
            let _ = self.device.poll(wgpu::PollType::Wait {
                submission_index: Some(submission),
                timeout: None,
            });
            rx.await??;
        }
        #[cfg(target_arch = "wasm32")]
        {
            let (sender, receiver) = futures_channel::oneshot::channel::<()>();
            buffer_slice.map_async(wgpu::MapMode::Read, move |_| {
                let _ = sender.send(());
            });
            let _ = self.device.poll(wgpu::PollType::Poll);
            let _ = receiver.await;
        }

        let data = buffer_slice.get_mapped_range();
        let words: &[u32] = bytemuck::cast_slice(&data[..RESULT_BUFFER_SIZE as usize]);
        let best_zeros = words[0];
        let nonce_id = words[1];
        drop(data);
        slot.staging_buffer.unmap();

        Ok(self.verify_result(midstate, difficulty, best_zeros, nonce_id))
    }
}

#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl MinerBackend for GpuMiner {
    fn name(&self) -> &str {
        &self.adapter_name
    }

    fn startup_summary(&self) -> Vec<String> {
        vec![
            format!("gpu_name={}", self.adapter_name),
            format!("gpu_backend={:?}", self.adapter_backend),
            format!("workgroup_size={}", WORKGROUP_SIZE),
            format!("max_dispatch_nonces={}", self.max_dispatch_nonces),
        ]
    }

    async fn benchmark(&self) -> anyhow::Result<f64> {
        let nonce_table = NonceTable::new();
        let midstate = Sha256Midstate::from_prefix(&[0u8; 64]);

        // Warm up GPU pipeline/driver state.
        let _ = self
            .mine_range(&midstate, &nonce_table, 256, 0, NONCE_SPACE_SIZE, None)
            .await?;

        let mut samples = Vec::with_capacity(8);
        for _ in 0..8 {
            let chunk = self
                .mine_range(&midstate, &nonce_table, 256, 0, NONCE_SPACE_SIZE, None)
                .await?;
            let secs = chunk.elapsed.as_secs_f64();
            if secs > 0.0 {
                samples.push(chunk.attempted as f64 / secs);
            }
        }

        if samples.is_empty() {
            return Ok(0.0);
        }
        samples.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        Ok(samples[samples.len() / 2])
    }

    fn max_batch_hint(&self) -> u32 {
        NONCE_SPACE_SIZE
    }

    async fn mine_range(
        &self,
        midstate: &Sha256Midstate,
        _nonce_table: &NonceTable,
        difficulty: u32,
        start_nonce: u32,
        nonce_count: u32,
        _cancel: Option<CancelFlag>,
    ) -> anyhow::Result<MiningChunkResult> {
        let range_start = start_nonce.min(NONCE_SPACE_SIZE);
        let range_end = range_start
            .saturating_add(nonce_count)
            .min(NONCE_SPACE_SIZE);
        if range_start >= range_end {
            return Ok(MiningChunkResult::empty());
        }

        #[cfg(not(target_arch = "wasm32"))]
        let started = std::time::Instant::now();
        // Single large dispatch for GPU stability (especially AMD consumer GPUs).
        let result = self
            .dispatch_range(midstate, difficulty, range_start, range_end - range_start)
            .await?;

        Ok(MiningChunkResult {
            result,
            attempted: (range_end - range_start) as u64,
            #[cfg(not(target_arch = "wasm32"))]
            elapsed: started.elapsed(),
            #[cfg(target_arch = "wasm32")]
            elapsed: std::time::Duration::ZERO,
        })
    }
}

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

    #[test]
    fn platform_backend_returns_one() {
        let b = platform_backend();
        // Should be exactly one backend flag.
        assert!(
            b == wgpu::Backends::VULKAN || b == wgpu::Backends::DX12 || b == wgpu::Backends::METAL
        );
    }

    #[test]
    fn identity_from_info_captures_name() {
        // AdapterIdentity should carry all fields from AdapterInfo.
        let id = AdapterIdentity {
            name: "AMD Radeon RX 6800".into(),
            vendor: 4098,
            device: 0x73BF,
            backend: "vulkan".into(),
            pci_bus: "0000:01:00.0".into(),
        };
        assert_eq!(id.name, "AMD Radeon RX 6800");
        assert_eq!(id.pci_bus, "0000:01:00.0");
    }
}