1const std = @import("std");
2const crypto = std.crypto;
3const math = std.math;
4const mem = std.mem;
5const meta = std.meta;
6
7const EncodingError = crypto.errors.EncodingError;
8const IdentityElementError = crypto.errors.IdentityElementError;
9const NonCanonicalError = crypto.errors.NonCanonicalError;
10const NotSquareError = crypto.errors.NotSquareError;
11
12/// Group operations over secp256k1.
13pub const Secp256k1 = struct {
14 /// The underlying prime field.
15 pub const Fe = @import("secp256k1/field.zig").Fe;
16 /// Field arithmetic mod the order of the main subgroup.
17 pub const scalar = @import("secp256k1/scalar.zig");
18
19 x: Fe,
20 y: Fe,
21 z: Fe = Fe.one,
22
23 is_base: bool = false,
24
25 /// The secp256k1 base point.
26 pub const basePoint = Secp256k1{
27 .x = Fe.fromInt(55066263022277343669578718895168534326250603453777594175500187360389116729240) catch unreachable,
28 .y = Fe.fromInt(32670510020758816978083085130507043184471273380659243275938904335757337482424) catch unreachable,
29 .z = Fe.one,
30 .is_base = true,
31 };
32
33 /// The secp256k1 neutral element.
34 pub const identityElement = Secp256k1{ .x = Fe.zero, .y = Fe.one, .z = Fe.zero };
35
36 pub const B = Fe.fromInt(7) catch unreachable;
37
38 pub const Endormorphism = struct {
39 const lambda: u256 = 37718080363155996902926221483475020450927657555482586988616620542887997980018;
40 const beta: u256 = 55594575648329892869085402983802832744385952214688224221778511981742606582254;
41
42 const lambda_s = s: {
43 var buf: [32]u8 = undefined;
44 mem.writeInt(u256, &buf, Endormorphism.lambda, .little);
45 break :s buf;
46 };
47
48 pub const SplitScalar = struct {
49 r1: [32]u8,
50 r2: [32]u8,
51 };
52
53 /// Compute r1 and r2 so that k = r1 + r2*lambda (mod L).
54 pub fn splitScalar(s: [32]u8, endian: std.lang.Endian) NonCanonicalError!SplitScalar {
55 const b1_neg_s = comptime s: {
56 var buf: [32]u8 = undefined;
57 mem.writeInt(u256, &buf, 303414439467246543595250775667605759171, .little);
58 break :s buf;
59 };
60 const b2_neg_s = comptime s: {
61 var buf: [32]u8 = undefined;
62 mem.writeInt(u256, &buf, scalar.field_order - 64502973549206556628585045361533709077, .little);
63 break :s buf;
64 };
65 const k = mem.readInt(u256, &s, endian);
66
67 const t1 = math.mulWide(u256, k, 21949224512762693861512883645436906316123769664773102907882521278123970637873);
68 const t2 = math.mulWide(u256, k, 103246583619904461035481197785446227098457807945486720222659797044629401272177);
69
70 const c1 = @as(u128, @truncate(t1 >> 384)) + @as(u1, @truncate(t1 >> 383));
71 const c2 = @as(u128, @truncate(t2 >> 384)) + @as(u1, @truncate(t2 >> 383));
72
73 var buf: [32]u8 = undefined;
74
75 mem.writeInt(u256, &buf, c1, .little);
76 const c1x = try scalar.mul(buf, b1_neg_s, .little);
77
78 mem.writeInt(u256, &buf, c2, .little);
79 const c2x = try scalar.mul(buf, b2_neg_s, .little);
80
81 const r2 = try scalar.add(c1x, c2x, .little);
82
83 var r1 = try scalar.mul(r2, lambda_s, .little);
84 r1 = try scalar.sub(s, r1, .little);
85
86 return SplitScalar{ .r1 = r1, .r2 = r2 };
87 }
88 };
89
90 /// Reject the neutral element.
91 pub fn rejectIdentity(p: Secp256k1) IdentityElementError!void {
92 const affine_0 = @intFromBool(p.x.equivalent(AffineCoordinates.identityElement.x)) & (@intFromBool(p.y.isZero()) | @intFromBool(p.y.equivalent(AffineCoordinates.identityElement.y)));
93 const is_identity = @intFromBool(p.z.isZero()) | affine_0;
94 if (is_identity != 0) {
95 return error.IdentityElement;
96 }
97 }
98
99 /// Create a point from affine coordinates after checking that they match the curve equation.
100 pub fn fromAffineCoordinates(p: AffineCoordinates) EncodingError!Secp256k1 {
101 const x = p.x;
102 const y = p.y;
103 const x3B = x.sq().mul(x).add(B);
104 const yy = y.sq();
105 if (!x3B.equivalent(yy)) {
106 return error.InvalidEncoding;
107 }
108 return .{ .x = x, .y = y, .z = Fe.one };
109 }
110
111 /// Create a point from serialized affine coordinates.
112 pub fn fromSerializedAffineCoordinates(xs: [32]u8, ys: [32]u8, endian: std.lang.Endian) (NonCanonicalError || EncodingError)!Secp256k1 {
113 const x = try Fe.fromBytes(xs, endian);
114 const y = try Fe.fromBytes(ys, endian);
115 return fromAffineCoordinates(.{ .x = x, .y = y });
116 }
117
118 /// Recover the Y coordinate from the X coordinate.
119 pub fn recoverY(x: Fe, is_odd: bool) NotSquareError!Fe {
120 const x3B = x.sq().mul(x).add(B);
121 var y = try x3B.sqrt();
122 const yn = y.neg();
123 y.cMov(yn, @intFromBool(is_odd) ^ @intFromBool(y.isOdd()));
124 return y;
125 }
126
127 /// Deserialize a SEC1-encoded point.
128 pub fn fromSec1(s: []const u8) (EncodingError || NotSquareError || NonCanonicalError)!Secp256k1 {
129 if (s.len < 1) return error.InvalidEncoding;
130 const encoding_type = s[0];
131 const encoded = s[1..];
132 switch (encoding_type) {
133 0 => {
134 if (encoded.len != 0) return error.InvalidEncoding;
135 return Secp256k1.identityElement;
136 },
137 2, 3 => {
138 if (encoded.len != 32) return error.InvalidEncoding;
139 const x = try Fe.fromBytes(encoded[0..32].*, .big);
140 const y_is_odd = (encoding_type == 3);
141 const y = try recoverY(x, y_is_odd);
142 return Secp256k1{ .x = x, .y = y };
143 },
144 4 => {
145 if (encoded.len != 64) return error.InvalidEncoding;
146 const x = try Fe.fromBytes(encoded[0..32].*, .big);
147 const y = try Fe.fromBytes(encoded[32..64].*, .big);
148 return Secp256k1.fromAffineCoordinates(.{ .x = x, .y = y });
149 },
150 else => return error.InvalidEncoding,
151 }
152 }
153
154 /// Serialize a point using the compressed SEC-1 format.
155 pub fn toCompressedSec1(p: Secp256k1) [33]u8 {
156 var out: [33]u8 = undefined;
157 const xy = p.affineCoordinates();
158 out[0] = if (xy.y.isOdd()) 3 else 2;
159 out[1..].* = xy.x.toBytes(.big);
160 return out;
161 }
162
163 /// Serialize a point using the uncompressed SEC-1 format.
164 pub fn toUncompressedSec1(p: Secp256k1) [65]u8 {
165 var out: [65]u8 = undefined;
166 out[0] = 4;
167 const xy = p.affineCoordinates();
168 out[1..33].* = xy.x.toBytes(.big);
169 out[33..65].* = xy.y.toBytes(.big);
170 return out;
171 }
172
173 /// Return a random point.
174 pub fn random(io: std.Io) Secp256k1 {
175 const n = scalar.random(io, .little);
176 return basePoint.mul(n, .little) catch unreachable;
177 }
178
179 /// Flip the sign of the X coordinate.
180 pub fn neg(p: Secp256k1) Secp256k1 {
181 return .{ .x = p.x, .y = p.y.neg(), .z = p.z };
182 }
183
184 /// Double a secp256k1 point.
185 // Algorithm 9 from https://eprint.iacr.org/2015/1060.pdf
186 pub fn dbl(p: Secp256k1) Secp256k1 {
187 var t0 = p.y.sq();
188 var Z3 = t0.dbl();
189 Z3 = Z3.dbl();
190 Z3 = Z3.dbl();
191 var t1 = p.y.mul(p.z);
192 var t2 = p.z.sq();
193 // b3 = (2^2)^2 + 2^2 + 1
194 const t2_4 = t2.dbl().dbl();
195 t2 = t2_4.dbl().dbl().add(t2_4).add(t2);
196 var X3 = t2.mul(Z3);
197 var Y3 = t0.add(t2);
198 Z3 = t1.mul(Z3);
199 t1 = t2.dbl();
200 t2 = t1.add(t2);
201 t0 = t0.sub(t2);
202 Y3 = t0.mul(Y3);
203 Y3 = X3.add(Y3);
204 t1 = p.x.mul(p.y);
205 X3 = t0.mul(t1);
206 X3 = X3.dbl();
207 return .{
208 .x = X3,
209 .y = Y3,
210 .z = Z3,
211 };
212 }
213
214 /// Add secp256k1 points, the second being specified using affine coordinates.
215 // Algorithm 8 from https://eprint.iacr.org/2015/1060.pdf
216 pub fn addMixed(p: Secp256k1, q: AffineCoordinates) Secp256k1 {
217 var t0 = p.x.mul(q.x);
218 var t1 = p.y.mul(q.y);
219 var t3 = q.x.add(q.y);
220 var t4 = p.x.add(p.y);
221 t3 = t3.mul(t4);
222 t4 = t0.add(t1);
223 t3 = t3.sub(t4);
224 t4 = q.y.mul(p.z);
225 t4 = t4.add(p.y);
226 var Y3 = q.x.mul(p.z);
227 Y3 = Y3.add(p.x);
228 var X3 = t0.dbl();
229 t0 = X3.add(t0);
230 // b3 = (2^2)^2 + 2^2 + 1
231 const t2_4 = p.z.dbl().dbl();
232 var t2 = t2_4.dbl().dbl().add(t2_4).add(p.z);
233 var Z3 = t1.add(t2);
234 t1 = t1.sub(t2);
235 const Y3_4 = Y3.dbl().dbl();
236 Y3 = Y3_4.dbl().dbl().add(Y3_4).add(Y3);
237 X3 = t4.mul(Y3);
238 t2 = t3.mul(t1);
239 X3 = t2.sub(X3);
240 Y3 = Y3.mul(t0);
241 t1 = t1.mul(Z3);
242 Y3 = t1.add(Y3);
243 t0 = t0.mul(t3);
244 Z3 = Z3.mul(t4);
245 Z3 = Z3.add(t0);
246
247 var ret = Secp256k1{
248 .x = X3,
249 .y = Y3,
250 .z = Z3,
251 };
252 ret.cMov(p, @intFromBool(q.x.isZero()));
253 return ret;
254 }
255
256 /// Add secp256k1 points.
257 // Algorithm 7 from https://eprint.iacr.org/2015/1060.pdf
258 pub fn add(p: Secp256k1, q: Secp256k1) Secp256k1 {
259 var t0 = p.x.mul(q.x);
260 var t1 = p.y.mul(q.y);
261 var t2 = p.z.mul(q.z);
262 var t3 = p.x.add(p.y);
263 var t4 = q.x.add(q.y);
264 t3 = t3.mul(t4);
265 t4 = t0.add(t1);
266 t3 = t3.sub(t4);
267 t4 = p.y.add(p.z);
268 var X3 = q.y.add(q.z);
269 t4 = t4.mul(X3);
270 X3 = t1.add(t2);
271 t4 = t4.sub(X3);
272 X3 = p.x.add(p.z);
273 var Y3 = q.x.add(q.z);
274 X3 = X3.mul(Y3);
275 Y3 = t0.add(t2);
276 Y3 = X3.sub(Y3);
277 X3 = t0.dbl();
278 t0 = X3.add(t0);
279 // b3 = (2^2)^2 + 2^2 + 1
280 const t2_4 = t2.dbl().dbl();
281 t2 = t2_4.dbl().dbl().add(t2_4).add(t2);
282 var Z3 = t1.add(t2);
283 t1 = t1.sub(t2);
284 const Y3_4 = Y3.dbl().dbl();
285 Y3 = Y3_4.dbl().dbl().add(Y3_4).add(Y3);
286 X3 = t4.mul(Y3);
287 t2 = t3.mul(t1);
288 X3 = t2.sub(X3);
289 Y3 = Y3.mul(t0);
290 t1 = t1.mul(Z3);
291 Y3 = t1.add(Y3);
292 t0 = t0.mul(t3);
293 Z3 = Z3.mul(t4);
294 Z3 = Z3.add(t0);
295
296 return .{
297 .x = X3,
298 .y = Y3,
299 .z = Z3,
300 };
301 }
302
303 /// Subtract secp256k1 points.
304 pub fn sub(p: Secp256k1, q: Secp256k1) Secp256k1 {
305 return p.add(q.neg());
306 }
307
308 /// Subtract secp256k1 points, the second being specified using affine coordinates.
309 pub fn subMixed(p: Secp256k1, q: AffineCoordinates) Secp256k1 {
310 return p.addMixed(q.neg());
311 }
312
313 /// Return affine coordinates.
314 pub fn affineCoordinates(p: Secp256k1) AffineCoordinates {
315 const affine_0 = @intFromBool(p.x.equivalent(AffineCoordinates.identityElement.x)) & (@intFromBool(p.y.isZero()) | @intFromBool(p.y.equivalent(AffineCoordinates.identityElement.y)));
316 const is_identity = @intFromBool(p.z.isZero()) | affine_0;
317 const zinv = p.z.invert();
318 var ret = AffineCoordinates{
319 .x = p.x.mul(zinv),
320 .y = p.y.mul(zinv),
321 };
322 ret.cMov(AffineCoordinates.identityElement, is_identity);
323 return ret;
324 }
325
326 /// Return true if both coordinate sets represent the same point.
327 pub fn equivalent(a: Secp256k1, b: Secp256k1) bool {
328 if (a.sub(b).rejectIdentity()) {
329 return false;
330 } else |_| {
331 return true;
332 }
333 }
334
335 fn cMov(p: *Secp256k1, a: Secp256k1, c: u1) void {
336 p.x.cMov(a.x, c);
337 p.y.cMov(a.y, c);
338 p.z.cMov(a.z, c);
339 }
340
341 fn pcSelect(comptime n: usize, pc: *const [n]Secp256k1, b: u8) Secp256k1 {
342 var t = Secp256k1.identityElement;
343 comptime var i: u8 = 1;
344 inline while (i < pc.len) : (i += 1) {
345 t.cMov(pc[i], @as(u1, @truncate((@as(usize, b ^ i) -% 1) >> 8)));
346 }
347 return t;
348 }
349
350 fn slide(s: [32]u8) [2 * 32 + 1]i8 {
351 var e: [2 * 32 + 1]i8 = undefined;
352 for (s, 0..) |x, i| {
353 e[i * 2 + 0] = @as(i8, @as(u4, @truncate(x)));
354 e[i * 2 + 1] = @as(i8, @as(u4, @truncate(x >> 4)));
355 }
356 // Now, e[0..63] is between 0 and 15, e[63] is between 0 and 7
357 var carry: i8 = 0;
358 for (e[0..64]) |*x| {
359 x.* += carry;
360 carry = (x.* + 8) >> 4;
361 x.* -= carry * 16;
362 std.debug.assert(x.* >= -8 and x.* <= 8);
363 }
364 e[64] = carry;
365 // Now, e[*] is between -8 and 8, including e[64]
366 std.debug.assert(carry >= -8 and carry <= 8);
367 return e;
368 }
369
370 fn pcMul(pc: *const [9]Secp256k1, s: [32]u8, comptime vartime: bool) IdentityElementError!Secp256k1 {
371 std.debug.assert(vartime);
372 const e = slide(s);
373 var q = Secp256k1.identityElement;
374 var pos = e.len - 1;
375 while (true) : (pos -= 1) {
376 const slot = e[pos];
377 if (slot > 0) {
378 q = q.add(pc[@as(usize, @intCast(slot))]);
379 } else if (slot < 0) {
380 q = q.sub(pc[@as(usize, @intCast(-slot))]);
381 }
382 if (pos == 0) break;
383 q = q.dbl().dbl().dbl().dbl();
384 }
385 try q.rejectIdentity();
386 return q;
387 }
388
389 fn pcMul16(pc: *const [16]Secp256k1, s: [32]u8, comptime vartime: bool) IdentityElementError!Secp256k1 {
390 var q = Secp256k1.identityElement;
391 var pos: usize = 252;
392 while (true) : (pos -= 4) {
393 const slot = @as(u4, @truncate((s[pos >> 3] >> @as(u3, @truncate(pos)))));
394 if (vartime) {
395 if (slot != 0) {
396 q = q.add(pc[slot]);
397 }
398 } else {
399 q = q.add(pcSelect(16, pc, slot));
400 }
401 if (pos == 0) break;
402 q = q.dbl().dbl().dbl().dbl();
403 }
404 try q.rejectIdentity();
405 return q;
406 }
407
408 fn precompute(p: Secp256k1, comptime count: usize) [1 + count]Secp256k1 {
409 var pc: [1 + count]Secp256k1 = undefined;
410 pc[0] = Secp256k1.identityElement;
411 pc[1] = p;
412 var i: usize = 2;
413 while (i <= count) : (i += 1) {
414 pc[i] = if (i % 2 == 0) pc[i / 2].dbl() else pc[i - 1].add(p);
415 }
416 return pc;
417 }
418
419 const basePointPc = pc: {
420 @setEvalBranchQuota(50000);
421 break :pc precompute(Secp256k1.basePoint, 15);
422 };
423
424 /// Multiply an elliptic curve point by a scalar.
425 /// Return error.IdentityElement if the result is the identity element.
426 pub fn mul(p: Secp256k1, s_: [32]u8, endian: std.lang.Endian) IdentityElementError!Secp256k1 {
427 const s = if (endian == .little) s_ else Fe.orderSwap(s_);
428 if (p.is_base) {
429 return pcMul16(&basePointPc, s, false);
430 }
431 try p.rejectIdentity();
432 const pc = precompute(p, 15);
433 return pcMul16(&pc, s, false);
434 }
435
436 /// Multiply an elliptic curve point by a *PUBLIC* scalar *IN VARIABLE TIME*
437 /// This can be used for signature verification.
438 pub fn mulPublic(p: Secp256k1, s_: [32]u8, endian: std.lang.Endian) (IdentityElementError || NonCanonicalError)!Secp256k1 {
439 const s = if (endian == .little) s_ else Fe.orderSwap(s_);
440 const zero = comptime scalar.Scalar.zero.toBytes(.little);
441 if (mem.eql(u8, &zero, &s)) {
442 return error.IdentityElement;
443 }
444 const pc = precompute(p, 8);
445 var lambda_p = try pcMul(&pc, Endormorphism.lambda_s, true);
446 var split_scalar = try Endormorphism.splitScalar(s, .little);
447 var px = p;
448
449 // If a key is negative, flip the sign to keep it half-sized,
450 // and flip the sign of the Y point coordinate to compensate.
451 if (split_scalar.r1[split_scalar.r1.len / 2] != 0) {
452 split_scalar.r1 = scalar.neg(split_scalar.r1, .little) catch zero;
453 px = px.neg();
454 }
455 if (split_scalar.r2[split_scalar.r2.len / 2] != 0) {
456 split_scalar.r2 = scalar.neg(split_scalar.r2, .little) catch zero;
457 lambda_p = lambda_p.neg();
458 }
459 return mulDoubleBasePublicEndo(px, split_scalar.r1, lambda_p, split_scalar.r2);
460 }
461
462 // Half-size double-base public multiplication when using the curve endomorphism.
463 // Scalars must be in little-endian.
464 // The second point is unlikely to be the generator, so don't even try to use the comptime table for it.
465 fn mulDoubleBasePublicEndo(p1: Secp256k1, s1: [32]u8, p2: Secp256k1, s2: [32]u8) IdentityElementError!Secp256k1 {
466 var pc1_array: [9]Secp256k1 = undefined;
467 const pc1 = if (p1.is_base) basePointPc[0..9] else pc: {
468 pc1_array = precompute(p1, 8);
469 break :pc &pc1_array;
470 };
471 const pc2 = precompute(p2, 8);
472 std.debug.assert(s1[s1.len / 2] == 0);
473 std.debug.assert(s2[s2.len / 2] == 0);
474 const e1 = slide(s1);
475 const e2 = slide(s2);
476 var q = Secp256k1.identityElement;
477 var pos: usize = 2 * 32 / 2; // second half is all zero
478 while (true) : (pos -= 1) {
479 const slot1 = e1[pos];
480 if (slot1 > 0) {
481 q = q.add(pc1[@as(usize, @intCast(slot1))]);
482 } else if (slot1 < 0) {
483 q = q.sub(pc1[@as(usize, @intCast(-slot1))]);
484 }
485 const slot2 = e2[pos];
486 if (slot2 > 0) {
487 q = q.add(pc2[@as(usize, @intCast(slot2))]);
488 } else if (slot2 < 0) {
489 q = q.sub(pc2[@as(usize, @intCast(-slot2))]);
490 }
491 if (pos == 0) break;
492 q = q.dbl().dbl().dbl().dbl();
493 }
494 try q.rejectIdentity();
495 return q;
496 }
497
498 /// Double-base multiplication of public parameters - Compute (p1*s1)+(p2*s2) *IN VARIABLE TIME*
499 /// This can be used for signature verification.
500 pub fn mulDoubleBasePublic(p1: Secp256k1, s1_: [32]u8, p2: Secp256k1, s2_: [32]u8, endian: std.lang.Endian) IdentityElementError!Secp256k1 {
501 const s1 = if (endian == .little) s1_ else Fe.orderSwap(s1_);
502 const s2 = if (endian == .little) s2_ else Fe.orderSwap(s2_);
503 try p1.rejectIdentity();
504 var pc1_array: [9]Secp256k1 = undefined;
505 const pc1 = if (p1.is_base) basePointPc[0..9] else pc: {
506 pc1_array = precompute(p1, 8);
507 break :pc &pc1_array;
508 };
509 try p2.rejectIdentity();
510 var pc2_array: [9]Secp256k1 = undefined;
511 const pc2 = if (p2.is_base) basePointPc[0..9] else pc: {
512 pc2_array = precompute(p2, 8);
513 break :pc &pc2_array;
514 };
515 const e1 = slide(s1);
516 const e2 = slide(s2);
517 var q = Secp256k1.identityElement;
518 var pos: usize = 2 * 32;
519 while (true) : (pos -= 1) {
520 const slot1 = e1[pos];
521 if (slot1 > 0) {
522 q = q.add(pc1[@as(usize, @intCast(slot1))]);
523 } else if (slot1 < 0) {
524 q = q.sub(pc1[@as(usize, @intCast(-slot1))]);
525 }
526 const slot2 = e2[pos];
527 if (slot2 > 0) {
528 q = q.add(pc2[@as(usize, @intCast(slot2))]);
529 } else if (slot2 < 0) {
530 q = q.sub(pc2[@as(usize, @intCast(-slot2))]);
531 }
532 if (pos == 0) break;
533 q = q.dbl().dbl().dbl().dbl();
534 }
535 try q.rejectIdentity();
536 return q;
537 }
538};
539
540/// A point in affine coordinates.
541pub const AffineCoordinates = struct {
542 x: Secp256k1.Fe,
543 y: Secp256k1.Fe,
544
545 /// Identity element in affine coordinates.
546 pub const identityElement = AffineCoordinates{ .x = Secp256k1.identityElement.x, .y = Secp256k1.identityElement.y };
547
548 pub fn neg(p: AffineCoordinates) AffineCoordinates {
549 return .{ .x = p.x, .y = p.y.neg() };
550 }
551
552 fn cMov(p: *AffineCoordinates, a: AffineCoordinates, c: u1) void {
553 p.x.cMov(a.x, c);
554 p.y.cMov(a.y, c);
555 }
556};
557
558test {
559 _ = @import("tests/secp256k1.zig");
560}