From d9841a7ac634472c1a9105f81f8e7b55e4bd1a4a Mon Sep 17 00:00:00 2001 From: Anthony Towns Date: Fri, 22 Sep 2023 09:40:45 -0400 Subject: [PATCH] Add make_secure_unique helper Co-authored-by: Pieter Wuille --- src/support/allocators/secure.h | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/support/allocators/secure.h b/src/support/allocators/secure.h index 558f835f11..4395567722 100644 --- a/src/support/allocators/secure.h +++ b/src/support/allocators/secure.h @@ -57,4 +57,28 @@ struct secure_allocator { // TODO: Consider finding a way to make incoming RPC request.params[i] mlock()ed as well typedef std::basic_string, secure_allocator > SecureString; +template +struct SecureUniqueDeleter { + void operator()(T* t) noexcept { + secure_allocator().deallocate(t, 1); + } +}; + +template +using secure_unique_ptr = std::unique_ptr>; + +template +secure_unique_ptr make_secure_unique(Args&&... as) +{ + T* p = secure_allocator().allocate(1); + + // initialize in place, and return as secure_unique_ptr + try { + return secure_unique_ptr(new (p) T(std::forward(as)...)); + } catch (...) { + secure_allocator().deallocate(p, 1); + throw; + } +} + #endif // BITCOIN_SUPPORT_ALLOCATORS_SECURE_H