From f961497e69b9062ba63a245735ba83625690df9c Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Fri, 2 Dec 2022 12:58:32 +0000 Subject: [PATCH 1/2] context: introduce unsafe `PreallocatedContext` trait Fixes unsoundness in `preallocated_gen_new` which previously did not properly constrain the lifetime of the buffer used to back the context object. We introduce an unsafe marker trait, and impl it for our existing preallocated-context markers. Annoyingly the trait has to be public even though it should never be used directly, and is only used alongside the sealed `Context` trait, so it is de-facto sealed itself. Fixes #543 --- src/context.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/context.rs b/src/context.rs index d90d33290..aca38a710 100644 --- a/src/context.rs +++ b/src/context.rs @@ -318,7 +318,15 @@ unsafe impl<'buf> Context for AllPreallocated<'buf> { } } -impl<'buf, C: Context + 'buf> Secp256k1 { +/// Trait marking that a particular context object internally points to +/// memory that must outlive `'a` +pub unsafe trait PreallocatedContext<'a> {} + +unsafe impl<'buf> PreallocatedContext<'buf> for AllPreallocated<'buf> {} +unsafe impl<'buf> PreallocatedContext<'buf> for SignOnlyPreallocated<'buf> {} +unsafe impl<'buf> PreallocatedContext<'buf> for VerifyOnlyPreallocated<'buf> {} + +impl<'buf, C: Context + PreallocatedContext<'buf>> Secp256k1 { /// Lets you create a context with a preallocated buffer in a generic manner (sign/verify/all). pub fn preallocated_gen_new(buf: &'buf mut [AlignedType]) -> Result, Error> { #[cfg(target_arch = "wasm32")] From 1e6eb6cb4dd435d062e9d4d16a2218c9033d5c78 Mon Sep 17 00:00:00 2001 From: Andrew Poelstra Date: Fri, 2 Dec 2022 13:23:16 +0000 Subject: [PATCH 2/2] shut clippy up --- src/context.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/context.rs b/src/context.rs index aca38a710..1320cb341 100644 --- a/src/context.rs +++ b/src/context.rs @@ -320,6 +320,11 @@ unsafe impl<'buf> Context for AllPreallocated<'buf> { /// Trait marking that a particular context object internally points to /// memory that must outlive `'a` +/// +/// # Safety +/// This trait is used internally to gate which context markers can safely +/// be used with the `preallocated_gen_new` function. Do not implement it +/// on your own structures. pub unsafe trait PreallocatedContext<'a> {} unsafe impl<'buf> PreallocatedContext<'buf> for AllPreallocated<'buf> {}