opt-in-miner 0.4.1

Opt-in Monero/Wownero mining library for transparent application monetization
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
#![deny(missing_docs)]

//! Opt-in Monero/Wownero mining library for application monetization.
//!
//! Embeds background Monero or Wownero mining into any Rust application.
//! Supports both solo mining (direct to a daemon's RPC) and pool mining (via Stratum protocol),
//! with automatic failover across a list of sources.
//!
//! # Features
//!
//! By default, this library mines Monero (via `RandomX`). Enable the
//! `wownero` feature to mine Wownero (via `RandomWOW`) instead.
//!
//! # Quick start
//!
//! Set `MONERO_WALLET`/`MONERO_SOURCES` (or `WOWNERO_WALLET`/`WOWNERO_SOURCES`)
//! at compile time, then:
//!
//! ```ignore
//! let mut miner = opt_in_miner::mining_state!("my-app");
//! miner.start();
//! ```
//!
//! # Builder API
//!
//! For full control, use [`Miner::builder`] directly:
//!
//! ```no_run
//! use opt_in_miner::{ConsentReply, Miner, Source, ConsentStatus, Persistence};
//!
//! let mut miner = Miner::builder()
//!     .wallet("your-monero-wallet-address")
//!     .sources(&[
//!         Source::node("node.moneroworld.com:18089"),
//!         Source::pool("pool.hashvault.pro:3333"),
//!     ])
//!     .cpu_fraction(0.25)
//!     .consent_check(|| ConsentReply {
//!         consent: ConsentStatus::Granted,
//!         persistence: Persistence::Save,
//!     })
//!     .build();
//!
//! miner.start();
//! // Mining runs in background threads. No-op if consent was denied.
//! miner.stop();
//! ```

mod job;
mod pool;
mod settings;
mod solo;
mod state;
mod throttle;
mod worker;

pub use settings::{Persistence, Reply as ConsentReply, Settings, Status as ConsentStatus};
pub use state::{MiningState, ToggleResult, compile_env};
pub use throttle::Throttle;

use pool::PoolSource;
use solo::SoloSource;
use worker::Worker;

use std::{
    sync::{
        Arc,
        atomic::{AtomicBool, AtomicU64, Ordering},
        mpsc,
    },
    thread,
    time::{Duration, Instant},
};

/// A mining source – either a Monero node (solo mining) or a pool (Stratum).
#[derive(Clone)]
pub enum Source {
    /// Solo mining against a Monero daemon's RPC endpoint.
    Solo {
        /// Address in `host:port` format. Default port 18081 if omitted.
        node: String,
    },
    /// Pool mining via the Stratum protocol.
    Pool {
        /// Pool address in `host:port` format.
        url: String,
    },
}

impl Source {
    /// Creates a solo mining source from a node address.
    pub fn node(address: &str) -> Self {
        Self::Solo {
            node: address.into(),
        }
    }

    /// Creates a pool mining source from a pool URL.
    pub fn pool(url: &str) -> Self {
        Self::Pool { url: url.into() }
    }
}

/// Builder for configuring a [`Miner`] instance.
pub struct MinerBuilder {
    sources: Vec<Source>,
    wallet: String,
    password: String,
    threads: usize,
    light: bool,
    cpu_fraction: f32,
    application_name: String,
    consent_check: Option<Box<dyn FnOnce() -> ConsentReply + Send>>,
}

impl MinerBuilder {
    /// Sets the list of mining sources. Tried in order; on failure, the next source is used.
    pub fn sources(mut self, sources: &[Source]) -> Self {
        self.sources = sources.to_vec();
        self
    }

    /// Sets the Monero wallet address that receives mining rewards.
    pub fn wallet(mut self, wallet: &str) -> Self {
        self.wallet = wallet.into();
        self
    }

    /// Sets the pool password. Defaults to `"x"`. Only relevant for pool mining.
    pub fn password(mut self, password: &str) -> Self {
        self.password = password.into();
        self
    }

    /// Sets the number of mining threads. Defaults to 1. Pass 0 for auto-detection.
    pub fn threads(mut self, count: usize) -> Self {
        self.threads = count;
        self
    }

    /// Enables `RandomX` light mode (256 MB RAM instead of 2 GB). Slower but less memory.
    /// Defaults to `true`.
    pub fn light(mut self, enabled: bool) -> Self {
        self.light = enabled;
        self
    }

    /// Sets the fraction of CPU time to use per mining thread (0.01–1.0). Defaults to 0.25.
    /// Can be changed at runtime via [`Miner::set_cpu_fraction`].
    pub fn cpu_fraction(mut self, fraction: f32) -> Self {
        self.cpu_fraction = fraction;
        self
    }

    /// Sets the application name used for consent storage path. Defaults to `"opt-in-miner"`.
    pub fn application_name(mut self, name: &str) -> Self {
        self.application_name = name.into();
        self
    }

    /// Sets a callback that asks the user for mining consent.
    /// Called only when no stored consent exists. The callback returns a [`ConsentReply`]
    /// indicating whether the user accepted and whether to persist the decision.
    pub fn consent_check(mut self, check: impl FnOnce() -> ConsentReply + Send + 'static) -> Self {
        self.consent_check = Some(Box::new(check));
        self
    }

    /// Builds the miner. Checks consent (calling the consent callback if needed).
    /// If consent is denied or missing, the miner is created but [`Miner::start`] will
    /// be a no-op until consent is granted via [`Miner::set_consent`].
    pub fn build(self) -> Miner {
        let mut settings = Settings::new(&self.application_name);

        let enabled = if settings.has_stored() {
            settings.consent() == ConsentStatus::Granted
        } else if let Some(check) = self.consent_check {
            let reply = check();
            settings.set_persistence(reply.persistence);
            settings.set_consent(reply.consent);
            reply.consent == ConsentStatus::Granted
        } else {
            false
        };

        let (thread_count, cpu_fraction) = if settings.has_stored() {
            (settings.threads(), settings.cpu_fraction())
        } else {
            let threads = if self.threads == 0 {
                thread::available_parallelism()
                    .map(std::num::NonZero::get)
                    .unwrap_or(1)
            } else {
                self.threads
            };
            (threads, self.cpu_fraction)
        };

        Miner {
            sources: self.sources,
            wallet: self.wallet,
            password: self.password,
            threads: thread_count,
            light: self.light,
            throttle: Throttle::new(cpu_fraction),
            settings,
            enabled,
            handle: None,
            running: Arc::new(AtomicBool::new(false)),
            hash_count: Arc::new(AtomicU64::new(0)),
        }
    }
}

/// A background Monero miner with runtime-adjustable settings.
///
/// Created via [`Miner::builder`]. Mining runs in background threads and does not
/// block the calling thread. Automatically stops on drop.
pub struct Miner {
    sources: Vec<Source>,
    wallet: String,
    password: String,
    threads: usize,
    light: bool,
    throttle: Throttle,
    settings: Settings,
    enabled: bool,
    handle: Option<thread::JoinHandle<()>>,
    running: Arc<AtomicBool>,
    hash_count: Arc<AtomicU64>,
}

impl Miner {
    /// Creates a new [`MinerBuilder`] with default settings.
    pub fn builder() -> MinerBuilder {
        MinerBuilder {
            sources: Vec::new(),
            wallet: String::new(),
            password: "x".into(),
            threads: 1,
            light: true,
            cpu_fraction: 0.25,
            application_name: "opt-in-miner".into(),
            consent_check: None,
        }
    }

    /// Starts mining in background threads. Returns immediately.
    /// Does nothing if already running or if consent has not been granted.
    pub fn start(&mut self) {
        if !self.enabled || self.sources.is_empty() || self.running.load(Ordering::Relaxed) {
            return;
        }

        let sources = self.sources.clone();
        let wallet = self.wallet.clone();
        let password = self.password.clone();
        let threads = self.threads;
        let light = self.light;
        let throttle = self.throttle.clone();
        let running = self.running.clone();
        let hash_count = self.hash_count.clone();

        running.store(true, Ordering::Relaxed);
        hash_count.store(0, Ordering::Relaxed);

        self.handle = Some(thread::spawn(move || {
            run_mining_loop(
                sources, wallet, password, threads, light, throttle, running, hash_count,
            );
        }));
    }

    /// Stops mining and waits for all threads to finish.
    pub fn stop(&mut self) {
        self.running.store(false, Ordering::Relaxed);
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }

    /// Returns whether the miner is currently running.
    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::Relaxed)
    }

    /// Returns the total number of hashes computed since the last [`Miner::start`].
    pub fn hash_count(&self) -> u64 {
        self.hash_count.load(Ordering::Relaxed)
    }

    /// Returns the current CPU fraction (0.01–1.0).
    pub fn cpu_fraction(&self) -> f32 {
        self.throttle.fraction()
    }

    /// Returns the current number of mining threads.
    pub fn threads(&self) -> usize {
        self.threads
    }

    /// Changes the number of mining threads. Restarts mining if currently running.
    pub fn set_threads(&mut self, count: usize) {
        self.threads = if count == 0 {
            thread::available_parallelism()
                .map(std::num::NonZero::get)
                .unwrap_or(1)
        } else {
            count
        };
        self.settings.set_threads(self.threads);
        if self.is_running() {
            self.stop();
            self.start();
        }
    }

    /// Changes the CPU fraction at runtime. Takes effect within seconds.
    pub fn set_cpu_fraction(&mut self, fraction: f32) {
        self.throttle.set_fraction(fraction);
        self.settings.set_cpu_fraction(fraction);
    }

    /// Returns the current consent status. [`ConsentStatus::Denied`] if no decision is stored.
    pub fn consent_status(&self) -> ConsentStatus {
        self.settings.consent()
    }

    /// Overrides the stored consent. [`ConsentStatus::Denied`] stops mining immediately.
    /// [`ConsentStatus::Granted`] enables mining (call [`Miner::start`] to begin).
    pub fn set_consent(&mut self, status: ConsentStatus) {
        self.settings.set_consent(status);
        self.enabled = status == ConsentStatus::Granted;
        if !self.enabled {
            self.stop();
        }
    }

    /// Returns the current persistence mode.
    pub fn persistence(&self) -> Persistence {
        self.settings.persistence()
    }

    /// Changes the persistence mode. [`Persistence::Save`] persists immediately.
    /// [`Persistence::Ask`] removes the file and resets settings to defaults.
    pub fn set_persistence(&mut self, persistence: Persistence) {
        self.settings.set_persistence(persistence);
    }
}

impl Drop for Miner {
    fn drop(&mut self) {
        self.stop();
    }
}

fn run_mining_loop(
    sources: Vec<Source>,
    wallet: String,
    password: String,
    threads: usize,
    light: bool,
    throttle: Throttle,
    running: Arc<AtomicBool>,
    hash_count: Arc<AtomicU64>,
) {
    let mut source_index = 0;

    while running.load(Ordering::Relaxed) {
        let source = &sources[source_index];
        let result = match source {
            Source::Pool { url } => run_pool(
                url,
                &wallet,
                &password,
                threads,
                light,
                &throttle,
                &running,
                &hash_count,
            ),
            Source::Solo { node } => run_solo(
                node,
                &wallet,
                threads,
                light,
                &throttle,
                &running,
                &hash_count,
            ),
        };

        if result.is_err() && running.load(Ordering::Relaxed) {
            source_index = (source_index + 1) % sources.len();
            thread::sleep(Duration::from_secs(5));
        }
    }
}

fn run_pool(
    url: &str,
    wallet: &str,
    password: &str,
    threads: usize,
    light: bool,
    throttle: &Throttle,
    running: &Arc<AtomicBool>,
    hash_count: &Arc<AtomicU64>,
) -> Result<(), ()> {
    let (mut pool, initial_job) = PoolSource::login(url, wallet, password).map_err(|_| ())?;

    let (share_sender, share_receiver) = mpsc::channel();
    let worker = Worker::new(
        threads,
        light,
        throttle.clone(),
        share_sender,
        hash_count.clone(),
    );
    worker.set_job(initial_job);

    let mut last_keepalive = Instant::now();
    let keepalive_interval = Duration::from_secs(60);

    while running.load(Ordering::Relaxed) {
        if let Some(job) = pool.try_receive_job() {
            worker.set_job(job);
        }

        while let Ok(share) = share_receiver.try_recv() {
            if pool
                .submit(&share.job_id, &share.nonce_hex, &share.hash_hex)
                .is_err()
            {
                worker.stop();
                return Err(());
            }
        }

        if last_keepalive.elapsed() >= keepalive_interval {
            if pool.keepalive().is_err() {
                worker.stop();
                return Err(());
            }
            last_keepalive = Instant::now();
        }

        thread::sleep(Duration::from_millis(100));
    }

    worker.stop();
    Ok(())
}

fn run_solo(
    node: &str,
    wallet: &str,
    threads: usize,
    light: bool,
    throttle: &Throttle,
    running: &Arc<AtomicBool>,
    hash_count: &Arc<AtomicU64>,
) -> Result<(), ()> {
    let mut source = SoloSource::new(node, wallet);
    let initial_job = source.get_block_template().map_err(|_| ())?;

    let (share_sender, share_receiver) = mpsc::channel();
    let worker = Worker::new(
        threads,
        light,
        throttle.clone(),
        share_sender,
        hash_count.clone(),
    );

    let mut current_job = initial_job.clone();
    worker.set_job(initial_job);

    let mut last_template_poll = Instant::now();
    let template_poll_interval = Duration::from_secs(15);

    while running.load(Ordering::Relaxed) {
        if last_template_poll.elapsed() >= template_poll_interval {
            if let Ok(new_job) = source.get_block_template() {
                if new_job.id != current_job.id {
                    current_job = new_job.clone();
                    worker.set_job(new_job);
                }
                last_template_poll = Instant::now();
            } else {
                source.disconnect();
                worker.stop();
                return Err(());
            }
        }

        while let Ok(share) = share_receiver.try_recv() {
            if let Some(template) = &current_job.template_blob
                && share.job_id == current_job.id
            {
                let mut block = template.clone();
                let nonce_offset = 39;
                if block.len() > nonce_offset + 4 {
                    block[nonce_offset..nonce_offset + 4]
                        .copy_from_slice(&share.nonce_value.to_le_bytes());
                    let _ = source.submit_block(&block);
                }
            }
        }

        thread::sleep(Duration::from_millis(100));
    }

    worker.stop();
    Ok(())
}