Workspace IndexMath › Day 47

Lagrange Interpolation + Reed-Solomon (Thread A Payoff) TODO

Math · Day 47 / 52 · December — Cryptography & Information Theory (Day 44-52)

Concept

Given k distinct points, a polynomial of degree at most k-1 is uniquely determined, and Lagrange interpolation constructs it explicitly by combining basis polynomials that equal 1 at one point and 0 at all the others. Reed-Solomon codes apply this fact directly to encoding: treat k data symbols as the coefficients of a polynomial, evaluate it at n distinct points, and use those values as the codeword — then any k of the n evaluations are enough to recover the original polynomial by interpolation. That makes it an MDS code with minimum distance n-k+1, able to recover from up to n-k erasures, and to correct errors at unknown positions up to half that many. The same structure underlies Shamir's secret sharing: put the secret in the constant term, hand out evaluations of a degree-(k-1) polynomial, and fewer than k shares reveal no information about the secret at all.

Using erasure codes instead of replication gets the same durability at a much lower storage cost, making it a fundamental tool for storage and transmission design; threshold signatures and data availability designs are both built on this same polynomial logic.

Code & Formula

# 라그랑주 보간 + Reed-Solomon — GF(p) 위에서 k=3,n=5 RS 인코딩 후 소실 2개 복구
# k개의 점으로 차수 k-1 다항식이 유일 결정된다는 사실을 그대로 부호화/복호화에 사용한다.

p = 97  # 작은 소수 유한체 GF(97)

def gf_inv(x):
    return pow(x, -1, p)

def poly_eval(coeffs, x):
    """coeffs[i]는 x^i의 계수. Horner's method로 f(x) mod p 계산."""
    y = 0
    for c in reversed(coeffs):
        y = (y * x + c) % p
    return y

def lagrange_interpolate(points, x_target=0):
    """points = [(x_i, y_i), ...] 로부터 f(x_target)을 복원 (기본: 상수항 f(0))."""
    total = 0
    for i, (xi, yi) in enumerate(points):
        num, den = 1, 1
        for j, (xj, _) in enumerate(points):
            if i == j:
                continue
            num = (num * (x_target - xj)) % p
            den = (den * (xi - xj)) % p
        total = (total + yi * num * gf_inv(den)) % p
    return total

# 원본 데이터 3개 심볼(k=3)을 다항식 계수로 삼는다: f(x) = c0 + c1*x + c2*x^2
secret_data = [17, 42, 5]  # c0=17(예: 복원 대상), c1=42, c2=5
k, n = 3, 5

# n=5개의 서로 다른 평가점(1..5)에서 계산한 값이 코드워드(RS 부호)
codeword = [(x, poly_eval(secret_data, x)) for x in range(1, n + 1)]
print("Reed-Solomon 코드워드 (x, f(x)):", codeword)

# 5개 중 2개(x=2, x=4)가 소실됐다고 가정 — k=3개만 있으면 복원 가능해야 한다
surviving = [pt for pt in codeword if pt[0] not in (2, 4)]
print("소실 후 살아남은 점:", surviving)

recovered_c0 = lagrange_interpolate(surviving, x_target=0)
print(f"라그랑주 보간으로 복원한 f(0)=c0: {recovered_c0}  (원본과 일치: {recovered_c0 == secret_data[0]})")

# 전체 다항식(3개 계수) 자체도 세 점으로 완전히 복원되는지 확인 (x=0,1,2 세 지점에서 값 비교)
for x_check in (0, 1, 2, 3, 4, 5):
    original = poly_eval(secret_data, x_check)
    via_interp = lagrange_interpolate(surviving, x_target=x_check)
    assert original == via_interp
print("모든 x에서 원본 다항식과 보간 결과 일치 (n-k=2개 소실까지 복구 가능, MDS 부호 성질).")

Exercise

Implement a k=3, n=5 Reed-Solomon encoder and a Lagrange-interpolation decoder over a small finite field, erase any two symbols, and confirm the original is recovered.

Practical Connection

Ethereum's blob data availability, KZG polynomial commitments, and threshold signatures for splitting oracle/relayer keys all use this interpolation-and-erasure-code structure, making it directly relevant background for designing Verex's oracle trust model.

If you study this on a given day, add a note link and a ✅ to this line in the source curriculum (docs/knowledge/math-50-curriculum.md) and this spot will lead straight to the note body. You can also write directly on this page — but regenerating overwrites it, so it's safer to keep anything you want to save as markdown under docs/algorithms/.


한국어

라그랑주 보간 + Reed-Solomon (스레드 A 수확) TODO

Math · Day 47 / 52 · 12월 — 암호학·정보이론 (Day 44–52)

개념

서로 다른 k개의 점이 주어지면 차수가 k-1 이하인 다항식이 유일하게 결정되고, 라그랑주 보간은 각 점에서만 1이고 나머지 점에서 0이 되는 기저 다항식을 조합해 그 다항식을 명시적으로 구성한다. Reed-Solomon 부호는 이 사실을 그대로 부호화에 쓴다. k개의 데이터 심볼을 다항식의 계수로 보고 서로 다른 n개의 점에서 평가한 값을 코드워드로 삼으면, n개 중 임의의 k개만 살아남아도 보간으로 원래 다항식을 복원할 수 있다. 그래서 이 부호는 최소 거리가 n-k+1인 MDS 부호가 되어 최대 n-k개의 소실을 복구하고, 위치를 모르는 오류는 그 절반까지 정정한다. 같은 구조가 Shamir의 비밀 분산에도 쓰이는데, 비밀을 상수항에 두고 k-1차 다항식의 평가값을 나눠 주면 k개 미만의 조각은 비밀에 대해 아무 정보도 주지 않는다.

복제 대신 소실 부호를 쓰면 같은 내구성을 훨씬 적은 저장 비용으로 얻을 수 있어 스토리지·전송 설계의 기본 도구다. 또 임계 서명과 데이터 가용성 설계가 모두 이 다항식 논리 위에 서 있다.

코드 · 수식

# 라그랑주 보간 + Reed-Solomon — GF(p) 위에서 k=3,n=5 RS 인코딩 후 소실 2개 복구
# k개의 점으로 차수 k-1 다항식이 유일 결정된다는 사실을 그대로 부호화/복호화에 사용한다.

p = 97  # 작은 소수 유한체 GF(97)

def gf_inv(x):
    return pow(x, -1, p)

def poly_eval(coeffs, x):
    """coeffs[i]는 x^i의 계수. Horner's method로 f(x) mod p 계산."""
    y = 0
    for c in reversed(coeffs):
        y = (y * x + c) % p
    return y

def lagrange_interpolate(points, x_target=0):
    """points = [(x_i, y_i), ...] 로부터 f(x_target)을 복원 (기본: 상수항 f(0))."""
    total = 0
    for i, (xi, yi) in enumerate(points):
        num, den = 1, 1
        for j, (xj, _) in enumerate(points):
            if i == j:
                continue
            num = (num * (x_target - xj)) % p
            den = (den * (xi - xj)) % p
        total = (total + yi * num * gf_inv(den)) % p
    return total

# 원본 데이터 3개 심볼(k=3)을 다항식 계수로 삼는다: f(x) = c0 + c1*x + c2*x^2
secret_data = [17, 42, 5]  # c0=17(예: 복원 대상), c1=42, c2=5
k, n = 3, 5

# n=5개의 서로 다른 평가점(1..5)에서 계산한 값이 코드워드(RS 부호)
codeword = [(x, poly_eval(secret_data, x)) for x in range(1, n + 1)]
print("Reed-Solomon 코드워드 (x, f(x)):", codeword)

# 5개 중 2개(x=2, x=4)가 소실됐다고 가정 — k=3개만 있으면 복원 가능해야 한다
surviving = [pt for pt in codeword if pt[0] not in (2, 4)]
print("소실 후 살아남은 점:", surviving)

recovered_c0 = lagrange_interpolate(surviving, x_target=0)
print(f"라그랑주 보간으로 복원한 f(0)=c0: {recovered_c0}  (원본과 일치: {recovered_c0 == secret_data[0]})")

# 전체 다항식(3개 계수) 자체도 세 점으로 완전히 복원되는지 확인 (x=0,1,2 세 지점에서 값 비교)
for x_check in (0, 1, 2, 3, 4, 5):
    original = poly_eval(secret_data, x_check)
    via_interp = lagrange_interpolate(surviving, x_target=x_check)
    assert original == via_interp
print("모든 x에서 원본 다항식과 보간 결과 일치 (n-k=2개 소실까지 복구 가능, MDS 부호 성질).")

연습

작은 유한체 위에서 k=3, n=5인 Reed-Solomon 인코더와 라그랑주 보간 디코더를 직접 구현해, 임의의 2개 심볼을 지운 뒤 원본이 복원되는지 확인하라.

실무 · Verex 연결

이더리움의 블롭 데이터 가용성과 KZG 다항식 커밋먼트, 오라클·릴레이어 키를 나눠 갖는 임계 서명이 모두 이 보간·소실 부호 구조를 쓰므로, Verex의 오라클 신뢰 모델을 설계할 때 직접적인 배경 지식이 된다.

공부한 날 원본 커리큘럼(docs/knowledge/math-50-curriculum.md)의 이 줄에 노트 링크와 ✅ 를 붙이면, 이 자리는 노트 본문으로 바로 이어집니다. 노트 없이 이 페이지에 바로 적어도 됩니다 — 다만 다시 생성하면 덮어쓰이므로, 남길 글은 docs/algorithms/ 의 마크다운으로 쓰는 편이 안전합니다.

← 46. ECC·디지털 서명48. 페어링/KZG(개념) →