Workspace IndexAlgorithms › Day 58

Nakamoto Consensus's Probabilistic Finality and Selfish Mining TODO

Algorithms · Day 58 / 100 · D. Distributed Systems & Consensus (Day 52-68)

Concept

Nakamoto consensus produces blocks via proof of work and treats the chain with the greatest cumulative work as canonical — finality here isn't absolute, it's probabilistic. The more honest blocks get stacked on top of a given block, the bigger the gap an attacker has to make up to revert it, so the probability of reversion decreases exponentially as confirmations accumulate. This guarantee holds only under the assumptions that the attacker's hash power is less than the honest majority's and that network propagation is fast enough. Selfish mining is a strategy where a miner withholds a mined block instead of publishing it immediately, keeping a secret chain, then releases it strategically when an honest block appears, invalidating honest miners' work. This strategy shows that an attacker can earn a reward share above their actual hash-power share even well below a majority, revealing that a protocol's incentive-compatibility is a separate question from its safety threshold.

How many confirmations to wait for is a decision that converts a safety parameter into money, and the existence of incentive-based attacks means an honest-majority assumption alone can't justify a system's safety.

Code & Formula

# 나카모토 합의의 확률적 최종성 — 공격자 해시파워 비율과 확인 수(confirmation)에 따른
# 되돌림(reorg) 성공 확률을 랜덤 워크 시뮬레이션으로 추정한다 (selfish mining 없이 정직한 다수 가정).

import random

random.seed(11)

def simulate_reorg_attempt(attacker_ratio, confirmations, max_steps=10000):
    """정직한 체인이 confirmations만큼 앞서 있을 때, 공격자가 따라잡는지 랜덤 워크로 시뮬레이션.
    lead > 0: 정직한 체인이 앞선 블록 수. 공격자가 lead를 0 이하로 만들면 추월 성공."""
    lead = confirmations
    for _ in range(max_steps):
        if random.random() < attacker_ratio:
            lead -= 1  # 공격자가 블록을 캔다
        else:
            lead += 1  # 정직한 채굴자가 블록을 캔다
        if lead <= 0:
            return True  # 공격자가 따라잡음 (reorg 성공)
        if lead > confirmations + 50:
            return False  # 격차가 충분히 벌어져 사실상 안전
    return False

def estimate_reorg_probability(attacker_ratio, confirmations, trials=2000):
    successes = sum(
        simulate_reorg_attempt(attacker_ratio, confirmations) for _ in range(trials)
    )
    return successes / trials

print("공격자 해시파워 비율별, 확인 수(confirmation)에 따른 되돌림 성공 확률 (시뮬레이션):\n")
for attacker_ratio in [0.10, 0.30, 0.45]:
    print(f"attacker_ratio = {attacker_ratio}")
    for conf in [1, 3, 6]:
        p = estimate_reorg_probability(attacker_ratio, conf, trials=1000)
        print(f"  confirmations={conf}: 되돌림 확률 ≈ {p*100:.1f}%")
    print()

print("-> 확인 수가 늘수록, 공격자 비율이 낮을수록 되돌림 확률이 지수적으로 감소한다.")
print("   (해시파워가 정직한 쪽보다 크면(>=50%) 확인 수와 무관하게 결국 따라잡는다.)")

Exercise

Write a script that takes an attacker's hash-power share and a confirmation count as input and estimates the probability of a successful reversion via a random-walk simulation, then plot the probability curve against confirmation count.

Practical Connection

In a prediction market, deciding how many confirmations to require before crediting a deposit or finalizing settlement has to weigh the probabilistic-finality curve against the amount at stake — and the same question resurfaces, just reshaped into finality rules and reorg risk, on a proof-of-stake chain.

If you study this on a given day, add a note link and a ✅ to this line in the source curriculum (docs/knowledge/dev-100-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/.


한국어

나카모토 합의의 확률적 최종성과 selfish mining TODO

Algorithms · Day 58 / 100 · D. 분산시스템·합의 (Day 52–68)

개념

나카모토 합의는 작업증명으로 블록을 생성하고 가장 누적 작업량이 큰 체인을 정본으로 삼는 규칙이며, 여기서 최종성은 절대적이지 않고 확률적이다. 어떤 블록 위에 정직한 블록이 더 쌓일수록 공격자가 그 블록을 되돌리기 위해 따라잡아야 할 격차가 커지므로, 되돌림 확률은 확인 수가 늘어남에 따라 지수적으로 감소한다. 이 보장은 공격자의 해시파워가 정직한 쪽보다 작다는 가정과 네트워크 전파가 충분히 빠르다는 가정 위에서만 성립한다. selfish mining은 채굴한 블록을 즉시 공개하지 않고 비밀 체인을 유지하다가 정직한 블록이 나오면 전략적으로 공개해, 정직한 채굴자들의 작업을 무효화시키는 전략이다. 이 전략은 공격자가 전체 해시파워의 과반에 크게 못 미치더라도 자기 지분보다 높은 보상 비율을 얻을 수 있음을 보여, 프로토콜의 인센티브 호환성이 안전성 임계값과 별개의 문제임을 드러낸다.

몇 확인을 기다려야 하는가는 안전 파라미터를 돈으로 환산하는 결정이며, 인센티브 공격이 존재한다는 사실은 다수 정직 가정만으로 시스템을 정당화할 수 없음을 뜻한다.

코드 · 수식

# 나카모토 합의의 확률적 최종성 — 공격자 해시파워 비율과 확인 수(confirmation)에 따른
# 되돌림(reorg) 성공 확률을 랜덤 워크 시뮬레이션으로 추정한다 (selfish mining 없이 정직한 다수 가정).

import random

random.seed(11)

def simulate_reorg_attempt(attacker_ratio, confirmations, max_steps=10000):
    """정직한 체인이 confirmations만큼 앞서 있을 때, 공격자가 따라잡는지 랜덤 워크로 시뮬레이션.
    lead > 0: 정직한 체인이 앞선 블록 수. 공격자가 lead를 0 이하로 만들면 추월 성공."""
    lead = confirmations
    for _ in range(max_steps):
        if random.random() < attacker_ratio:
            lead -= 1  # 공격자가 블록을 캔다
        else:
            lead += 1  # 정직한 채굴자가 블록을 캔다
        if lead <= 0:
            return True  # 공격자가 따라잡음 (reorg 성공)
        if lead > confirmations + 50:
            return False  # 격차가 충분히 벌어져 사실상 안전
    return False

def estimate_reorg_probability(attacker_ratio, confirmations, trials=2000):
    successes = sum(
        simulate_reorg_attempt(attacker_ratio, confirmations) for _ in range(trials)
    )
    return successes / trials

print("공격자 해시파워 비율별, 확인 수(confirmation)에 따른 되돌림 성공 확률 (시뮬레이션):\n")
for attacker_ratio in [0.10, 0.30, 0.45]:
    print(f"attacker_ratio = {attacker_ratio}")
    for conf in [1, 3, 6]:
        p = estimate_reorg_probability(attacker_ratio, conf, trials=1000)
        print(f"  confirmations={conf}: 되돌림 확률 ≈ {p*100:.1f}%")
    print()

print("-> 확인 수가 늘수록, 공격자 비율이 낮을수록 되돌림 확률이 지수적으로 감소한다.")
print("   (해시파워가 정직한 쪽보다 크면(>=50%) 확인 수와 무관하게 결국 따라잡는다.)")

연습

공격자 해시파워 비율과 확인 수를 입력받아 되돌림 성공 확률을 랜덤 워크 시뮬레이션으로 추정하는 스크립트를 짜고, 확인 수에 따른 확률 곡선을 그려 보라.

실무 · Verex 연결

예측시장에서 입금 인정이나 정산 확정을 몇 확인 뒤에 할지는 확률적 최종성 곡선과 걸린 금액을 함께 놓고 정해야 하며, 지분증명 체인이라면 같은 질문이 확정성 규칙과 재구성 위험으로 형태만 바뀌어 남는다.

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

← 57. DAG 합의59. Casper FFG + LMD-GHOST →