pull down to refresh

Analysis of secp256k1's first commit: Modular inversion via Fermat's Little Theorem

This is a cross-post from my blog. I'm starting to write more about early Bitcoin implementations, and feedback is very welcome.

Why modular inversion matters in secp256k1Why modular inversion matters in secp256k1

In secp256k1, almost every elliptic curve operation requires a modular inversion in the finite field (computing ). This is an expensive operation.

In the very first commit of the library (2013), instead of using the Extended Euclidean Algorithm (which is used today), the code computed the inverse using Fermat's Little Theorem.

Fermat's Little Theorem (intuitive version)Fermat's Little Theorem (intuitive version)

If is prime and , then:

From this, we can derive the modular inverse directly:

So to invert (a), we just need to compute (a^{p-2} \mod p).

The challengeThe challenge

The prime used in secp256k1 is (p = 2^{256} - 2^{32} - 977). This means the exponent (p-2) is enormous. Naïve exponentiation would be far too slow.

The standard solution is binary exponentiation (exponentiation by squaring), which brings the complexity down to (O(\log n)).

This post is a summary.

The full article goes deeper into:

  • A more intuitive explanation of Fermat’s Little Theorem
  • How binary exponentiation works in practice with examples
  • The actual 5-bit addition chain optimization used in the first commit (with code analysis)

Read the full article here:

The secp256k1 first commit analysis part 2: modular inversion via Fermat's Little Theorem

Thanks for posting! I don't have much of a math background and so I find these kinda like exploring an unknown jungle. For instance, I didn't know about exponentiation by squaring, but it is so cool!

I also appreciate your general efforts to examine these artefacts of Bitcoin history.

reply
5 sats \ 0 replies \ @Hazard_sats 10 Jul -30 sats

Fascinating look back at the 2013 repository. Even though the Extended Euclidean Algorithm is the standard today, seeing how Fermat's Little Theorem was handled with binary squaring in that first commit shows how deeply thought out the core math was from day one.