forked from zig-bitcoin/coconut
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coconut_zig.txt
516 lines (368 loc) · 16.9 KB
/
coconut_zig.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
// src/benchmarks.zig
const std = @import("std");
const bdhke = @import("bdhke.zig");
const secp256k1 = @import("secp256k1.zig");
const Scalar = secp256k1.Scalar;
const PublicKey = secp256k1.PublicKey;
const SecretKey = secp256k1.SecretKey;
const zul = @import("zul");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
try benchmarkZul(allocator);
}
const Context = struct {
secret_msg: []const u8 = "test_message",
dhke: bdhke.Dhke,
bf: SecretKey,
a: SecretKey,
};
fn hashToCurve(ctx: Context, _: std.mem.Allocator, _: *std.time.Timer) !void {
_ = try bdhke.Dhke.hashToCurve(ctx.secret_msg);
}
fn step1Alice(ctx: Context, _: std.mem.Allocator, _: *std.time.Timer) !void {
_ = try ctx.dhke.step1Alice(ctx.secret_msg, ctx.bf);
}
fn step2Bob(ctx: Context, _: std.mem.Allocator, t: *std.time.Timer) !void {
const B_ = try ctx.dhke.step1Alice(ctx.secret_msg, ctx.bf);
t.reset();
_ = try ctx.dhke.step2Bob(B_, ctx.a);
}
fn step3Alice(ctx: Context, _: std.mem.Allocator, t: *std.time.Timer) !void {
const B_ = try ctx.dhke.step1Alice(ctx.secret_msg, ctx.bf);
const C_ = try ctx.dhke.step2Bob(B_, ctx.a);
const pub_key = ctx.a.publicKey(ctx.dhke.secp);
t.reset();
_ = try ctx.dhke.step3Alice(C_, ctx.bf, pub_key);
}
fn verify(ctx: Context, _: std.mem.Allocator, t: *std.time.Timer) !void {
const B_ = try ctx.dhke.step1Alice(ctx.secret_msg, ctx.bf);
const C_ = try ctx.dhke.step2Bob(B_, ctx.a);
const pub_key = ctx.a.publicKey(ctx.dhke.secp);
const C = try ctx.dhke.step3Alice(C_, ctx.bf, pub_key);
t.reset();
_ = try ctx.dhke.verify(ctx.a, C, ctx.secret_msg);
}
fn end2End(ctx: Context, _: std.mem.Allocator, _: *std.time.Timer) !void {
const b_ = try ctx.dhke
.step1Alice(ctx.secret_msg, ctx.bf);
const c_ = try ctx.dhke.step2Bob(b_, ctx.a);
const c = try ctx.dhke
.step3Alice(c_, ctx.bf, ctx.a.publicKey(ctx.dhke.secp));
_ = try ctx.dhke.verify(ctx.a, c, ctx.secret_msg);
}
fn benchmarkZul(allocator: std.mem.Allocator) !void {
const a_bytes: [32]u8 = [_]u8{1} ** 32;
const r_bytes: [32]u8 = [_]u8{1} ** 32;
const ctx = Context{
.dhke = try bdhke.Dhke.init(allocator),
.a = try SecretKey.fromSlice(&a_bytes),
.bf = try SecretKey.fromSlice(&r_bytes),
};
defer ctx.dhke.deinit();
(try zul.benchmark.runC(ctx, hashToCurve, .{})).print("hashToCurve");
(try zul.benchmark.runC(ctx, step1Alice, .{})).print("step1Alice");
(try zul.benchmark.runC(ctx, step2Bob, .{})).print("step2Bob");
(try zul.benchmark.runC(ctx, step3Alice, .{})).print("step3Alice");
(try zul.benchmark.runC(ctx, verify, .{})).print("verify");
(try zul.benchmark.runC(ctx, end2End, .{})).print("e2e");
}
// src/secp256k1.zig
const std = @import("std");
const secp256k1 = @cImport({
@cInclude("secp256k1.h");
@cInclude("secp256k1_recovery.h");
@cInclude("secp256k1_preallocated.h");
});
const crypto = std.crypto;
pub const Secp256k1 = struct {
ctx: ?*secp256k1.struct_secp256k1_context_struct,
ptr: []align(16) u8,
pub fn deinit(self: @This(), allocator: std.mem.Allocator) void {
allocator.free(@as([]align(16) u8, @ptrCast(self.ptr)));
}
pub fn genNew(allocator: std.mem.Allocator) !@This() {
// verify and sign only
const size: usize = secp256k1.secp256k1_context_preallocated_size(257 | 513);
const ptr = try allocator.alignedAlloc(u8, 16, size);
const ctx =
secp256k1.secp256k1_context_preallocated_create(ptr.ptr, 257 | 513);
var seed: [32]u8 = undefined;
var rng = std.Random.DefaultPrng.init(@intCast(std.time.timestamp()));
rng.fill(&seed);
const res = secp256k1.secp256k1_context_randomize(ctx, &seed);
std.debug.assert(res == 1);
return .{
.ctx = ctx,
.ptr = ptr,
};
}
};
pub const Scalar = struct {
data: [32]u8,
pub inline fn fromSecretKey(sk: SecretKey) @This() {
return .{ .data = sk.secretBytes() };
}
};
pub const PublicKey = struct {
pk: secp256k1.secp256k1_pubkey,
pub fn fromSlice(c: []const u8) !@This() {
var pk: secp256k1.secp256k1_pubkey = .{};
if (secp256k1.secp256k1_ec_pubkey_parse(secp256k1.secp256k1_context_no_precomp, &pk, c.ptr, c.len) == 1) {
return .{ .pk = pk };
}
return error.InvalidPublicKey;
}
pub fn fromSecretKey(secp_: Secp256k1, sk: SecretKey) PublicKey {
var pk: secp256k1.secp256k1_pubkey = .{};
const res = secp256k1.secp256k1_ec_pubkey_create(secp_.ctx, &pk, &sk.data);
std.debug.assert(res == 1);
return PublicKey{ .pk = pk };
}
/// Serializes the key as a byte-encoded pair of values. In compressed form the y-coordinate is
/// represented by only a single bit, as x determines it up to one bit.
pub fn serialize(self: PublicKey) [33]u8 {
var ret = [_]u8{0} ** 33;
self.serializeInternal(&ret, 258);
return ret;
}
inline fn serializeInternal(self: PublicKey, ret: []u8, flag: u32) void {
var ret_len = ret.len;
const res = secp256k1.secp256k1_ec_pubkey_serialize(secp256k1.secp256k1_context_no_precomp, ret.ptr, &ret_len, &self.pk, flag);
std.debug.assert(res == 1);
std.debug.assert(ret_len == ret.len);
}
pub fn negate(self: @This(), secp: *const Secp256k1) PublicKey {
var pk = self.pk;
const res = secp256k1.secp256k1_ec_pubkey_negate(secp.ctx, &pk);
std.debug.assert(res == 1);
return .{ .pk = pk };
}
pub fn mulTweak(self: @This(), secp: *const Secp256k1, other: Scalar) !PublicKey {
var pk = self.pk;
if (secp256k1.secp256k1_ec_pubkey_tweak_mul(secp.ctx, &pk, @ptrCast(&other.data)) == 1) return .{ .pk = pk };
return error.InvalidTweak;
}
pub fn combine(self: @This(), other: PublicKey) !PublicKey {
return PublicKey.combineKeys(&.{
&self, &other,
});
}
pub fn combineKeys(keys: []const *const PublicKey) !PublicKey {
if (keys.len == 0) return error.InvalidPublicKeySum;
var ret = PublicKey{
.pk = .{},
};
if (secp256k1.secp256k1_ec_pubkey_combine(secp256k1.secp256k1_context_no_precomp, &ret.pk, @ptrCast(keys.ptr), keys.len) == 1) return ret;
return error.InvalidPublicKeySum;
}
};
pub const SecretKey = struct {
data: [32]u8,
pub fn fromSlice(data: []const u8) !@This() {
if (data.len != 32) {
return error.InvalidSecretKey;
}
if (secp256k1.secp256k1_ec_seckey_verify(
secp256k1.secp256k1_context_no_precomp,
@ptrCast(data.ptr),
) == 0) return error.InvalidSecretKey;
return .{
.data = data[0..32].*,
};
}
pub inline fn publicKey(self: @This(), secp: Secp256k1) PublicKey {
return PublicKey.fromSecretKey(secp, self);
}
pub inline fn secretBytes(self: @This()) [32]u8 {
return self.data;
}
};
// src/main.zig
const std = @import("std");
const bdhke = @import("bdhke.zig");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
try bdhke.testBDHKE(allocator);
}
// src/bdhke.zig
const std = @import("std");
const secp256k1 = @import("secp256k1.zig");
const crypto = std.crypto;
pub const Dhke = struct {
const Self = @This();
secp: secp256k1.Secp256k1,
allocator: std.mem.Allocator,
pub fn init(allocator: std.mem.Allocator) !Self {
return .{
.secp = try secp256k1.Secp256k1.genNew(allocator),
.allocator = allocator,
};
}
pub fn deinit(self: Self) void {
self.secp.deinit(self.allocator);
}
pub fn hashToCurve(message: []const u8) !secp256k1.PublicKey {
const domain_separator = "Secp256k1_HashToCurve_Cashu_";
var hasher = crypto.hash.sha2.Sha256.init(.{});
hasher.update(domain_separator);
hasher.update(message);
const msg_to_hash = hasher.finalResult();
var buf: [33]u8 = undefined;
buf[0] = 0x02;
var counter_buf: [4]u8 = undefined;
const till = comptime try std.math.powi(u32, 2, 16);
var counter: u32 = 0;
while (counter < till) : (counter += 1) {
hasher = crypto.hash.sha2.Sha256.init(.{});
hasher.update(&msg_to_hash);
std.mem.writeInt(u32, &counter_buf, counter, .little);
hasher.update(&counter_buf);
hasher.final(buf[1..]);
const pk = secp256k1.PublicKey.fromSlice(&buf) catch continue;
return pk;
}
return error.NoValidPointFound;
}
pub fn step1Alice(self: Self, sec_msg: []const u8, blinding_factor: secp256k1.SecretKey) !secp256k1.PublicKey {
const y = try Self.hashToCurve(sec_msg);
const b = try y.combine(secp256k1.PublicKey.fromSecretKey(self.secp, blinding_factor));
return b;
}
pub fn step2Bob(self: Self, b: secp256k1.PublicKey, a: secp256k1.SecretKey) !secp256k1.PublicKey {
return try b.mulTweak(&self.secp, secp256k1.Scalar.fromSecretKey(a));
}
pub fn step3Alice(self: Self, c_: secp256k1.PublicKey, r: secp256k1.SecretKey, a: secp256k1.PublicKey) !secp256k1.PublicKey {
return c_.combine(
(try a
.mulTweak(&self.secp, secp256k1.Scalar.fromSecretKey(r)))
.negate(&self.secp),
) catch return error.Secp256k1Error;
}
pub fn verify(self: Self, a: secp256k1.SecretKey, c: secp256k1.PublicKey, secret_msg: []const u8) !bool {
const y = try Self.hashToCurve(secret_msg);
const res = try y.mulTweak(&self.secp, secp256k1.Scalar.fromSecretKey(a));
return std.meta.eql(c.pk, res.pk);
}
};
/// End-to-end test scenario for BDHKE
pub fn testBDHKE(allocator: std.mem.Allocator) !void {
// Initialize with deterministic values
const secret_msg = "test_message";
var a_bytes: [32]u8 = [_]u8{0} ** 31 ++ [_]u8{1};
var r_bytes: [32]u8 = [_]u8{0} ** 31 ++ [_]u8{1};
const dhke = try Dhke.init(allocator);
defer dhke.deinit();
const a = try secp256k1.SecretKey.fromSlice(&a_bytes);
const bf = try secp256k1.SecretKey.fromSlice(&r_bytes);
std.debug.print("Starting BDHKE test\n", .{});
std.debug.print("Secret message: {s}\n", .{secret_msg});
std.debug.print("Alice's private key (a): {s}\n", .{std.fmt.fmtSliceHexLower(&a_bytes)});
std.debug.print("Alice's public key (A): {s}\n", .{std.fmt.fmtSliceHexLower(&a.publicKey(dhke.secp).serialize())});
// Deterministic blinding factor
std.debug.print("r private key: {s}\n", .{std.fmt.fmtSliceHexLower(&r_bytes)});
std.debug.print("Blinding factor (r): {s}\n", .{std.fmt.fmtSliceHexLower(&bf.publicKey(dhke.secp).serialize())});
// Step 1: Alice blinds the message
const B_ = try dhke.step1Alice(secret_msg, bf);
std.debug.print("Blinded message (B_): {s}\n", .{std.fmt.fmtSliceHexLower(&B_.serialize())});
std.debug.print("Step 1 complete: Message blinded\n", .{});
// Step 2: Bob signs the blinded message
const C_ = try dhke.step2Bob(B_, a);
std.debug.print("Blinded signature (C_): {s}\n", .{std.fmt.fmtSliceHexLower(&C_.serialize())});
std.debug.print("Step 2 complete: Blinded message signed\n", .{});
// Step 3: Alice unblinds the signature
const C = try dhke.step3Alice(C_, bf, a.publicKey(dhke.secp));
std.debug.print("Unblinded signature (C): {s}\n", .{std.fmt.fmtSliceHexLower(&C.serialize())});
std.debug.print("Step 3 complete: Signature unblinded\n", .{});
// Final verification
const final_verification = try dhke.verify(a, C, secret_msg);
if (!final_verification) {
return error.VerificationFailed;
}
std.debug.print("Final verification successful\n", .{});
std.debug.print("BDHKE test completed successfully\n", .{});
}
test "testBdhke" {
const secret_msg = "test_message";
const a = try secp256k1.SecretKey.fromSlice(&[_]u8{1} ** 32);
const blinding_factor = try secp256k1.SecretKey.fromSlice(&[_]u8{1} ** 32);
const dhke = try Dhke.init(std.testing.allocator);
defer dhke.deinit();
const _b = try dhke.step1Alice(secret_msg, blinding_factor);
const _c = try dhke.step2Bob(_b, a);
const step3_c = try dhke.step3Alice(_c, blinding_factor, a.publicKey(dhke.secp));
const res = try dhke.verify(a, step3_c, secret_msg);
try std.testing.expect(res);
}
test "test_hash_to_curve_zero" {
var buffer: [64]u8 = undefined;
const hex = "0000000000000000000000000000000000000000000000000000000000000000";
const expected_result = "024cce997d3b518f739663b757deaec95bcd9473c30a14ac2fd04023a739d1a725";
const res = try Dhke.hashToCurve(try std.fmt.hexToBytes(&buffer, hex));
try std.testing.expectEqualSlices(u8, try std.fmt.hexToBytes(&buffer, expected_result), &res.serialize());
}
test "test_hash_to_curve_one" {
var buffer: [64]u8 = undefined;
const hex = "0000000000000000000000000000000000000000000000000000000000000001";
const expected_result = "022e7158e11c9506f1aa4248bf531298daa7febd6194f003edcd9b93ade6253acf";
const res = try Dhke.hashToCurve(try std.fmt.hexToBytes(&buffer, hex));
try std.testing.expectEqualSlices(u8, try std.fmt.hexToBytes(&buffer, expected_result), &res.serialize());
}
test "test_hash_to_curve_two" {
var buffer: [64]u8 = undefined;
const hex = "0000000000000000000000000000000000000000000000000000000000000002";
const expected_result = "026cdbe15362df59cd1dd3c9c11de8aedac2106eca69236ecd9fbe117af897be4f";
const res = try Dhke.hashToCurve(try std.fmt.hexToBytes(&buffer, hex));
try std.testing.expectEqualSlices(u8, try std.fmt.hexToBytes(&buffer, expected_result), &res.serialize());
}
test "test_step1_alice" {
const dhke = try Dhke.init(std.testing.allocator);
defer dhke.deinit();
var hex_buffer: [64]u8 = undefined;
const bf = try secp256k1.SecretKey.fromSlice(try std.fmt.hexToBytes(&hex_buffer, "0000000000000000000000000000000000000000000000000000000000000001"));
const pub_key = try dhke.step1Alice("test_message", bf);
try std.testing.expectEqualSlices(u8, try std.fmt.hexToBytes(&hex_buffer, "025cc16fe33b953e2ace39653efb3e7a7049711ae1d8a2f7a9108753f1cdea742b"), &pub_key.serialize());
}
test "test_step2_bob" {
const dhke = try Dhke.init(std.testing.allocator);
defer dhke.deinit();
var hex_buffer: [64]u8 = undefined;
const bf = try secp256k1.SecretKey.fromSlice(try std.fmt.hexToBytes(&hex_buffer, "0000000000000000000000000000000000000000000000000000000000000001"));
const pub_key = try dhke.step1Alice("test_message", bf);
const a = try secp256k1.SecretKey.fromSlice(try std.fmt.hexToBytes(&hex_buffer, "0000000000000000000000000000000000000000000000000000000000000001"));
const c = try dhke.step2Bob(pub_key, a);
try std.testing.expectEqualSlices(u8, try std.fmt.hexToBytes(&hex_buffer, "025cc16fe33b953e2ace39653efb3e7a7049711ae1d8a2f7a9108753f1cdea742b"), &c.serialize());
}
test "test_step3_alice" {
const dhke = try Dhke.init(std.testing.allocator);
defer dhke.deinit();
var hex_buffer: [64]u8 = undefined;
const c_ = try secp256k1.PublicKey.fromSlice(try std.fmt.hexToBytes(&hex_buffer, "02a9acc1e48c25eeeb9289b5031cc57da9fe72f3fe2861d264bdc074209b107ba2"));
const bf = try secp256k1.SecretKey.fromSlice(try std.fmt.hexToBytes(&hex_buffer, "0000000000000000000000000000000000000000000000000000000000000001"));
const a = try secp256k1.PublicKey.fromSlice(try std.fmt.hexToBytes(&hex_buffer, "020000000000000000000000000000000000000000000000000000000000000001"));
const result = try dhke.step3Alice(c_, bf, a);
try std.testing.expectEqualSlices(u8, try std.fmt.hexToBytes(&hex_buffer, "03c724d7e6a5443b39ac8acf11f40420adc4f99a02e7cc1b57703d9391f6d129cd"), &result.serialize());
}
test "test_verify" {
const dhke = try Dhke.init(std.testing.allocator);
defer dhke.deinit();
var hex_buffer: [64]u8 = undefined;
// Generate Alice's private key and public key
const a = try secp256k1.SecretKey.fromSlice(try std.fmt.hexToBytes(&hex_buffer, "0000000000000000000000000000000000000000000000000000000000000001"));
const A = a.publicKey(dhke.secp);
const bf = try secp256k1.SecretKey.fromSlice(try std.fmt.hexToBytes(&hex_buffer, "0000000000000000000000000000000000000000000000000000000000000002"));
// Generate a shared secret
const secret_msg = "test";
const B_ = try dhke.step1Alice(secret_msg, bf);
const C_ = try dhke.step2Bob(B_, a);
const C = try dhke.step3Alice(C_, bf, A);
try std.testing.expect(try dhke.verify(a, C, secret_msg));
try std.testing.expect(!try dhke.verify(a, try C.combine(C), secret_msg));
try std.testing.expect(!try dhke.verify(a, A, secret_msg));
}
// src/lib.zig