harmoniis-wallet 0.1.44

Smart-contract wallet for the Harmoniis decentralised marketplace (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
//! Cloud mining orchestration — start, stop, destroy, status, info.
//!
//! Security model:
//! - SSH key derived from wallet vault (namespace "vast-ssh") — deterministic, no files
//! - Only a derived labeled webcash wallet goes to the cloud
//! - Recovery uses the local deterministic secret — no SCP download needed

use anyhow::{Context, Result};
use std::path::Path;

use super::config::{self, InstanceState};
use super::ssh;
use super::vast::VastClient;

const REMOTE_HRMW: &str = "/root/.local/bin/hrmw";
const REMOTE_WALLET: &str = "/root/cloudminer_webcash.db";

/// Print the top offers table and let the user select.
pub fn print_offers_table(offers: &[super::vast::Offer]) {
    println!();
    println!(
        "{:<3} {:<5} {:<16} {:>10} {:>8} {:>10}  {:>10}",
        "#", "GPUs", "GPU", "TFLOPS", "$/hr", "FLOPS/$", "Offer ID"
    );
    println!("{}", "-".repeat(75));
    for (i, o) in offers.iter().enumerate() {
        println!(
            "{:<3} {:<5} {:<16} {:>10.1} {:>8.2} {:>10.1}  {:>10}",
            i + 1,
            format!("{}x", o.num_gpus),
            o.gpu_name,
            o.tflops(),
            o.dph_total,
            o.flops_per_dollar(),
            o.id,
        );
    }
    println!();
}

/// Prompt user to select an offer.
pub fn prompt_offer_selection(offers: &[super::vast::Offer]) -> Result<&super::vast::Offer> {
    if offers.is_empty() {
        anyhow::bail!("No GPU offers found matching criteria");
    }
    if offers.len() == 1 {
        println!("Only one offer available — selecting it.");
        return Ok(&offers[0]);
    }

    print!("Select offer [1-{}] (default 1): ", offers.len());
    use std::io::Write;
    std::io::stdout().flush()?;

    let mut input = String::new();
    std::io::stdin().read_line(&mut input)?;
    let input = input.trim();

    let idx = if input.is_empty() {
        0
    } else {
        input
            .parse::<usize>()
            .context("invalid selection")?
            .checked_sub(1)
            .context("selection must be >= 1")?
    };

    offers
        .get(idx)
        .ok_or_else(|| anyhow::anyhow!("selection out of range"))
}

/// Full cloud mining start: search → select → provision → install → mine.
///
/// Called by `hrmw webminer cloud start`. Does everything in one flow.
pub async fn start(
    label: &str,
    machine_id: Option<u64>,
    wallet_db_path: &Path,
    ssh_key: &ed25519_dalek::SigningKey,
) -> Result<InstanceState> {
    let cfg = config::load_config()?;
    let api_key = config::resolve_api_key(&cfg)?;
    let client = VastClient::new(&api_key);

    // 1. Upload SSH key to Vast.ai account
    println!("[1/6] Uploading SSH key to Vast.ai...");
    let pubkey = ssh::ssh_public_key_string(ssh_key);
    client.upload_ssh_key(&pubkey).await?;

    // 2. Select offer
    let offer_id = if let Some(id) = machine_id {
        println!("[2/6] Using specified machine: {id}");
        id
    } else {
        println!("[2/6] Searching for best GPU offers...");
        let offers = client.find_best_offers().await?;
        if offers.is_empty() {
            anyhow::bail!("No GPU offers found. Check Vast.ai availability.");
        }
        print_offers_table(&offers);
        let selected = prompt_offer_selection(&offers)?;
        println!(
            "  Selected: {}x {} (${:.2}/hr, {:.1} TFLOPS)",
            selected.num_gpus,
            selected.gpu_name,
            selected.dph_total,
            selected.tflops()
        );
        selected.id
    };

    // 3. Create instance (no onstart — we install everything via SSH after boot)
    println!("[3/6] Creating instance...");
    let instance_id = client.create_instance(offer_id, "").await?;
    println!("  Instance: {instance_id}");

    // 4. Wait for running (5 min max, auto-destroy if stuck)
    println!("[4/6] Waiting for instance to start...");
    let instance = wait_for_running(&client, instance_id).await?;
    let (ssh_host, ssh_port) = instance
        .ssh_connection()
        .ok_or_else(|| anyhow::anyhow!("No SSH connection info"))?;
    println!("  SSH: root@{ssh_host}:{ssh_port}");

    // Wait for SSH to accept connections
    wait_for_ssh(ssh_key, &ssh_host, ssh_port).await?;

    // 5. Install GLIBC + hrmw via SSH
    println!("[5/6] Installing hrmw...");
    install_hrmw_remote(ssh_key, &ssh_host, ssh_port).await?;

    // Verify GPUs
    match ssh::exec(
        ssh_key,
        &ssh_host,
        ssh_port,
        &format!("{REMOTE_HRMW} webminer list-devices"),
    ) {
        Ok(output) => {
            for line in output.trim().lines() {
                println!("  {line}");
            }
        }
        Err(_) => println!("  GPU detection unavailable"),
    }

    // Upload the labeled webcash wallet
    println!("  Uploading mining wallet...");
    upload_file(ssh_key, &ssh_host, ssh_port, wallet_db_path, REMOTE_WALLET)?;

    // 6. Start mining
    println!("[6/6] Starting miner...");
    let _ = ssh::exec(
        ssh_key,
        &ssh_host,
        ssh_port,
        "mkdir -p /root/.harmoniis/wallet",
    );
    let cmd = format!("{REMOTE_HRMW} webminer run --accept-terms --webcash-wallet {REMOTE_WALLET}");
    ssh::exec_background(ssh_key, &ssh_host, ssh_port, &cmd)?;

    // Verify miner started
    tokio::time::sleep(std::time::Duration::from_secs(8)).await;
    let check = ssh::exec(ssh_key, &ssh_host, ssh_port, "pgrep -a hrmw")?;
    if check.trim().is_empty() {
        let log =
            ssh::exec(ssh_key, &ssh_host, ssh_port, "cat /root/miner.log").unwrap_or_default();
        // Auto-destroy on failure
        let _ = client.destroy_instance(instance_id).await;
        config::clear_state()?;
        anyhow::bail!("Miner failed to start. Instance destroyed.\n{log}");
    }

    // Show initial miner output
    if let Ok(log) = ssh::exec(ssh_key, &ssh_host, ssh_port, "head -25 /root/miner.log") {
        println!();
        for line in log.trim().lines() {
            println!("  {line}");
        }
    }

    // Save state
    let state = InstanceState {
        instance_id,
        offer_id,
        label: label.to_string(),
        ssh_host: ssh_host.clone(),
        ssh_port,
        gpu_name: instance.gpu_name.unwrap_or_else(|| "Unknown".to_string()),
        num_gpus: instance.num_gpus.unwrap_or(0),
        cost_per_hour: instance.dph_total.unwrap_or(0.0),
        started_at: chrono::Utc::now().to_rfc3339(),
    };
    config::add_instance(&state)?;

    println!();
    println!("Mining started.");
    println!("  GPU: {}x {}", state.num_gpus, state.gpu_name);
    println!("  Cost: ${:.2}/hr", state.cost_per_hour);
    println!("  Status: hrmw webminer cloud status");
    println!("  Stop:   hrmw webminer cloud stop");

    Ok(state)
}

/// Stop mining and recover locally. Instance keeps running (charges continue).
pub async fn stop(state: &InstanceState, ssh_key: &ed25519_dalek::SigningKey) -> Result<()> {
    println!("Stopping miner on instance {}...", state.instance_id);
    let _ = ssh::exec(
        ssh_key,
        &state.ssh_host,
        state.ssh_port,
        "kill $(pgrep hrmw) 2>/dev/null || true",
    );
    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
    println!("Miner stopped.");
    println!();
    println!("Recovering mined webcash locally...");
    // Recovery happens in the CLI handler (needs wallet objects).
    // This function just stops the remote process.
    println!();
    println!("WARNING: Instance is still running. Vast.ai is still charging.");
    println!("  Use `hrmw webminer cloud destroy` to stop charges.");

    Ok(())
}

/// Destroy a single instance. Stops charges.
pub async fn destroy(state: &InstanceState) -> Result<()> {
    let cfg = config::load_config()?;
    let api_key = config::resolve_api_key(&cfg)?;
    let client = VastClient::new(&api_key);

    println!("Destroying instance {}...", state.instance_id);
    client.destroy_instance(state.instance_id).await?;
    config::remove_instance(state.instance_id)?;
    println!("Instance destroyed. Charges stopped.");

    Ok(())
}

/// Destroy all instances.
pub async fn destroy_all() -> Result<()> {
    let instances = config::load_instances()?;
    if instances.is_empty() {
        println!("No active instances.");
        return Ok(());
    }
    let cfg = config::load_config()?;
    let api_key = config::resolve_api_key(&cfg)?;
    let client = VastClient::new(&api_key);

    for state in &instances {
        println!("Destroying instance {}...", state.instance_id);
        let _ = client.destroy_instance(state.instance_id).await;
    }
    config::clear_state()?;
    println!(
        "All {} instances destroyed. Charges stopped.",
        instances.len()
    );

    Ok(())
}

/// Show remote miner status.
pub async fn status(state: &InstanceState, ssh_key: &ed25519_dalek::SigningKey) -> Result<()> {
    let cfg = config::load_config()?;
    let api_key = config::resolve_api_key(&cfg)?;
    let client = VastClient::new(&api_key);

    let instance = client.get_instance(state.instance_id).await?;

    println!("Cloud Mining Status");
    println!("  Instance: {}", state.instance_id);
    println!(
        "  Status:   {}",
        instance.actual_status.as_deref().unwrap_or("unknown")
    );
    println!("  GPU:      {}x {}", state.num_gpus, state.gpu_name);
    println!("  Cost:     ${:.2}/hr", state.cost_per_hour);
    println!("  Started:  {}", state.started_at);
    println!();

    // Check miner process
    let running = match ssh::exec(
        ssh_key,
        &state.ssh_host,
        state.ssh_port,
        "pgrep -a hrmw || echo 'NOT_RUNNING'",
    ) {
        Ok(output) if output.contains("NOT_RUNNING") => {
            println!("  Miner:    NOT RUNNING");
            false
        }
        Ok(_) => {
            println!("  Miner:    RUNNING");
            true
        }
        Err(e) => {
            println!("  Miner:    unknown ({e})");
            false
        }
    };

    // Extract mining stats from the latest log line
    if running {
        if let Ok(log) = ssh::exec(
            ssh_key,
            &state.ssh_host,
            state.ssh_port,
            "grep 'speed=' /root/miner.log | tail -1",
        ) {
            let line = log.trim();
            if !line.is_empty() {
                // Parse speed= and solutions= from the line
                let speed = line
                    .split("speed=")
                    .nth(1)
                    .and_then(|s| s.split_whitespace().next())
                    .unwrap_or("?");
                let solutions = line
                    .split("solutions=")
                    .nth(1)
                    .and_then(|s| s.split_whitespace().next())
                    .unwrap_or("?");
                println!("  Speed:    {speed}");
                println!("  Solutions: {solutions}");
            }
        }
        // Count total mined
        if let Ok(count) = ssh::exec(
            ssh_key,
            &state.ssh_host,
            state.ssh_port,
            "grep -c 'SOLUTION FOUND' /root/miner.log 2>/dev/null || echo 0",
        ) {
            let n = count.trim();
            if n != "0" {
                let amount = n.parse::<u64>().unwrap_or(0) as f64 * 185.546875;
                println!("  Mined:    {n} solutions ({amount} webcash)");
            }
        }
    }

    // Show last few log lines
    if let Ok(log) = ssh::exec(
        ssh_key,
        &state.ssh_host,
        state.ssh_port,
        "tail -5 /root/miner.log 2>/dev/null",
    ) {
        let trimmed = log.trim();
        if !trimmed.is_empty() {
            println!();
            for line in trimmed.lines() {
                println!("  {line}");
            }
        }
    }

    Ok(())
}

/// Show mining wallet info — remote balance if instance is active, otherwise local.
pub fn info(label: &str, ssh_key: &ed25519_dalek::SigningKey) {
    println!("Mining label: {label}");
    println!("Wallet: {label}_webcash.db");
    if let Ok(Some(state)) = config::load_state() {
        println!();
        println!("Active instance: {}", state.instance_id);
        println!("  GPU: {}x {}", state.num_gpus, state.gpu_name);
        println!("  Cost: ${:.2}/hr", state.cost_per_hour);
        println!("  Started: {}", state.started_at);

        // Show remote mining stats from log
        if let Ok(output) = ssh::exec(
            ssh_key,
            &state.ssh_host,
            state.ssh_port,
            "echo \"solutions=$(grep -c 'SOLUTION FOUND' /root/miner.log 2>/dev/null || echo 0)\"; echo \"inserted=$(grep -c 'Inserted amount' /root/miner.log 2>/dev/null || echo 0)\"; grep 'speed=' /root/miner.log 2>/dev/null | tail -1",
        ) {
            println!();
            println!("Remote mining:");
            for line in output.trim().lines() {
                if line.starts_with("solutions=") {
                    let n: u64 = line.trim_start_matches("solutions=").parse().unwrap_or(0);
                    let amount = n as f64 * 185.546875;
                    println!("  Solutions found: {n} ({amount} webcash)");
                } else if line.starts_with("inserted=") {
                    let n: u64 = line.trim_start_matches("inserted=").parse().unwrap_or(0);
                    let amount = n as f64 * 185.546875;
                    println!("  Inserted to wallet: {n} ({amount} webcash)");
                } else if line.contains("speed=") {
                    let speed = line.split("speed=").nth(1).and_then(|s| s.split_whitespace().next()).unwrap_or("?");
                    println!("  Current speed: {speed}");
                }
            }
        }
    } else {
        println!("No active cloud mining instance.");
        println!();
        println!("Recover mined webcash: hrmw webcash recover --label {label}");
    }
}

// ── Internal helpers ──────────────────────────────────────────────────────

/// Upload a file to remote via SCP.
fn upload_file(
    ssh_key: &ed25519_dalek::SigningKey,
    host: &str,
    port: u16,
    local_path: &Path,
    remote_path: &str,
) -> Result<()> {
    let key_file = ssh::write_temp_key_file(ssh_key)?;
    let status = std::process::Command::new("scp")
        .args([
            "-o",
            "StrictHostKeyChecking=no",
            "-o",
            "UserKnownHostsFile=/dev/null",
            "-o",
            "LogLevel=ERROR",
            "-i",
            &key_file.to_string_lossy(),
            "-P",
            &port.to_string(),
            &local_path.to_string_lossy(),
            &format!("root@{host}:{remote_path}"),
        ])
        .status()
        .context("scp failed")?;
    if !status.success() {
        anyhow::bail!("SCP upload failed");
    }
    Ok(())
}

async fn wait_for_running(client: &VastClient, instance_id: u64) -> Result<super::vast::Instance> {
    for i in 0..30 {
        tokio::time::sleep(std::time::Duration::from_secs(10)).await;
        match client.get_instance(instance_id).await {
            Ok(inst) if inst.is_running() => return Ok(inst),
            Ok(inst) => {
                let s = inst.actual_status.as_deref().unwrap_or("unknown");
                if i % 3 == 0 {
                    println!("  Status: {s}...");
                }
            }
            Err(e) if i > 5 => {
                let _ = client.destroy_instance(instance_id).await;
                return Err(e);
            }
            Err(_) => {}
        }
    }
    println!("  Instance did not start in 5 minutes — destroying...");
    let _ = client.destroy_instance(instance_id).await;
    config::clear_state()?;
    anyhow::bail!("Instance did not start. Destroyed to stop charges. Try a different offer.")
}

async fn wait_for_ssh(ssh_key: &ed25519_dalek::SigningKey, host: &str, port: u16) -> Result<()> {
    for _ in 0..30 {
        if let Ok(out) = ssh::exec(ssh_key, host, port, "echo ok") {
            if out.contains("ok") {
                return Ok(());
            }
        }
        tokio::time::sleep(std::time::Duration::from_secs(5)).await;
    }
    anyhow::bail!("SSH not ready after 2.5 minutes")
}

async fn install_hrmw_remote(
    ssh_key: &ed25519_dalek::SigningKey,
    host: &str,
    port: u16,
) -> Result<()> {
    // Step 1: Ensure system deps are available.
    // - UBUNTU24: has GLIBC 2.39 + libssl3, but may lack NVRTC
    // - Ubuntu 20.04: needs GLIBC + libssl upgrade from noble repo
    println!("  Checking system dependencies...");
    let glibc_check =
        ssh::exec(ssh_key, host, port, "ldd --version 2>&1 | head -1").unwrap_or_default();
    if glibc_check.contains("2.31") || glibc_check.contains("2.35") {
        println!("  Upgrading GLIBC + libssl...");
        ssh::exec(
            ssh_key,
            host,
            port,
            "echo 'deb http://archive.ubuntu.com/ubuntu noble main' >> /etc/apt/sources.list && apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -yqq libc6 libssl3t64",
        )
        .context("GLIBC/libssl upgrade failed")?;
    }

    // Ensure NVRTC is available (needed for CUDA kernel compilation at runtime).
    // UBUNTU24 template has libcuda but not libnvrtc.
    // Try multiple package names to cover CUDA 12.x and 13.x.
    let nvrtc_check =
        ssh::exec(ssh_key, host, port, "ldconfig -p | grep libnvrtc").unwrap_or_default();
    if nvrtc_check.is_empty() {
        println!("  Installing CUDA NVRTC...");
        ssh::exec(
            ssh_key,
            host,
            port,
            concat!(
                "apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -yqq ",
                "cuda-nvrtc-13-0 2>/dev/null || ",
                "DEBIAN_FRONTEND=noninteractive apt-get install -yqq cuda-nvrtc-12-6 2>/dev/null || ",
                "DEBIAN_FRONTEND=noninteractive apt-get install -yqq cuda-nvrtc-12-4 2>/dev/null || ",
                "DEBIAN_FRONTEND=noninteractive apt-get install -yqq cuda-nvrtc-12-0 2>/dev/null || ",
                "DEBIAN_FRONTEND=noninteractive apt-get install -yqq libnvrtc12 2>/dev/null || true",
            ),
        )
        .ok();
    }

    // Step 2: Install hrmw
    println!("  Installing hrmw...");
    ssh::exec(
        ssh_key,
        host,
        port,
        "mkdir -p /root/.harmoniis/wallet /root/.local/bin && curl --proto '=https' --tlsv1.2 -sSf https://harmoniis.com/wallet/install | sh",
    )
    .context("hrmw install failed")?;

    // Step 3: Verify
    let version = ssh::exec(ssh_key, host, port, &format!("{REMOTE_HRMW} --version"))
        .context("hrmw verification failed")?;
    println!("  {}", version.trim());

    Ok(())
}