purify
C++ Purify implementation with native circuit and BPP support
Loading...
Searching...
No Matches
c_api.cpp
Go to the documentation of this file.
1// Copyright (c) 2026 Judica, Inc.
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or https://opensource.org/license/mit/.
4
9
10#include "purify.h"
11
12#include <algorithm>
13#include <array>
14#include <cstdint>
15#include <span>
16#include <string_view>
17
18#include "purify/curve.hpp"
19#include "purify/error.hpp"
20#include "purify/secret.hpp"
21#include "secure_cleanup.hpp"
22#include "core.h"
23#include "error_bridge.hpp"
24
26
28
29bool ranges_overlap(const void* lhs, std::size_t lhs_size, const void* rhs, std::size_t rhs_size) noexcept {
30 if (lhs_size == 0 || rhs_size == 0 || lhs == nullptr || rhs == nullptr) {
31 return false;
32 }
33
34 const auto lhs_addr = reinterpret_cast<std::uintptr_t>(lhs);
35 const auto rhs_addr = reinterpret_cast<std::uintptr_t>(rhs);
36 if (lhs_addr <= rhs_addr) {
37 return (rhs_addr - lhs_addr) < lhs_size;
38 }
39 return (lhs_addr - rhs_addr) < rhs_size;
40}
41
42Bytes copy_bytes(const unsigned char* data, std::size_t size) {
43 if (size == 0) {
44 return {};
45 }
46 return Bytes(data, data + size);
47}
48
50public:
51 explicit SecretKeyInput(const unsigned char* secret_key) noexcept
52 : present_(secret_key != nullptr) {
53 if (present_) {
54 std::copy_n(secret_key, value_.size(), value_.begin());
55 }
56 }
57
60
62 detail::secure_clear_bytes(value_.data(), value_.size());
63 }
64
65 [[nodiscard]] const unsigned char* data() const noexcept {
66 return present_ ? value_.data() : nullptr;
67 }
68
69private:
70 std::array<unsigned char, PURIFY_SECRET_KEY_BYTES> value_{};
71 bool present_{false};
72};
73
75 if (out == nullptr) {
76 return;
77 }
78 detail::secure_clear_bytes(out->secret_key, sizeof(out->secret_key));
79 std::fill(std::begin(out->public_key), std::end(out->public_key), 0);
80}
81
83 if (out == nullptr) {
84 return;
85 }
86 detail::secure_clear_bytes(out->secret_key, sizeof(out->secret_key));
87 std::fill(std::begin(out->xonly_public_key), std::end(out->xonly_public_key), 0);
88}
89
91 static const UInt256 value =
92 UInt256::from_hex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");
93 return value;
94}
95
97 static const UInt256 value = [] {
100 return out;
101 }();
102 return value;
103}
104
105Bytes tagged_message(std::string_view prefix, const Bytes& message) {
106 Bytes out;
107 out.reserve(prefix.size() + message.size());
108 out.insert(out.end(), prefix.begin(), prefix.end());
109 out.insert(out.end(), message.begin(), message.end());
110 return out;
111}
112
113Result<UInt512> parse_secret_key(const unsigned char* secret_key) {
114 if (secret_key == nullptr) {
115 return unexpected_error(ErrorCode::MissingValue, "parse_secret_key:null_secret_key");
116 }
117 const purify_error_code code = purify_validate_secret_key(secret_key);
118 if (code != PURIFY_ERROR_OK) {
120 "parse_secret_key:purify_validate_secret_key");
121 }
123 WipeOnDestruction packed_guard(packed);
124 return packed;
125}
126
127Result<UInt512> parse_public_key(const unsigned char* public_key) {
128 if (public_key == nullptr) {
129 return unexpected_error(ErrorCode::MissingValue, "parse_public_key:null_public_key");
130 }
131 const purify_error_code code = purify_validate_public_key(public_key);
132 if (code != PURIFY_ERROR_OK) {
134 "parse_public_key:purify_validate_public_key");
135 }
137 return packed;
138}
139
140void write_uint512(const UInt512& value, unsigned char* out) {
141 const std::array<unsigned char, PURIFY_PUBLIC_KEY_BYTES> bytes = value.to_bytes_be();
142 std::copy(bytes.begin(), bytes.end(), out);
143}
144
145void write_field_element(const FieldElement& value, unsigned char* out) {
146 std::array<unsigned char, PURIFY_FIELD_ELEMENT_BYTES> bytes =
147 value.to_bytes_be();
148 WipeOnDestruction bytes_guard(bytes);
149 std::copy(bytes.begin(), bytes.end(), out);
150}
151
154 if (!unpacked.has_value()) {
155 return unexpected_error(
156 unpacked.error(),
157 "derive_public_key_from_secret:unpack_secret");
158 }
159 WipeOnDestruction unpacked_guard(*unpacked);
160 PURIFY_ASSIGN_OR_RETURN(const auto& p1, curve1().mul_secret_affine(generator1(), unpacked->first),
161 "derive_public_key_from_secret:mul_secret_affine_p1");
162 PURIFY_ASSIGN_OR_RETURN(const auto& p2, curve2().mul_secret_affine(generator2(), unpacked->second),
163 "derive_public_key_from_secret:mul_secret_affine_p2");
164 return pack_public(p1.x.to_uint256(), p2.x.to_uint256());
165}
166
167} // namespace purify::capi_detail
168
169extern "C" {
170
172 purify_error_code status;
173 if (out == nullptr) {
175 }
178 if (status != PURIFY_ERROR_OK) {
180 return status;
181 }
182 purify::Result<purify::UInt512> packed_secret =
184 if (!packed_secret.has_value()) {
187 }
188 purify::capi_detail::WipeOnDestruction packed_secret_guard(
189 *packed_secret);
192 if (!public_key.has_value()) {
195 }
197 return PURIFY_ERROR_OK;
198}
199
201 const unsigned char* seed,
202 size_t seed_len) {
203 purify_error_code status;
204 const unsigned char* seed_input = seed;
205 purify::Bytes seed_copy;
206 if (out == nullptr) {
208 }
209 if (purify::capi_detail::ranges_overlap(out, sizeof(*out), seed, seed_len)) {
210 seed_copy = purify::capi_detail::copy_bytes(seed, seed_len);
211 seed_input = seed_copy.data();
212 }
214 status = purify_core_seed_secret_key(out->secret_key, seed_input, seed_len);
215 if (status != PURIFY_ERROR_OK) {
217 return status;
218 }
219 purify::Result<purify::UInt512> packed_secret =
221 if (!packed_secret.has_value()) {
224 }
225 purify::capi_detail::WipeOnDestruction packed_secret_guard(
226 *packed_secret);
229 if (!public_key.has_value()) {
232 }
234 return PURIFY_ERROR_OK;
235}
236
238 const unsigned char secret_key[PURIFY_SECRET_KEY_BYTES]) {
239 if (out_public_key == nullptr) {
241 }
242 const purify::capi_detail::SecretKeyInput secret_input(secret_key);
243 std::fill(out_public_key, out_public_key + PURIFY_PUBLIC_KEY_BYTES, 0);
244
245 purify::Result<purify::UInt512> packed_secret =
247 if (!packed_secret.has_value()) {
249 }
250 purify::capi_detail::WipeOnDestruction packed_secret_guard(
251 *packed_secret);
252
254 if (!public_key.has_value()) {
256 }
257
258 purify::capi_detail::write_uint512(*public_key, out_public_key);
259 return PURIFY_ERROR_OK;
260}
261
263 const unsigned char secret_key[PURIFY_SECRET_KEY_BYTES],
264 purify_secp_context* secp_context) {
265 if (out == nullptr) {
267 }
268 const purify::capi_detail::SecretKeyInput secret_input(secret_key);
270
271 purify::Result<purify::UInt512> packed_secret =
273 if (!packed_secret.has_value()) {
275 }
276
277 static const purify::TaggedHash kBip340KeyGenTag("Purify/BIP340/KeyGen");
278 std::array<unsigned char, PURIFY_SECRET_KEY_BYTES> packed_secret_bytes = packed_secret->to_bytes_be();
279 purify::Bytes ikm(packed_secret_bytes.begin(), packed_secret_bytes.end());
280#if PURIFY_USE_LEGACY_FIELD_HASHES
281 std::optional<purify::UInt256> scalar =
283 purify::bytes_from_ascii("Purify/BIP340/KeyGen"));
284#else
285 std::optional<purify::UInt256> scalar = purify::tagged_hash_to_int<4>(
286 std::span<const unsigned char>(ikm.data(), ikm.size()), purify::capi_detail::secp256k1_order_minus_one(),
287 kBip340KeyGenTag);
288#endif
289 purify::detail::secure_clear_bytes(ikm.data(), ikm.size());
290 purify::detail::secure_clear_bytes(packed_secret_bytes.data(), packed_secret_bytes.size());
291 if (!scalar.has_value()) {
293 }
294 scalar->add_small(1);
295
296 const std::array<unsigned char, PURIFY_BIP340_SECRET_KEY_BYTES> scalar_bytes = scalar->to_bytes_be();
297 std::copy(scalar_bytes.begin(), scalar_bytes.end(), out->secret_key);
298 if (secp_context == nullptr) {
301 }
302 if (purify_bip340_key_from_seckey(secp_context, out->secret_key, out->xonly_public_key) == 0) {
305 }
306 return PURIFY_ERROR_OK;
307}
308
310 const unsigned char secret_key[PURIFY_SECRET_KEY_BYTES],
311 const unsigned char* message,
312 size_t message_len) {
313 if (out_field_element == nullptr) {
315 }
316 if (message_len != 0 && message == nullptr) {
317 std::fill(out_field_element,
318 out_field_element + PURIFY_FIELD_ELEMENT_BYTES, 0);
320 }
321 const purify::capi_detail::SecretKeyInput secret_input(secret_key);
322 const purify::Bytes message_bytes =
323 purify::capi_detail::copy_bytes(message, message_len);
324 std::fill(out_field_element,
325 out_field_element + PURIFY_FIELD_ELEMENT_BYTES, 0);
326
327 purify::Result<purify::UInt512> packed_secret =
329 if (!packed_secret.has_value()) {
331 }
332 purify::capi_detail::WipeOnDestruction packed_secret_guard(
333 *packed_secret);
334
336 if (!unpacked.has_value()) {
338 }
339 purify::capi_detail::WipeOnDestruction unpacked_guard(*unpacked);
340
343 if (!m1.has_value()) {
345 }
348 if (!m2.has_value()) {
350 }
351
353 purify::curve1().mul_secret_affine(*m1, unpacked->first);
354 if (!q1.has_value()) {
356 }
359 purify::curve2().mul_secret_affine(*m2, unpacked->second);
360 if (!q2.has_value()) {
362 }
364
365 purify::FieldElement output = purify::combine(q1->x, q2->x);
366 purify::capi_detail::WipeOnDestruction output_guard(output);
367 purify::capi_detail::write_field_element(output, out_field_element);
368 return PURIFY_ERROR_OK;
369}
370
371} // extern "C"
purify_error_code purify_generate_key(purify_generated_key *out)
Generates one random Purify keypair.
Definition c_api.cpp:171
purify_error_code purify_generate_key_from_seed(purify_generated_key *out, const unsigned char *seed, size_t seed_len)
Deterministically derives one Purify keypair from seed material.
Definition c_api.cpp:200
purify_error_code purify_eval(unsigned char out_field_element[PURIFY_FIELD_ELEMENT_BYTES], const unsigned char secret_key[PURIFY_SECRET_KEY_BYTES], const unsigned char *message, size_t message_len)
Evaluates the Purify PRF for one packed secret and message.
Definition c_api.cpp:309
purify_error_code purify_derive_public_key(unsigned char out_public_key[PURIFY_PUBLIC_KEY_BYTES], const unsigned char secret_key[PURIFY_SECRET_KEY_BYTES])
Derives the packed public key corresponding to one packed Purify secret.
Definition c_api.cpp:237
purify_error_code purify_derive_bip340_key(purify_bip340_key *out, const unsigned char secret_key[PURIFY_SECRET_KEY_BYTES], purify_secp_context *secp_context)
Derives one canonical BIP340 keypair from one packed Purify secret.
Definition c_api.cpp:262
Result< AffinePoint > mul_secret_affine(const JacobianPoint &point, const UInt256 &scalar) const
Multiplies a public point by a secret scalar using exception-free complete formulas.
Definition curve.cpp:156
bool has_value() const noexcept
Definition expected.hpp:170
Field element modulo the backend scalar field used by this implementation.
Definition numeric.hpp:834
std::array< unsigned char, 32 > to_bytes_be() const
Serializes the field element in big-endian form.
Definition numeric.cpp:84
Reusable BIP340-style tagged SHA-256 helper.
Definition curve.hpp:111
SecretKeyInput(const unsigned char *secret_key) noexcept
Definition c_api.cpp:51
SecretKeyInput(const SecretKeyInput &)=delete
SecretKeyInput & operator=(const SecretKeyInput &)=delete
const unsigned char * data() const noexcept
Definition c_api.cpp:65
purify_error_code purify_core_sample_secret_key(unsigned char out_secret_key[PURIFY_SECRET_KEY_BYTES])
Definition core.c:321
purify_error_code purify_core_seed_secret_key(unsigned char out_secret_key[PURIFY_SECRET_KEY_BYTES], const unsigned char *seed, size_t seed_len)
Definition core.c:340
Elliptic-curve helpers, fixed parameters, and hash-to-curve utilities for Purify.
Library-level error taxonomy used to classify Purify failures.
#define PURIFY_ASSIGN_OR_RETURN(lhs, expr, context)
Evaluates an expected-like expression, binds the value to lhs, and propagates errors.
Definition error.hpp:338
void write_field_element(const FieldElement &value, unsigned char *out)
Definition c_api.cpp:145
void clear_generated_key(purify_generated_key *out) noexcept
Definition c_api.cpp:74
const UInt256 & secp256k1_order()
Definition c_api.cpp:90
void clear_bip340_key(purify_bip340_key *out) noexcept
Definition c_api.cpp:82
void write_uint512(const UInt512 &value, unsigned char *out)
Definition c_api.cpp:140
Bytes copy_bytes(const unsigned char *data, std::size_t size)
Definition c_api.cpp:42
bool ranges_overlap(const void *lhs, std::size_t lhs_size, const void *rhs, std::size_t rhs_size) noexcept
Definition c_api.cpp:29
Bytes tagged_message(std::string_view prefix, const Bytes &message)
Definition c_api.cpp:105
Result< UInt512 > parse_public_key(const unsigned char *public_key)
Definition c_api.cpp:127
Result< UInt512 > derive_public_key_from_secret(const UInt512 &secret)
Definition c_api.cpp:152
Result< UInt512 > parse_secret_key(const unsigned char *secret_key)
Definition c_api.cpp:113
const UInt256 & secp256k1_order_minus_one()
Definition c_api.cpp:96
constexpr ErrorCode from_core_error_code(purify_error_code code) noexcept
constexpr purify_error_code to_core_error_code(ErrorCode code) noexcept
void secure_clear_bytes(void *data, std::size_t size) noexcept
Definition secret.hpp:22
constexpr Unexpected< Error > unexpected_error(ErrorCode code, const char *context=nullptr)
Constructs an unexpected Error value from a machine-readable code.
Definition error.hpp:293
BigUInt< 8 > UInt512
512-bit unsigned integer used for private and packed public keys.
Definition numeric.hpp:821
Bytes bytes_from_ascii(std::string_view input)
Encodes an ASCII string as a byte vector.
Definition curve.cpp:168
BigUInt< 4 > UInt256
256-bit unsigned integer used for field elements and curve orders.
Definition numeric.hpp:817
const EllipticCurve & curve1()
Returns the first Purify curve instance.
Definition curve.cpp:261
Expected< T, Error > Result
Expected-returning convenience alias for Purify value-producing APIs.
Definition error.hpp:99
const JacobianPoint & generator1()
Returns the fixed generator for the first curve.
Definition curve.cpp:282
UInt512 pack_public(const UInt256 &x1, const UInt256 &x2)
Packs two x-coordinates into the reference 512-bit public-key encoding.
Definition curve.cpp:399
Result< std::pair< UInt256, UInt256 > > unpack_secret(const UInt512 &z)
Splits a packed private key into its two per-curve secret scalars.
Definition curve.cpp:326
Result< JacobianPoint > hash_to_curve(const Bytes &data, const EllipticCurve &curve)
Hashes arbitrary data onto the supplied curve by rejection sampling x-coordinates.
Definition curve.cpp:273
std::vector< unsigned char > Bytes
Dynamically sized byte string used for messages, serialized witnesses, and proofs.
Definition common.hpp:99
const EllipticCurve & curve2()
Returns the second Purify curve instance.
Definition curve.cpp:266
const JacobianPoint & generator2()
Returns the fixed generator for the second curve.
Definition curve.cpp:293
FieldElement combine(const FieldElement &x1, const FieldElement &x2)
Applies the Purify curve-combination map to two x-coordinates.
Definition curve.cpp:405
std::optional< BigUInt< Words > > tagged_hash_to_int(std::span< const unsigned char > data, const BigUInt< Words > &range, const TaggedHash &tag, std::span< const unsigned char > info={})
Rejection-samples a uniformly distributed integer below range using repeated tagged hashes.
Definition curve.hpp:166
std::optional< BigUInt< Words > > hash_to_int(const Bytes &data, const BigUInt< Words > &range, const Bytes &info={})
Rejection-samples a uniformly distributed integer below range.
Definition curve.hpp:150
Public C core for Purify key validation, key derivation, key generation, and evaluation.
#define PURIFY_SECRET_KEY_BYTES
Definition purify.h:17
#define PURIFY_PUBLIC_KEY_BYTES
Definition purify.h:18
purify_error_code
Machine-readable status code returned by the Purify C core.
Definition purify.h:28
@ PURIFY_ERROR_MISSING_VALUE
Definition purify.h:41
@ PURIFY_ERROR_OK
Definition purify.h:29
@ PURIFY_ERROR_INTERNAL_MISMATCH
Definition purify.h:57
@ PURIFY_ERROR_BACKEND_REJECTED_INPUT
Definition purify.h:53
purify_error_code purify_validate_secret_key(const unsigned char secret_key[PURIFY_SECRET_KEY_BYTES])
Validates one packed Purify secret key.
Definition core.c:313
#define PURIFY_FIELD_ELEMENT_BYTES
Definition purify.h:19
purify_error_code purify_validate_public_key(const unsigned char public_key[PURIFY_PUBLIC_KEY_BYTES])
Validates one packed Purify public key.
Definition core.c:317
int purify_bip340_key_from_seckey(purify_secp_context *context, unsigned char seckey32[32], unsigned char xonly_pubkey32[32])
Canonicalizes a valid secp256k1 secret key for BIP340 and derives its x-only public key.
Secret-owning Purify key material wrappers.
static BigUInt from_bytes_be(const unsigned char *data, std::size_t size)
Definition numeric.hpp:238
void sub_assign(const BigUInt &other)
Subtracts another fixed-width integer in place.
Definition numeric.hpp:486
static BigUInt from_hex(std::string_view hex)
Definition numeric.hpp:283
static BigUInt one()
Definition numeric.hpp:216
std::array< unsigned char, Words *8 > to_bytes_be() const
Serializes the value to a fixed-width big-endian byte array.
Definition numeric.hpp:640
ErrorCode code
Definition error.hpp:76
Canonical BIP340 keypair derived from one packed Purify secret.
Definition purify.h:68
unsigned char secret_key[PURIFY_BIP340_SECRET_KEY_BYTES]
Definition purify.h:69
unsigned char xonly_public_key[PURIFY_BIP340_XONLY_PUBKEY_BYTES]
Definition purify.h:70
Seed/public-key bundle returned by the C core key-generation entry points.
Definition purify.h:62
unsigned char secret_key[PURIFY_SECRET_KEY_BYTES]
Definition purify.h:63
unsigned char public_key[PURIFY_PUBLIC_KEY_BYTES]
Definition purify.h:64