Skip to content

Commit

Permalink
std.crypto.ecc: add support for the secp256k1 curve (#11880)
Browse files Browse the repository at this point in the history
std.crypto.ecc: add support for the secp256k1 curve

Usage of the secp256k1 elliptic curve recently grew exponentially,
since this is the curve used by Bitcoin and other popular blockchains
such as Ethereum.

With this, Zig has support for all the widely deployed elliptic curves
today.
  • Loading branch information
jedisct1 authored and andrewrk committed Jul 19, 2022
1 parent 09ff086 commit 3d22b6c
Show file tree
Hide file tree
Showing 8 changed files with 4,933 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/std/crypto.zig
Expand Up @@ -64,6 +64,7 @@ pub const ecc = struct {
pub const P256 = @import("crypto/pcurves/p256.zig").P256;
pub const P384 = @import("crypto/pcurves/p384.zig").P384;
pub const Ristretto255 = @import("crypto/25519/ristretto255.zig").Ristretto255;
pub const Secp256k1 = @import("crypto/pcurves/secp256k1.zig").Secp256k1;
};

/// Hash functions.
Expand Down Expand Up @@ -205,6 +206,7 @@ test {
_ = ecc.P256;
_ = ecc.P384;
_ = ecc.Ristretto255;
_ = ecc.Secp256k1;

_ = hash.blake2;
_ = hash.Blake3;
Expand Down
11 changes: 11 additions & 0 deletions lib/std/crypto/pcurves/common.zig
Expand Up @@ -295,6 +295,17 @@ pub fn Field(comptime params: FieldParams) type {
const x63 = x32.sqn(31).mul(x31);
const x126 = x63.sqn(63).mul(x63);
return x126.sqn(126).mul(x126).sqn(3).mul(t111).sqn(33).mul(x32).sqn(64).mul(x2).sqn(30);
} else if (field_order == 115792089237316195423570985008687907853269984665640564039457584007908834671663) {
const t11 = x2.mul(x2.sq());
const t1111 = t11.mul(t11.sqn(2));
const t11111 = x2.mul(t1111.sq());
const t1111111 = t11.mul(t11111.sqn(2));
const x11 = t1111111.sqn(4).mul(t1111);
const x22 = x11.sqn(11).mul(x11);
const x27 = x22.sqn(5).mul(t11111);
const x54 = x27.sqn(27).mul(x27);
const x108 = x54.sqn(54).mul(x54);
return x108.sqn(108).mul(x108).sqn(7).mul(t1111111).sqn(23).mul(x22).sqn(6).mul(t11).sqn(2);
} else {
return x2.pow(std.meta.Int(.unsigned, field_bits), (field_order + 1) / 4);
}
Expand Down

0 comments on commit 3d22b6c

Please sign in to comment.