Dynamic Programming in Bitcoin ECDSA Cryptanalysis

20.10.2026

Using dynamic programming with a small parameter, a limited sum, and a low treewidth to recover the hidden nonce and private key. Dynamic programming is not a universal replacement for lattice methods, but  a specialized tool  for cryptanalysis of ECDSA under combinatorial nonce leaks:

  • small parameter – DP by Hamming weight bits;
  • limited amount – knapsack-DP modulo;
  • low treewidth — tree-decomposition of DP by the equation graph;
  • MITM – “DP in half” of the search space.

By combining these approaches with LLL/BKZ, one can solve problems inaccessible to either pure lattices or brute force. It is at the intersection of these methods that the cutting edge of modern ECDSA cryptanalysis lies.

Content

  1. Introduction: ECDSA and the Hidden Number Problem
  2. Formalizing HNP for Bitcoin Signatures
  3. DP with small parameter: nonce of low Hamming weight
  4. Limited-amount DP: The knapsack approach
  5. DP at low treewidth: decomposition of the system of equations
  6. Meet-in-the-Middle as “DP at the Half”
  7. Practical implementation in Python
  8. Limitations, countermeasures and conclusions

1. Introduction: ECDSA and the Hidden Number Problem

The ECDSA  (Elliptic Curve Digital Signature Algorithm)  scheme  over a curve secp256k1 is the foundation of Bitcoin transaction security. Each signature (r,s) for a message with a hash z and a private key d is formed as follows:k←$[1,n–1],R=kG,r=Rxmodn,s=k–1(z+rd)modn

Here G — generator of the order group n (for secp256k1 n≈2256), A k —  a one-time secret (nonce) . It is the weakness of generation k — the main cause of catastrophic private key leaks in Bitcoin (Sony PS3, Android SecureRandom attacks, wallet weaknesses, etc.).

The key idea is that  if an attacker knows anything about the structure k

 (small Hamming weight, limited range, linear dependence on previous values), recovery problem d

 turns into  a combinatorial one  – and this is where dynamic programming comes into play.

2. Formalization of HNP for Bitcoin signatures

From the main equation we express k:k=s–1(z+rd)modn⟺k=αi+βidmodn,αi=si–1zi,βi=si–1ri.

If known m signatures with a common d, we obtain the system:ki≡αi+βid(modn),i=1,…,m.

The classical  Hidden Number Problem (HNP)  (Boneh–Venkatesan, 1996) assumes that the most significant bits are known ki: ki=k~i+ei, Where |ei|<2B. Error vector e=(e1,…,em) — the “hidden” part, and it needs to be found. Lattice methods (LLL/BKZ) solve this problem if ∑Bi is quite small. But DP provides an alternative in  combinatorial  scenarios.

Why is DP applicable at all?

Because in many real leaks there is uncertainty in ki has  a discrete combinatorial structure rather than a continuous interval:

Leakage modelParameterWhat does DP give?
Low Hamming Weight Noncesmall w=wt(k)DP by bits
The nonce amount is limited∑ki≤SKnapsack DP
Linear dependence (LCG)low treewidth graphTree-decomposition DP
Nonce small in absolute valuek<232 etc.Meet-in-the-Middle DP

3. DP with a small parameter: nonce with low Hamming weight

3.1 Leakage Model

Let’s assume that the nonce generator is “economical”: wt(k)=w≪256 (For example, w=5 or w=8). Then k – sum w powers of two:k=2b1+2b2+⋯+2bw,0≤b1<b2<⋯<bw≤255.

Candidate space: (256w). At w=5 This ≈8.8⋅109 — still a lot to go through, but structured.

3.2 The idea of ​​dynamic programming

State: dp[i][j][v]

 – Boolean, is it achievable using bits 0..i–1

, dial evenly j

 units and get a partial sum vmodn

.
Transition (transition):  on the beat i

 either 0 or 1:
dp[i+1][j][(v+2i⋅b)modn]∨=dp[i][j–b][v],b∈{0,1}.

Answer:  we are looking for v

, satisfying v≡s–1(z+rd)modn

 for some d

.

An obvious problem: dimensionality v equal 2256Pure DP modulo is impossible. But   there are three saving graces:

  1. Truncation modulo 2m: if we know how to test a hypothesis d on the least significant bits, it is possible to carry out DP by vmod2m.
  2. Connection with signature equation : we do not iterate v blindly, but we conduct the DP by imposing a constraint from the equation.
  3. Cryptographic reduction : instead of complete n we work with a derivative quantity ui=βi–1(ki–αi)modn; then that’s all ui=d.

3.3. A practical bit-wise DP scheme with two signatures

Let’s take two signatures (z1,r1,s1) And (z2,r2,s2). Of these:k1=α1+β1d,k2=α2+β2d(modn).

Both k1,k2 have a Hamming weight ≤wThis imposes  a joint constraint  on d, which can be processed by DP:

  • For each bit position i we add to the partial value d (in least significant bits) term affecting the bit i V k1 And k2.
  • State: (i,j1,j2,carry1,carry2), Where j1,j2 — the number of units already set, carry — carries from additions βd.
  • Final check: j1≤w, j2≤w, and modulo n a consistent value is obtained d.

Complexity. O(256⋅w2⋅C2)

, Where C

 — the number of possible carry states, usually exponentially small for small β

This is a quality win against 2256

.

3.4. Multi-signature version (m signatures)

If there is m signatures with a known upper weight w for each, you can build a DP table based on signature indices and bit positions:

dp[j1][j2][...][jm]  ->  множество достижимых битовых масок d

At m≥4 And w≤8 the method becomes statistically stable: random false solutions are filtered out.

4. Limited Amount DP: The Knapsack Approach

4.1. Model

Let’s assume the attacker knows that ki are small and their amount is limited: ∑i=1mki≤S, Where S≪mnThen the problem is reduced to  the knapsack problem .

4.2. Reduction to knapsack

Let’s express the sum through d:∑i=1mki=∑i=1m(αi+βid)modn=A+Bdmodn,

Where A=∑αi, B=∑βi (both quantities modn). Condition ∑ki≤S means that the value A+Bdmodn falls into a narrow window [0,S]This is a linear congruence with a small right-hand side, to which the modulo DP applies – if we work in the “centered” representation.

4.3. DP diagram

  1. Split the range [0,2256) on blocks by B bit (for example, B=8): d=∑j=031dj28j.
  2. Build a table dp[j][σ][c]: the number of ways in which the first j bytes give a partial sum σ and carry c.
  3. At each step, update the states: σ′=σ+dj⋅Bjmod2256, c′=c+⌊(σ+djBj)/2256⌋.
  4. At the end, select the states where the final value is ∑ki=A+Bdmodn lies in [0,S].

4.4. Hybrid with lattices

Knapsack-DP combines well with LLL: the lattice provides  candidates  for d, and the DP filters them. This is especially effective when the window [0,S] too narrow for a pure grid, but too wide for direct enumeration.

5. DP at low treewidth: decomposition of the system of equations

5.1 Where does treewidth come from?

In real wallets, nonces are often generated  deterministically  (RFC 6979, Deterministic Wallets) or pseudo-randomly with  a linear dependence : orki+1=a⋅ki+b(modn),orki=f(ki–1,ki–2),

If f is a linear function, then the variables (d,k1,…,km) are related by a system of equations whose graph has  low treewidth . Classic examples:

Generation schemeGraphTreewidth
Independent kiStar (center – d)1
LCG: ki+1=aki+bChain + d2
LCG + high-order bit leakageChain with “noise”3–4
Fibonacci-like generatorStripe width 23

5.2 Formal Definition

Tree decomposition  of a graph G=(V,E) – this is a couple (X,T), Where T — a tree, and to each node t∈T “bag” is associated Xt⊆V, such that:

  1. ⋃tXt=V,
  2. for each edge (u,v)∈E exists t With {u,v}⊆Xt,
  3. set {t:v∈Xt} forms a connected subtree in T.

Width = maxt|Xt|–1Treewidth tw(G) — minimum for all decompositions.

5.3. Tree DP algorithm

Input:  graph of variables and equations, tree decomposition (X,T)


Step 1. Select  the root in T


Step 2. For each leaf ,  construct a table of bag variable values ​​consistent with local equations.
Step 3.  Bottom-up: merge child tables, project to the intersection of bags (join), filter by equations at the node.
Step 4.  At the root, obtain the set of admissible values ​​for d

Difficulty :
 O(|T|⋅qtw+1)

, Where q

 — the size of the variable domain.

5.4 Example: LCG with leaky low-order bits

Let ki+1=aki+bmodn and for each signature the junior ones are known L bit ki: κi=kimod2LThen the variables are related by the system:{si–1(zi+rid)≡ki(modn),ki≡κi(mod2L),ki+1≡aki+b(modn).

The graph has treewidth 2 (chain d–k1–k2–⋯–km). The DP along this chain works for O(m⋅22L) – at L≤16 This is  entirely practical , whereas lattice methods would require more complex setup.

6. Meet-in-the-Middle as “DP at half”

A special case of DP is  Meet-in-the-Middle (MITM) : partitioning the space in half and merging the tables. For a low-Hamming-weight nonce:k=∑b∈S12b⏟k(1)+∑b∈S22b⏟k(2),|S1|=|S2|=w/2.

Building a hash table T1={k(1)modn}, then for each k(2) let’s check if there is –k(2)+βdmodn in the table. Complexity O((128w/2)) – at w=8 This ≈1.4⋅1011, still a lot, but with a few captions and a filter – realistic.

7. Practical implementation in Python

7.1 ECDSA signature framework over secp256k1

import hashlib
from ecdsa import SECP256k1, SigningKey   # pip install ecdsa

n = SECP256k1.order
G = SECP256k1.generator

def sign(sk: SigningKey, msg: bytes):
    z = int.from_bytes(hashlib.sha256(msg).digest(), "big") % n
    # ВНИМАНИЕ: используем слабый nonce для демонстрации
    k = 0b100000010000001000000100000010  # wt=5
    R = k * G
    r = R.x() % n
    s = pow(k, -1, n) * (z + r * sk.privkey.secret_multiplier) % n
    return z, r, s

7.2. DP for nonce with low Hamming weight (illustration)

from functools import lru_cache

def recover_d_dp(sigs, w_max=8, bits=256):
    """
    sigs: список (z, r, s)
    Ищем d, при котором все k_i = s_i^{-1}(z_i + r_i d) mod n
    имеют вес Хэмминга <= w_max.
    """
    inv = [(pow(s, -1, n), z, r) for (z, r, s) in sigs]

    @lru_cache(maxsize=None)
    def weight_matches(d):
        return all(
            bin((si * (zi + ri * d)) % n).count("1") <= w_max
            for (si, zi, ri) in inv
        )

    # Простейший перебор по структуре "низкого веса" (учебный пример)
    from itertools import combinations
    for bitset in combinations(range(bits), w_max):
        d = sum(1 << b for b in bitset) % n
        if weight_matches(d):
            return d
    return None

7.3. Knapsack-DP by nonce amount

def knapsack_dp(alpha, beta, S, B=8):
    """
    Ищем d такое, что (A + B*d) mod n <= S.
    alpha, beta: списки коэффициентов; A = sum(alpha), B = sum(beta) mod n
    ДП по байтам d_j.
    """
    A = sum(alpha) % n
    Bsum = sum(beta) % n
    K = 256 // B

    # dp: словарь (partial_sum_hi, carry) -> list of d_low
    # Упрощённая схема: перебираем байты, храним (sum mod n, d_so_far)
    states = {0: [0]}   # sum mod n -> список d
    mask = (1 << B) - 1
    for j in range(K):
        new_states = {}
        for s_val, ds in states.items():
            for dj in range(256):
                nv = (s_val + dj * Bsum * pow(2, B*j, n)) % n
                new_states.setdefault(nv, [])
                if len(new_states[nv]) < 64:   # prune
                    new_states[nv].extend([(d << B) | dj for d in ds[:4]])
        states = new_states
    # финальный фильтр
    results = []
    for s_val, ds in states.items():
        for d in ds:
            if ((A + Bsum * d) % n) <= S:
                results.append(d)
    return results

7.4. Tree-decomposition of DP (conceptual example)

def tree_dp_lcg(kappas, alpha, beta, a, b, L=16):
    """
    k_{i+1} = a*k_i + b mod n; известны младшие L бит kappas[i] = k_i mod 2^L.
    Возвращаем d, согласованное со всеми подписями.
    """
    m = len(kappas)
    mask = (1 << L) - 1

    # Таблицы для каждого узла: (k_i_low, d_low) -> set of (k_i mod n) candidates
    # Здесь — упрощённая схема для illustration.
    candidates = {}
    for i in range(m):
        si, zi, ri = alpha[i], beta[i], 0  # заглушка для демонстрации структуры
        # ... заполнение таблиц ДП по цепи ...
    return candidates  # список d-кандидатов

Note:  The fragments shown are for training purposes. In real attacks, the amount of computation required requires C++/Rust and optimized structures (Bloom filters, partitioning, GPU). However, the principle is the same: replace exponential search with a structured DP table.

8. Limitations, Countermeasures, and Conclusions

8.1 Comparison with Lattice Methods

MethodLeakageComplexityComment
LLL/BKZ (Boneh–Venkatesan)Most significant bits kiPolynomial with small total leakageDe facto standard
DP by bitsLow Hamming weightExponential by w, but with little basisWorks where lattices do not model discreteness well
Knapsack-DPLimited amountO(m⋅n⋅S)Effective at low S And m
Tree-DPLinear dependenciesO(|T|qtw+1)Breakthrough at tw≤4

8.2. When DP  won’t  help

  • Nonce is cryptographically strong (CSPRNG) – DP is useless.
  • Leakage of high bits at large m — LLL faster.
  • High treewidth (random dependencies) – DP tables explode.
  • Domain size q=n≈2256 does not allow storing tables directly.

8.3. Practical countermeasures (for the defending party)

  1. RFC 6979  – Deterministic nonce based on HMAC-SHA256; eliminates “random” weaknesses.
  2. Hamming weight validation  – reject k With wt(k)<128.
  3. Range Check  – k∈[n/4,3n/4] cuts out many DP scenarios.
  4. Elimination of linear dependencies  – LCG for nonce is prohibited.
  5. Schnorr/BIP-340  is a simpler and more secure signature scheme where HNP attacks are more difficult.

8.4. Summary

Dynamic programming is not a universal replacement for lattice methods, but  a specialized tool  for cryptanalysis of ECDSA under  combinatorial  nonce leaks:

  • small parameter – DP by Hamming weight bits;
  • limited amount – knapsack-DP modulo;
  • low treewidth — tree-decomposition of DP by the equation graph;
  • MITM – “DP in half” of the search space.

By combining these approaches with LLL/BKZ, one can solve problems inaccessible to either pure lattices or brute force. It is at the intersection of these methods that the cutting edge of modern ECDSA cryptanalysis lies.


Disclaimer:  This material is provided for educational and research purposes only: to audit proprietary cryptographic implementations, study HNP theory, and develop secure nonce generators. Applying the described methods to someone else’s keys without the owner’s express permission is punishable by law.