ccp_randomx/
cache.rs

1/*
2 * Copyright 2024 Fluence DAO
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use std::sync::Arc;
18
19use crate::bindings::cache::*;
20use crate::flags::RandomXFlags;
21use crate::try_alloc;
22use crate::RResult;
23
24// constant that doesn't seems to ever change
25const ARGON_BLOCK_SIZE: u64 = 1024;
26// RandomX's configuration.h
27const RANDOMX_ARGON_MEMORY: u64 = 262144;
28pub const CACHE_LEN: u64 = RANDOMX_ARGON_MEMORY * ARGON_BLOCK_SIZE;
29
30#[derive(Debug)]
31pub struct Cache {
32    inner: Arc<CacheInner>,
33}
34
35#[derive(Debug)]
36struct CacheInner {
37    cache: *mut randomx_cache,
38}
39
40unsafe impl Send for CacheInner {}
41unsafe impl Sync for CacheInner {}
42
43/// Contains a Cache handle, can't be created from scratch,
44/// only obtained from already existing Cache.
45#[derive(Clone, Debug)]
46pub struct CacheHandle {
47    inner: Arc<CacheInner>,
48}
49
50impl Cache {
51    /// Creates RandomX cache with the provided global_nonce.
52    /// Flags is any combination of these 2 flags (each flag can be set or not set):
53    ///  - RANDOMX_FLAG_LARGE_PAGES - allocate memory in large pages
54    ///  - RANDOMX_FLAG_JIT - create cache structure with JIT compilation support; this makes
55    ///                                     subsequent Dataset initialization faster
56    /// Optionally, one of these two flags may be selected:
57    ///  - RANDOMX_FLAG_ARGON2_SSSE3 - optimized Argon2 for CPUs with the SSSE3 instruction set
58    ///                                makes subsequent cache initialization faster
59    ///   - RANDOMX_FLAG_ARGON2_AVX2 - optimized Argon2 for CPUs with the AVX2 instruction set
60    ///                                makes subsequent cache initialization faster
61    pub fn new(global_nonce: &[u8], flags: RandomXFlags) -> RResult<Self> {
62        let cache = try_alloc!(
63            randomx_alloc_cache(flags.bits()),
64            crate::RandomXError::CacheAllocationFailed { flags }
65        );
66
67        let cache_inner = CacheInner { cache };
68        let mut cache = Self {
69            inner: Arc::new(cache_inner),
70        };
71        cache.initialize(global_nonce);
72        Ok(cache)
73    }
74
75    /// Initializes the cache memory using the provided global nonce value.
76    /// Does nothing if called with the same value again.
77    pub fn initialize(&mut self, global_nonce: &[u8]) {
78        unsafe {
79            randomx_init_cache(
80                self.raw(),
81                global_nonce.as_ptr() as *const std::ffi::c_void,
82                global_nonce.len(),
83            )
84        };
85    }
86
87    pub fn handle(&self) -> CacheHandle {
88        CacheHandle {
89            inner: self.inner.clone(),
90        }
91    }
92
93    pub(crate) fn raw(&self) -> *mut randomx_cache {
94        self.inner.cache
95    }
96}
97
98impl CacheHandle {
99    pub fn raw(&self) -> *mut randomx_cache {
100        self.inner.cache
101    }
102}
103
104impl Drop for CacheInner {
105    fn drop(&mut self) {
106        unsafe { randomx_release_cache(self.cache) }
107    }
108}
109
110pub trait CacheRawAPI {
111    fn raw(&self) -> *mut randomx_cache;
112}
113
114impl CacheRawAPI for Cache {
115    fn raw(&self) -> *mut randomx_cache {
116        self.raw()
117    }
118}
119
120impl CacheRawAPI for CacheHandle {
121    fn raw(&self) -> *mut randomx_cache {
122        self.raw()
123    }
124}