randomx_rust_wrapper/
cache.rs

1/*
2 * Copyright 2024 Fluence Labs Limited
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#[derive(Debug)]
25pub struct Cache {
26    inner: Arc<CacheInner>,
27}
28
29#[derive(Debug)]
30struct CacheInner {
31    cache: *mut randomx_cache,
32}
33
34unsafe impl Send for CacheInner {}
35unsafe impl Sync for CacheInner {}
36
37/// Contains a Cache handle, can't be created from scratch,
38/// only obtained from already existing Cache.
39#[derive(Clone, Debug)]
40pub struct CacheHandle {
41    inner: Arc<CacheInner>,
42}
43
44impl Cache {
45    /// Creates RandomX cache with the provided global_nonce.
46    /// Flags is any combination of these 2 flags (each flag can be set or not set):
47    ///  - RANDOMX_FLAG_LARGE_PAGES - allocate memory in large pages
48    ///  - RANDOMX_FLAG_JIT - create cache structure with JIT compilation support; this makes
49    ///                                     subsequent Dataset initialization faster
50    /// Optionally, one of these two flags may be selected:
51    ///  - RANDOMX_FLAG_ARGON2_SSSE3 - optimized Argon2 for CPUs with the SSSE3 instruction set
52    ///                                makes subsequent cache initialization faster
53    ///   - RANDOMX_FLAG_ARGON2_AVX2 - optimized Argon2 for CPUs with the AVX2 instruction set
54    ///                                makes subsequent cache initialization faster
55    pub fn new(global_nonce: &[u8], flags: RandomXFlags) -> RResult<Self> {
56        let cache = try_alloc!(
57            randomx_alloc_cache(flags.bits()),
58            crate::RandomXError::CacheAllocationFailed { flags }
59        );
60
61        let cache_inner = CacheInner { cache };
62        let mut cache = Self {
63            inner: Arc::new(cache_inner),
64        };
65        cache.initialize(global_nonce);
66        Ok(cache)
67    }
68
69    /// Initializes the cache memory using the provided global nonce value.
70    /// Does nothing if called with the same value again.
71    pub fn initialize(&mut self, global_nonce: &[u8]) {
72        unsafe {
73            randomx_init_cache(
74                self.raw(),
75                global_nonce.as_ptr() as *const std::ffi::c_void,
76                global_nonce.len(),
77            )
78        };
79    }
80
81    pub fn handle(&self) -> CacheHandle {
82        CacheHandle {
83            inner: self.inner.clone(),
84        }
85    }
86
87    pub(crate) fn raw(&self) -> *mut randomx_cache {
88        self.inner.cache
89    }
90}
91
92impl CacheHandle {
93    pub fn raw(&self) -> *mut randomx_cache {
94        self.inner.cache
95    }
96}
97
98impl Drop for CacheInner {
99    fn drop(&mut self) {
100        unsafe { randomx_release_cache(self.cache) }
101    }
102}
103
104pub trait CacheRawAPI {
105    fn raw(&self) -> *mut randomx_cache;
106}
107
108impl CacheRawAPI for Cache {
109    fn raw(&self) -> *mut randomx_cache {
110        self.raw()
111    }
112}
113
114impl CacheRawAPI for CacheHandle {
115    fn raw(&self) -> *mut randomx_cache {
116        self.raw()
117    }
118}