secp256k1
Points in, points out
import { addPoints, liftX, multiplyGenerator, multiplyPoint } from "@agntn/curves/secp256k1";
const G = multiplyGenerator("1"); // "0279be667ef9dcbb…1798"
multiplyGenerator(3n); // "02f9308a019258c3…36f9"
addPoints(G, multiplyGenerator(2n)); // "02f9308a019258c3…36f9", 3G again
Points are SEC1 hex without 0x, 33 bytes compressed or 65 uncompressed. Output is compressed unless you pass { compressed: false }. A scalar is hex up to 64 digits or a bigint, from 1 to n - 1.
| Function | Does |
|---|---|
addPoints(a, b) | a + b, as in a split key vanity address |
subtractPoints(a, b) | a - b, the offset between two known keys |
negatePoint(p) | same x, the other y |
multiplyPoint(p, k) | k times p |
multiplyGenerator(k) | k times G, the public key of k |
liftX(x) | both points above x, even first |
isOnCurve(p) | true or false |
convertPoint(p) | between 33 and 65 bytes |
sign(secret, { digest }) | an ECDSA signature and its recovery ID |
signingNonce(secret, { digest }) | the k that sign draws |
verify(sig, { digest, publicKey }) | true or false for an ECDSA signature |
recoverPublicKey(sig, { digest, recovery }) | the public key for a recovery ID |
Half of G
What's G times the inverse of 2?
import { invertScalar, multiplyPoint } from "@agntn/curves/secp256k1";
invertScalar(2n); // "7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1"
multiplyPoint(G, invertScalar(2n)); // "0200000000000000000000003b78ce563f89a0ed9414f5aa28ad0d96d6795f9c63"
Eleven zero bytes at the start of x. Out of 2^256 possible values. Make of that what you will.
Scalars mod n
addScalars, subtractScalars, multiplyScalars and invertScalar work mod the group order and give 64 hex digits back:
addScalars("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140", "2"); // "000…001"
That first number is n - 1, so adding 2 wraps to 1.
Verify an ECDSA signature from Bitcoin block 170
On 12 January 2009, Satoshi paid Hal Finney 10 BTC. The transaction in block 170 sent 40 BTC back to Satoshi. Input 0 spent the 50 BTC block 9 paid to Satoshi's key.
The transaction is f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16. Its input 0 signs the legacy SIGHASH_ALL digest below. That's a signature worth checking.
import { verify, recoverPublicKey } from "@agntn/curves/secp256k1";
const SATOSHI = "0411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3";
const digest = "7a05c6145f10101e9d6325494245adf1297d80f8f38d4d576d57cdba220bcb19";
const signature = "4e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd41181522ec8eca07de4860a4acdd12909d831cc56cbbac4622082221a8768d1d09";
verify(signature, { digest, publicKey: SATOSHI }); // true
verify(signature, { digest, publicKey: SATOSHI, lowS: true }); // true
recoverPublicKey(signature, { digest, recovery: 1 }); // "0311db93e1dcdb8a…a6909a5c"
recoverPublicKey(signature, { digest, recovery: 0 }); // "02fa0afca078065d…c316d323"
Why do both recovery IDs return a key? Each returned key verifies the signature. Recovery 1 gives Satoshi's key in compressed form. Recovery 0 gives another verifying key. One signature, two keys. Only one of them paid Hal. Compare the recovered key with the one you expect, using the same encoding.
The signature is r followed by s, as 128 hex digits without 0x. Unpack a DER signature first. Hash the message yourself and pass the digest as hex without 0x. The digest can be 1 to 64 bytes. Beyond 32 bytes, only the leftmost 256 bits count.
lowS: true rejects s above n / 2, as in Bitcoin's BIP 62 and BIP 146. This signature has a low s, so it passes either way. The default is false, unlike noble and libsecp256k1, because SEC 1 accepts either s.
Recovery IDs run from 0 to 3. Bit 0 selects the parity of the y coordinate of R. Bit 1 selects x = r + n, which requires r below p - n. IDs 2 and 3 almost never work on a real signature. For this signature, both throw because no such point exists.
Recovered keys are compressed SEC1 hex by default. Pass compressed: false for an uncompressed key. Verification and recovery take public input.
The playground has the same signature behind the block 170 chip.
Sign a digest with ECDSA
Satoshi's key stays Satoshi's. Secret 1 can still sign the same sighash, though:
import { multiplyGenerator, recoverPublicKey, sign, verify } from "@agntn/curves/secp256k1";
const digest = "7a05c6145f10101e9d6325494245adf1297d80f8f38d4d576d57cdba220bcb19";
const { signature, recovery } = sign("1", { digest });
// signature: "51e6cc3b28037f59…ddb5e5aa2f", recovery: 1
verify(signature, { digest, publicKey: multiplyGenerator("1"), lowS: true }); // true
recoverPublicKey(signature, { digest, recovery }); // "0279be667ef9dcbb…1798", which is G
Sign it again. Same bytes. Why? RFC 6979 builds k from the secret and the digest with HMAC-SHA-256. No random number generator, so none to get wrong. Sony signed PS3 software with the same k every time, and that gave its key away.
SHA-256 is the default, not the only choice. If another hash made the digest, name it with hash to match other RFC 6979 signers.
The secret is hex up to 64 digits or a bigint, from 1 to n - 1, like the scalar of multiplyGenerator. The digest reads the way verify reads it, 1 to 64 bytes.
s always comes out at most n / 2. Bitcoin's BIP 146 and Ethereum both want it that way. The recovery ID tracks that choice, so recoverPublicKey with it gives your key back. Ethereum's v is 27 plus it.
Read the signing nonce
Read the nonce behind a signature with signingNonce. Its point's x coordinate shows up as r. That's k hiding in plain sight.
import { multiplyGenerator, signingNonce } from "@agntn/curves/secp256k1";
const digest = "7a05c6145f10101e9d6325494245adf1297d80f8f38d4d576d57cdba220bcb19";
const k = signingNonce("1", { digest }); // "f7e737b6c30dea14…5d863e64"
multiplyGenerator(k); // "0251e6cc3b28037f…74e1f4f6", and its x is the signature's r
You get the k that signed, as 64 hex digits. It's k as drawn, never n - k, even when sign flips s low. Rejected candidates don't count.
Keep k as secret as the private key. Anyone with k and the signature can compute that key.
It's useful for test vectors and comparing RFC 6979 signers. It also helps debug differing signatures. The other six SEC 1 curves export it too.
Sign and verify BIP340 Schnorr signatures
This is BIP340's own test vector 1. Does the signature still work with a different message or key?
import { verify } from "@agntn/curves/bip340";
const publicKey = "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659";
const message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89";
const signature = "6896bd60eeae296db48a229ff71dfe071bde413e6d43f917dc8dcf8c78de33418906d11ac976abccb20b091292bff4ea897efcb639ea871cfa95f6de339e4b0a";
verify(signature, { message, publicKey }); // true
verify(signature, { message: "", publicKey }); // false
verify(signature, { message, publicKey: "5".padStart(64, "0") }); // false
The publicKey is an x-only key: 64 hex digits without 0x. It picks the point with even y above that x. Strip 02 or 03 from a compressed SEC1 key and you have it. liftX(x).even gives that point back as SEC1.
The message is hex without 0x. It can be any length, even empty. Vector 15 signs an empty message.
The signature is 128 hex digits. First comes the x of R, then s.
Vector 1 signs pi with a key made of e. The message is the first 32 bytes of pi's hex digits after the point. The secret key is the same slice of e. Nothing up the sleeve.
A wrong signature returns false. So does a key with x at or above p, or with no point above it. Here, x = 5 has no point. BIP340's vectors call that a failed signature. That's the right call.
An r at or above p or an s at or above n also returns false. So does a computed R at infinity or with odd y. Wrong input shape throws an error instead. The ECDSA verify above throws when its public key is no point. BIP340 doesn't.
Taproot signs a 32-byte sighash. Nostr signs the 32-byte event id.
Sign by BIP340
import { getPublicKey, sign } from "@agntn/curves/bip340";
const secret = "b7e151628aed2a6abf7158809cf4f3c762e7160f38b4da56a784d9045190cfef";
const message = "243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89";
getPublicKey(secret); // "dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659"
sign(secret, { message, random: "0".repeat(63) + "1" }); // "6896bd60eeae296d…339e4b0a", vector 1
sign(secret, { message }); // new bytes every call, and every one verifies
That's vector 1 again, signed this time. The secret is the e slice, 64 hex digits for a number from 1 to n - 1.
random is the BIP's aux_rand, 32 bytes mixed into the nonce. Leave it out and 32 fresh bytes go in, as the BIP recommends. Pass the vector's own and you get its signature to the byte.
A secret whose point has odd y gets negated before it signs. You never see it. The x-only key stays the same either way.
Each signature goes through verify before it comes back, another BIP recommendation. It costs about a millisecond. Cheap insurance against a flipped bit.
What it refuses
subtractPoints(G, G) // The result is the point at infinity, which is no public key, as with P minus P
multiplyPoint(G, "0") // Scalar must be hex without 0x or a bigint, from 1 to the curve order minus 1
negatePoint("02000…0005") // Invalid SEC1 secp256k1 public key
sign("0", { digest }) // Secret must be hex without 0x or a bigint, from 1 to the curve order minus 1
verify("00", { digest, publicKey: SATOSHI }) // Signature must be 128 hex digits without 0x, r then s
verify(signature, { digest: "", publicKey: SATOSHI }) // Digest must be hex without 0x, 1 to 64 bytes
verify("00", { message, publicKey }) // Signature must be 128 hex digits without 0x, r then s
verify(signature, { message: "0x00", publicKey }) // Message must be hex without 0x
verify(signature, { message, publicKey: "02" + publicKey }) // Public key must be 64 hex digits without 0x
sign(secret, { message, random: "00" }) // Random must be 64 hex digits without 0x, the aux_rand of BIP340
The last four lines use @agntn/curves/bip340.
No point of secp256k1 has x = 5, so the compressed form above is no point at all. isOnCurve says false for it instead of throwing. A coordinate at or above p is refused too, as SEC 1 asks.
For r or s outside 1 to n - 1, verify returns false. Recovery throws r and s must both be from 1 to the curve order minus 1.
For the block 170 signature, recovery 2 throws No point of secp256k1 has x = r + n, so recovery 2 fails. Recovery 3 reports the same problem with its own ID.
Written from the specs
The domain parameters come from SEC 2, section 2.4.1. The encodings follow SEC 1, sections 2.3.3 and 2.3.4. No @noble/curves underneath, though the tests hold every result to it.
Points add with the complete formulas of Renes, Costello and Batina (2016), in projective coordinates. No special cases. Infinity and a point plus itself take the same twelve multiplications as any other sum.
Verification follows SEC 1 section 4.1.4, and recovery follows section 4.1.6. All 574 secp256k1 Wycheproof P1363 vectors for SHA-256 and SHA-512 get the expected answer. Recovery tests also match results frozen from @noble/curves 2.4.0.
Signing follows SEC 1 section 4.1.3. The nonce comes from RFC 6979, with HMAC-SHA-256 from @agntn/hashes. The RFC's own examples check it: K-163 throws two candidates out before the third fits, and P-256 lands on the RFC's k for sample and test. Nine signatures, keys 1 and n - 1 among them, match @noble/curves 2.4.0 to the byte. Recovery IDs too.
BIP340 verification gets the expected answer for all 19 official vectors. It also passes nine cases frozen from @noble/curves 2.4.0. Six are signatures over messages of 0, 1, 32, 64 and 200 bytes. Three are broken copies noble refused.
Signing gets every vector with a secret right, eight of them, and eight more frozen from noble. Noble isn't underneath. The BIP's tagged hashes use SHA-256 from @agntn/hashes.
Is it as fast as noble? Almost. A public key takes about 0.46 ms here and 0.34 ms in noble, on the same machine. Both take the same steps for every secret, so it's a fair race. We lose it by about a tenth of a millisecond.
Where does the time go? Into the same steps for every secret. G goes through a comb of 4 rows, 64 multiples built on the first call. Every scalar walks 16 steps of four doublings and four additions. No digit is ever zero, so scalar 1 does the work of n - 1.
A bigger comb would be faster. But then a repeated secret runs faster than random ones, and that's a leak. Four rows don't show it.
Any other point takes about 1.07 ms. Verification and recovery only see public scalars, so they read G from a table of 960 multiples instead. At most 64 additions and no doubling. Its time follows the digits, and there that's fine. A signature checks in about 1.2 ms.
Signing puts the nonce through the comb too. Then k^(n - 2) inverts it, since Euclid's step count would leak k. An ECDSA signature takes about 0.6 ms. BIP340 takes about 2.1 ms, most of it the verify it runs on itself.
In a local dudect run, a fixed secret and random ones stayed within 0.44 percent. JavaScript promises nothing about timing, though, and none of this is audited. Real funds stay out.
Over MCP
curves_secp256k1_compute does add, subtract, negate, multiply, lift, check, sign, nonce, verify and recover. Scalar math stays in the library.
{"operation":"lift","even":"0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","odd":"0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"}
For sign, pass secret and digest. You get signature, recovery and the publicKey that signed, compressed unless compressed is false.
For nonce, pass secret and digest, with optional hash. You get nonce, a second secret that's worth guarding as closely as the key.
For verify, pass the public key as point, plus digest and signature. You can also pass lowS. For recover, pass digest, signature and recovery. You can also pass compressed.
The CLI uses the same inputs. Running curves secp256k1 verify with Satoshi's key, digest and signature above returns:
{"operation":"verify","valid":true}
curves_bip340_compute does keypair, sign and verify. keypair takes secret. sign takes secret and message, plus random when you want the same bytes twice. verify takes publicKey, message and signature. The CLI takes the same values:
curves bip340 verify --public-key dff1d77f2a671c5f36183726db2341be58feae1da2deced843240f7b502ba659 --message 243f6a8885a308d313198a2e03707344a4093822299f31d0082efa98ec4e6c89 --signature 6896bd60eeae296db48a229ff71dfe071bde413e6d43f917dc8dcf8c78de33418906d11ac976abccb20b091292bff4ea897efcb639ea871cfa95f6de339e4b0a
It prints {"operation":"verify","valid":true}.