Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: wip randomx miner #6508

Closed
wants to merge 32 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
e94f73c
Add scaffold for randomx_miner
brianp Aug 28, 2024
63e0d2f
Communicate with monero node over proxy
brianp Aug 29, 2024
5ac4dd9
refactor requests to the proxy
brianp Aug 30, 2024
14f2c3b
Calculate the hash
brianp Aug 30, 2024
ac56f12
increment the blockhashing blog nonce
brianp Aug 30, 2024
bf6bf05
Error refactoring
brianp Sep 2, 2024
74c3cc9
Allow the RandomX factory to accept params
brianp Sep 2, 2024
a177bd4
Add to CI
brianp Sep 2, 2024
0c4b9bf
submit the block with successful hash
brianp Sep 2, 2024
65223ae
Update the mined block timestamp
brianp Sep 3, 2024
fce301e
Initialize empty caches on lite mode
brianp Sep 3, 2024
8876af8
Add cli options for node and wallet address
brianp Sep 3, 2024
a497ff9
Update config options
brianp Sep 3, 2024
472720c
Enhance the config options with more usability
brianp Sep 3, 2024
e29d5ae
Re-write for better thread management
brianp Sep 4, 2024
a0b242f
Add support for shared caches when multithreading
brianp Sep 4, 2024
c9fc64f
Better bail out for new templates
brianp Sep 4, 2024
8fa9565
Enhance logging and include thread index
brianp Sep 4, 2024
d4e57fa
Remove unused includes
brianp Sep 4, 2024
2f474cc
formatting
brianp Sep 5, 2024
31f47b6
machete
brianp Sep 5, 2024
e8b1a2e
lints
brianp Sep 5, 2024
cdc2e62
tari deps version bump
brianp Sep 5, 2024
f3330aa
Less noisy console
brianp Sep 6, 2024
a6c8f22
Fix refresh limit
brianp Sep 6, 2024
169c77c
Use thread::scope to avoid cloning
brianp Sep 6, 2024
7a08e4a
Use unique keys when creating vms
brianp Sep 6, 2024
7b10c3c
Only report block found on success submit
brianp Sep 6, 2024
f4bc933
Ensure the right loops are broken
brianp Sep 6, 2024
f045a14
Move blocking code out of the mining cycle
brianp Sep 6, 2024
6e74330
Remove the randomx miner application
brianp Sep 6, 2024
4cb9058
Remove remnamts
brianp Sep 6, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build_binaries.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ concurrency:
group: '${{ github.workflow }} @ ${{ github.event.pull_request.head.label || github.head_ref || github.ref }}'
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/v') || github.ref != 'refs/heads/development' || github.ref != 'refs/heads/nextnet' || github.ref != 'refs/heads/stagenet' }}

permissions: {}
permissions: { }

jobs:
matrix-prep:
Expand Down
71 changes: 39 additions & 32 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions base_layer/core/src/proof_of_work/monero_rx/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ pub fn randomx_difficulty(
let monero_pow_data = verify_header(header, genesis_block_hash, consensus)?;
trace!(target: LOG_TARGET, "Valid Monero data: {}", monero_pow_data);
let blockhashing_blob = monero_pow_data.to_blockhashing_blob();
let vm = randomx_factory.create(monero_pow_data.randomx_key())?;
let vm = randomx_factory.create(monero_pow_data.randomx_key(), None, None)?;
get_random_x_difficulty(&blockhashing_blob, &vm).map(|(diff, _)| diff)
}

Expand Down Expand Up @@ -1245,7 +1245,7 @@ mod test {
let key = from_hex("2aca6501719a5c7ab7d4acbc7cc5d277b57ad8c27c6830788c2d5a596308e5b1").unwrap();
let rx = RandomXFactory::default();

let (difficulty, hash) = get_random_x_difficulty(&input, &rx.create(&key).unwrap()).unwrap();
let (difficulty, hash) = get_random_x_difficulty(&input, &rx.create(&key, None, None).unwrap()).unwrap();
assert_eq!(
hash.to_hex(),
"f68fbc8cc85bde856cd1323e9f8e6f024483038d728835de2f8c014ff6260000"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ mod test {
fn randomx_hash(input: &[u8], key: &str) -> String {
let key = from_hex(key).unwrap();
RandomXFactory::default()
.create(&key)
.create(&key, None, None)
.unwrap()
.calculate_hash(input)
.unwrap()
Expand Down
2 changes: 1 addition & 1 deletion base_layer/core/src/proof_of_work/monero_rx/pow_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ use crate::{
proof_of_work::monero_rx::helpers::create_block_hashing_blob,
};

/// This is a struct to deserialize the data from he pow field into data required for the randomX Monero merged mine
/// This is a struct to deserialize the data from the pow field into data required for the randomX Monero merged mine
/// pow.
#[derive(Clone, Debug)]
pub struct MoneroPowData {
Expand Down
91 changes: 50 additions & 41 deletions base_layer/core/src/proof_of_work/randomx_factory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
};

use log::*;
use randomx_rs::{RandomXCache, RandomXError, RandomXFlag, RandomXVM};
use randomx_rs::{RandomXCache, RandomXDataset, RandomXError, RandomXFlag, RandomXVM};

const LOG_TARGET: &str = "c::pow::randomx_factory";

Expand All @@ -35,32 +35,21 @@ pub struct RandomXVMInstance {
}

impl RandomXVMInstance {
fn create(key: &[u8], flags: RandomXFlag) -> Result<Self, RandomXVMFactoryError> {
let (flags, cache) = match RandomXCache::new(flags, key) {
Ok(cache) => (flags, cache),
Err(err) => {
warn!(
target: LOG_TARGET,
"Error initializing RandomX cache with flags {:?}. {:?}. Fallback to default flags", flags, err
);
// This is informed by how RandomX falls back on any cache allocation failure
// https://github.com/xmrig/xmrig/blob/02b2b87bb685ab83b132267aa3c2de0766f16b8b/src/crypto/rx/RxCache.cpp#L88
let flags = RandomXFlag::FLAG_DEFAULT;
let cache = RandomXCache::new(flags, key)?;
(flags, cache)
},
};

fn create(
key: &[u8],
flags: RandomXFlag,
cache: Option<RandomXCache>,
dataset: Option<RandomXDataset>,
) -> Result<Self, RandomXVMFactoryError> {
// Note: Memory required per VM in light mode is 256MB
let vm = RandomXVM::new(flags, Some(cache), None)?;

// Note: No dataset is initialized here because we want to run in light mode. Only a cache
// is required by the VM for verification, giving it a dataset will only make the VM
// consume more memory than necessary. Dataset is currently an optional value as it may be
// useful at some point in future.

// Note: RandomXFlag::FULL_MEM and RandomXFlag::LARGE_PAGES are incompatible with
// light mode. These are not set by RandomX automatically even in fast mode.
let cache = match cache {
Some(c) => c,
None => RandomXCache::new(flags, key)?,
};
let vm = RandomXVM::new(flags, Some(cache), dataset)?;

Ok(Self {
#[allow(clippy::arc_with_non_send_sync)]
Expand Down Expand Up @@ -106,15 +95,26 @@ impl RandomXFactory {
}
}

pub fn new_with_flags(max_vms: usize, flags: RandomXFlag) -> Self {
Self {
inner: Arc::new(RwLock::new(RandomXFactoryInner::new_with_flags(max_vms, flags))),
}
}

/// Create a new RandomX VM instance with the specified key
pub fn create(&self, key: &[u8]) -> Result<RandomXVMInstance, RandomXVMFactoryError> {
pub fn create(
&self,
key: &[u8],
cache: Option<RandomXCache>,
dataset: Option<RandomXDataset>,
) -> Result<RandomXVMInstance, RandomXVMFactoryError> {
let res;
{
let mut inner = self
.inner
.write()
.map_err(|_| RandomXVMFactoryError::PoisonedLockError)?;
res = inner.create(key)?;
res = inner.create(key, cache, dataset)?;
}
Ok(res)
}
Expand Down Expand Up @@ -158,29 +158,38 @@ impl RandomXFactoryInner {
}
}

pub(crate) fn new_with_flags(max_vms: usize, flags: RandomXFlag) -> Self {
debug!(
target: LOG_TARGET,
"RandomX factory started with {} max VMs and recommended flags = {:?}", max_vms, flags
);
Self {
flags,
vms: Default::default(),
max_vms,
}
}

/// Create a new RandomXVMInstance
pub(crate) fn create(&mut self, key: &[u8]) -> Result<RandomXVMInstance, RandomXVMFactoryError> {
pub(crate) fn create(
&mut self,
key: &[u8],
cache: Option<RandomXCache>,
dataset: Option<RandomXDataset>,
) -> Result<RandomXVMInstance, RandomXVMFactoryError> {
if let Some(entry) = self.vms.get_mut(key) {
let vm = entry.1.clone();
entry.0 = Instant::now();
return Ok(vm);
}

if self.vms.len() >= self.max_vms {
let mut oldest_value = Instant::now();
let mut oldest_key = None;
for (k, v) in &self.vms {
if v.0 < oldest_value {
oldest_key = Some(k.clone());
oldest_value = v.0;
}
}
if let Some(k) = oldest_key {
self.vms.remove(&k);
if let Some(oldest_key) = self.vms.iter().min_by_key(|(_, (i, _))| *i).map(|(k, _)| k.clone()) {
self.vms.remove(&oldest_key);
}
}

let vm = RandomXVMInstance::create(key, self.flags)?;
let vm = RandomXVMInstance::create(key, self.flags, cache, dataset)?;

self.vms.insert(Vec::from(key), (Instant::now(), vm.clone()));

Expand Down Expand Up @@ -216,14 +225,14 @@ mod test {
let factory = RandomXFactory::new(2);

let key = b"some-key";
let vm = factory.create(&key[..]).unwrap();
let vm = factory.create(&key[..], None, None).unwrap();
let preimage = b"hashme";
let hash1 = vm.calculate_hash(&preimage[..]).unwrap();
let vm = factory.create(&key[..]).unwrap();
let vm = factory.create(&key[..], None, None).unwrap();
assert_eq!(vm.calculate_hash(&preimage[..]).unwrap(), hash1);

let key = b"another-key";
let vm = factory.create(&key[..]).unwrap();
let vm = factory.create(&key[..], None, None).unwrap();
assert_ne!(vm.calculate_hash(&preimage[..]).unwrap(), hash1);
}

Expand All @@ -236,7 +245,7 @@ mod test {
let factory = factory.clone();
threads.push(tokio::spawn(async move {
let key = b"some-key";
let vm = factory.create(&key[..]).unwrap();
let vm = factory.create(&key[..], None, None).unwrap();
let preimage = b"hashme";
let _hash = vm.calculate_hash(&preimage[..]).unwrap();
}));
Expand Down
6 changes: 3 additions & 3 deletions common/src/configuration/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,9 @@ pub fn get_default_config(use_mining_config: bool) -> [&'static str; 12] {
include_str!("../../config/presets/g_miner.toml"),
include_str!("../../config/presets/f_merge_mining_proxy.toml"),
include_str!("../../config/presets/e_validator_node.toml"),
include_str!("../../config/presets/h_collectibles.toml"),
include_str!("../../config/presets/i_indexer.toml"),
include_str!("../../config/presets/j_dan_wallet_daemon.toml"),
include_str!("../../config/presets/i_collectibles.toml"),
include_str!("../../config/presets/j_indexer.toml"),
include_str!("../../config/presets/k_dan_wallet_daemon.toml"),
]
}

Expand Down
Loading