Skip to content

Commit

Permalink
Add AlignType and use it for buffer allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
elichai committed Apr 29, 2020
1 parent 0782872 commit 84ebaa0
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 31 deletions.
30 changes: 20 additions & 10 deletions secp256k1-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,12 @@ pub mod recovery;
use core::{hash, slice, ptr};
use types::*;

#[cfg(any(target_pointer_width = "32", target_pointer_width = "16", target_pointer_width = "8"))]
pub type AlignType = u64;

#[cfg(not(any(target_pointer_width = "32", target_pointer_width = "16", target_pointer_width = "8")))]
pub type AlignType = usize;

/// Flag for context to enable no precomputation
pub const SECP256K1_START_NONE: c_uint = 1;
/// Flag for context to enable verification precomputation
Expand Down Expand Up @@ -300,14 +306,18 @@ pub unsafe extern "C" fn rustsecp256k1_v0_1_1_context_create(flags: c_uint) -> *
use std::mem;
assert!(mem::align_of::<usize>() >= mem::align_of::<u8>());
assert_eq!(mem::size_of::<usize>(), mem::size_of::<&usize>());
assert!(mem::align_of::<AlignType>() >= mem::align_of::<u8>());
assert!(mem::align_of::<AlignType>() >= mem::align_of::<usize>());
assert!(mem::size_of::<AlignType>() >= mem::size_of::<usize>());
assert!(mem::align_of::<AlignType>() >= mem::align_of::<&AlignType>());

let word_size = mem::size_of::<usize>();
let word_size = mem::size_of::<AlignType>();
let n_words = (secp256k1_context_preallocated_size(flags) + word_size - 1) / word_size;

let buf = vec![0usize; n_words + 1].into_boxed_slice();
let ptr = Box::into_raw(buf) as *mut usize;
::core::ptr::write(ptr, n_words);
let ptr: *mut usize = ptr.offset(1);
let buf = vec![0 as AlignType; n_words + 1].into_boxed_slice();
let ptr: *mut AlignType = Box::into_raw(buf) as *mut AlignType;
::core::ptr::write(ptr, n_words as AlignType);
let ptr: *mut AlignType = ptr.offset(1);

secp256k1_context_preallocated_create(ptr as *mut c_void, flags)
}
Expand All @@ -327,12 +337,12 @@ pub unsafe fn secp256k1_context_create(flags: c_uint) -> *mut Context {
#[cfg(all(feature = "std", not(feature = "external-symbols")))]
pub unsafe extern "C" fn rustsecp256k1_v0_1_1_context_destroy(ctx: *mut Context) {
secp256k1_context_preallocated_destroy(ctx);
let ctx: *mut usize = ctx as *mut usize;
let ctx: *mut AlignType = ctx as *mut AlignType;

let n_words_ptr: *mut usize = ctx.offset(-1);
let n_words: usize = ::core::ptr::read(n_words_ptr);
let slice: &mut [usize] = slice::from_raw_parts_mut(n_words_ptr , n_words+1);
let _ = Box::from_raw(slice as *mut [usize]);
let n_words_ptr: *mut AlignType = ctx.offset(-1);
let n_words: AlignType = ::core::ptr::read(n_words_ptr);
let slice: &mut [AlignType] = slice::from_raw_parts_mut(n_words_ptr , (n_words+1) as usize);
let _ = Box::from_raw(slice as *mut [AlignType]);
}

#[cfg(all(feature = "std", not(feature = "external-symbols")))]
Expand Down
36 changes: 18 additions & 18 deletions src/context.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use core::marker::PhantomData;
use core::mem::ManuallyDrop;
use ptr;
use ffi::{self, CPtr};
use ffi::{self, CPtr, AlignType};
use ffi::types::{c_uint, c_void};
use Error;
use Secp256k1;
Expand All @@ -17,7 +17,7 @@ pub unsafe trait Context : private::Sealed {
/// A constant description of the context.
const DESCRIPTION: &'static str;
/// A function to deallocate the memory when the context is dropped.
unsafe fn deallocate(ptr: *mut [u8]);
unsafe fn deallocate(ptr: *mut [AlignType]);
}

/// Marker trait for indicating that an instance of `Secp256k1` can be used for signing.
Expand Down Expand Up @@ -80,7 +80,7 @@ mod std_only {
const FLAGS: c_uint = ffi::SECP256K1_START_SIGN;
const DESCRIPTION: &'static str = "signing only";

unsafe fn deallocate(ptr: *mut [u8]) {
unsafe fn deallocate(ptr: *mut [AlignType]) {
let _ = Box::from_raw(ptr);
}
}
Expand All @@ -89,7 +89,7 @@ mod std_only {
const FLAGS: c_uint = ffi::SECP256K1_START_VERIFY;
const DESCRIPTION: &'static str = "verification only";

unsafe fn deallocate(ptr: *mut [u8]) {
unsafe fn deallocate(ptr: *mut [AlignType]) {
let _ = Box::from_raw(ptr);
}
}
Expand All @@ -98,7 +98,7 @@ mod std_only {
const FLAGS: c_uint = VerifyOnly::FLAGS | SignOnly::FLAGS;
const DESCRIPTION: &'static str = "all capabilities";

unsafe fn deallocate(ptr: *mut [u8]) {
unsafe fn deallocate(ptr: *mut [AlignType]) {
let _ = Box::from_raw(ptr);
}
}
Expand All @@ -109,7 +109,7 @@ mod std_only {
#[cfg(target_arch = "wasm32")]
ffi::types::sanity_checks_for_wasm();

let buf = vec![0u8; Self::preallocate_size_gen()].into_boxed_slice();
let buf = vec![0 as AlignType; Self::preallocate_size_gen()].into_boxed_slice();
let ptr = Box::into_raw(buf);
Secp256k1 {
ctx: unsafe { ffi::secp256k1_context_preallocated_create(ptr as *mut c_void, C::FLAGS) },
Expand Down Expand Up @@ -149,7 +149,7 @@ mod std_only {
impl<C: Context> Clone for Secp256k1<C> {
fn clone(&self) -> Secp256k1<C> {
let clone_size = unsafe {ffi::secp256k1_context_preallocated_clone_size(self.ctx)};
let ptr_buf = Box::into_raw(vec![0u8; clone_size].into_boxed_slice());
let ptr_buf = Box::into_raw(vec![0 as AlignType; clone_size].into_boxed_slice());
Secp256k1 {
ctx: unsafe { ffi::secp256k1_context_preallocated_clone(self.ctx, ptr_buf as *mut c_void) },
phantom: PhantomData,
Expand All @@ -169,7 +169,7 @@ unsafe impl<'buf> Context for SignOnlyPreallocated<'buf> {
const FLAGS: c_uint = ffi::SECP256K1_START_SIGN;
const DESCRIPTION: &'static str = "signing only";

unsafe fn deallocate(_ptr: *mut [u8]) {
unsafe fn deallocate(_ptr: *mut [AlignType]) {
// Allocated by the user
}
}
Expand All @@ -178,7 +178,7 @@ unsafe impl<'buf> Context for VerifyOnlyPreallocated<'buf> {
const FLAGS: c_uint = ffi::SECP256K1_START_VERIFY;
const DESCRIPTION: &'static str = "verification only";

unsafe fn deallocate(_ptr: *mut [u8]) {
unsafe fn deallocate(_ptr: *mut [AlignType]) {
// Allocated by the user
}
}
Expand All @@ -187,14 +187,14 @@ unsafe impl<'buf> Context for AllPreallocated<'buf> {
const FLAGS: c_uint = SignOnlyPreallocated::FLAGS | VerifyOnlyPreallocated::FLAGS;
const DESCRIPTION: &'static str = "all capabilities";

unsafe fn deallocate(_ptr: *mut [u8]) {
unsafe fn deallocate(_ptr: *mut [AlignType]) {
// Allocated by the user
}
}

impl<'buf, C: Context + 'buf> Secp256k1<C> {
/// Lets you create a context with preallocated buffer in a generic manner(sign/verify/all)
pub fn preallocated_gen_new(buf: &'buf mut [u8]) -> Result<Secp256k1<C>, Error> {
pub fn preallocated_gen_new(buf: &'buf mut [AlignType]) -> Result<Secp256k1<C>, Error> {
#[cfg(target_arch = "wasm32")]
ffi::types::sanity_checks_for_wasm();

Expand All @@ -208,14 +208,14 @@ impl<'buf, C: Context + 'buf> Secp256k1<C> {
C::FLAGS)
},
phantom: PhantomData,
buf: buf as *mut [u8],
buf: buf as *mut [AlignType],
})
}
}

impl<'buf> Secp256k1<AllPreallocated<'buf>> {
/// Creates a new Secp256k1 context with all capabilities
pub fn preallocated_new(buf: &'buf mut [u8]) -> Result<Secp256k1<AllPreallocated<'buf>>, Error> {
pub fn preallocated_new(buf: &'buf mut [AlignType]) -> Result<Secp256k1<AllPreallocated<'buf>>, Error> {
Secp256k1::preallocated_gen_new(buf)
}
/// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for a context
Expand All @@ -238,14 +238,14 @@ impl<'buf> Secp256k1<AllPreallocated<'buf>> {
ManuallyDrop::new(Secp256k1 {
ctx: raw_ctx,
phantom: PhantomData,
buf: ptr::null_mut::<[u8;0]>() as *mut [u8] ,
buf: ptr::null_mut::<[AlignType;0]>() as *mut [AlignType] ,
})
}
}

impl<'buf> Secp256k1<SignOnlyPreallocated<'buf>> {
/// Creates a new Secp256k1 context that can only be used for signing
pub fn preallocated_signing_only(buf: &'buf mut [u8]) -> Result<Secp256k1<SignOnlyPreallocated<'buf>>, Error> {
pub fn preallocated_signing_only(buf: &'buf mut [AlignType]) -> Result<Secp256k1<SignOnlyPreallocated<'buf>>, Error> {
Secp256k1::preallocated_gen_new(buf)
}

Expand All @@ -270,14 +270,14 @@ impl<'buf> Secp256k1<SignOnlyPreallocated<'buf>> {
ManuallyDrop::new(Secp256k1 {
ctx: raw_ctx,
phantom: PhantomData,
buf: ptr::null_mut::<[u8;0]>() as *mut [u8] ,
buf: ptr::null_mut::<[AlignType;0]>() as *mut [AlignType] ,
})
}
}

impl<'buf> Secp256k1<VerifyOnlyPreallocated<'buf>> {
/// Creates a new Secp256k1 context that can only be used for verification
pub fn preallocated_verification_only(buf: &'buf mut [u8]) -> Result<Secp256k1<VerifyOnlyPreallocated<'buf>>, Error> {
pub fn preallocated_verification_only(buf: &'buf mut [AlignType]) -> Result<Secp256k1<VerifyOnlyPreallocated<'buf>>, Error> {
Secp256k1::preallocated_gen_new(buf)
}

Expand All @@ -302,7 +302,7 @@ impl<'buf> Secp256k1<VerifyOnlyPreallocated<'buf>> {
ManuallyDrop::new(Secp256k1 {
ctx: raw_ctx,
phantom: PhantomData,
buf: ptr::null_mut::<[u8;0]>() as *mut [u8] ,
buf: ptr::null_mut::<[AlignType;0]>() as *mut [AlignType] ,
})
}
}
16 changes: 13 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,9 @@ pub use secp256k1_sys as ffi;
#[cfg(any(test, feature = "rand"))] use rand::Rng;
#[cfg(any(test, feature = "std"))] extern crate core;

use core::{fmt, ptr, str};
use core::{fmt, mem, ptr, str};

pub use ffi::AlignType;

#[macro_use]
mod macros;
Expand Down Expand Up @@ -530,7 +532,7 @@ impl std::error::Error for Error {
pub struct Secp256k1<C: Context> {
ctx: *mut ffi::Context,
phantom: PhantomData<C>,
buf: *mut [u8],
buf: *mut [AlignType],
}

// The underlying secp context does not contain any references to memory it does not own
Expand Down Expand Up @@ -602,7 +604,15 @@ impl<C: Context> Secp256k1<C> {

/// Returns the required memory for a preallocated context buffer in a generic manner(sign/verify/all)
pub fn preallocate_size_gen() -> usize {
unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) }
assert!(mem::align_of::<AlignType>() >= mem::align_of::<u8>());
assert!(mem::align_of::<AlignType>() >= mem::align_of::<usize>());
assert!(mem::size_of::<AlignType>() >= mem::size_of::<usize>());
assert!(mem::align_of::<AlignType>() >= mem::align_of::<&AlignType>());

let bytes_size = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) };
let word_size = mem::size_of::<AlignType>();
let n_words = (bytes_size + word_size - 1) / word_size;
n_words
}

/// (Re)randomizes the Secp256k1 context for cheap sidechannel resistance;
Expand Down

0 comments on commit 84ebaa0

Please sign in to comment.