1 of 54

SegWit

2018년 1월 11일

박주형 <jh@kodebox.io>

KODEBOX

2 of 54

목차

1. 블록 사이즈 논쟁의 역사

  • Scalability
  • 첫 번째 제안
  • Bitcoin XT
  • 반대파
  • 중국
  • SegWit

2. SegWit

  • txid, wtxid
  • 새로운 스크립트
  • 새로운 블록 사이즈
  • Commitment Structure
  • Transaction Malleability

3. SegWit의 영향

  • Micropayment Channel
  • Script Version Up
  • Pruning

3 of 54

블록 사이즈 논쟁의 역사

4 of 54

블록 사이즈 제한: 1MB

사토시가 아무말 없이 2010년 7월에 블록의 1MB제한을 추가

의도를 밝히진 않았지만 DOS 공격을 막기 위해서였던 것으로 추측

Satoshi once told me, "I think most P2P networks, and websites for that matter, are vulnerable to an endless number of DoS attacks. The best we can realistically do is limit the worst cases."

5 of 54

첫 번째 제안 (2010년 10월 3일)

Jeff Garzik�Contributor to Bitcoin Core

We should be able to at least match Paypal's average transaction rate...

6 of 54

diff --git a/main.h b/main.h

index c5a0127..c92592a 100644

--- a/main.h

+++ b/main.h

@@ -14,7 +14,10 @@ class CBlockIndex;

class CWalletTx;

class CKeyItem;

-static const unsigned int MAX_BLOCK_SIZE = 1000000;

+static const unsigned int TX_PER_MINUTE = 1400;

+static const unsigned int TX_AVG_SIZE_GUESS = 256;

+static const unsigned int MAX_BLOCK_SIZE =

+ TX_PER_MINUTE * TX_AVG_SIZE_GUESS * 10 * 2;

7 of 54

Satoshi says

+1 theymos. Don't use this patch, it'll make you incompatible with the network, to your own detriment.

We can phase in a change later if we get closer to needing it.

8 of 54

Bitcoin Scalability

9 of 54

Bitcoin Scalability

10 of 54

Bitcoin Scalability

11 of 54

1월 7일 기준 수수료

일반적인 트랜잭션 사이즈(median) : 226 byte

2,000원의 수수료를 내면 최대 21시간의 딜레이

20,000원의 수수료를 내면 최대 1시간의 딜레이

소액결제가 불가능한 시스템

12 of 54

BIP-101 & Bitcoin xt

Gavin Andresen

Bitcoin lead developer (2010~2014)

프로토콜에 제한을 두지 말자

“There are limits on routing table sizes, but they are not top-down-specified-in-a-standards-document protocol limits. They are organic limits that arise from whatever hardware is available and from the (sometimes very contentious!) interaction of the engineers keeping the Internet backbone up and running.”

“Trust that smart developers will fix scaling or denial-of-service issues as they arise”

13 of 54

BIP 101

This BIP proposes replacing the fixed one megabyte maximum block size with a maximum size that grows over time at a predictable rate.

블록 사이즈 리밋을 즉시 8메가로 수정

2년마다 2배로 늘리기

2016년 1월 11일에 75% 이상의 해시파워가 동의하면 진행

14 of 54

15 of 54

블록 사이즈 투표

16 of 54

비트코인 커미터들

2015년 당시 커미터 5 명 중 권한이 큰 2명이 하드포크를 통한 블록사이즈 늘리기에 반대

  • Gavin Andresen
  • Jeff Garzik
  • Wladimir van der Laan (the official maintainer, the man who does releases)
  • Gregory Maxwell (Blockstream)
  • Pieter Wuille (Blockstream)

17 of 54

Wladimir van der Laan

(2014/8~) Bitcoin Lead maintainer

I mostly have a problem with proposals that bake in expected exponential bandwidth growth. I don’t think it’s realistic. If we’ve learned anything from the 2008 subprime bubble crisis it should be that nothing ever keeps growing exponentially, and assuming so can be hazardous. It reduces a complex geographical issue, the distribution of internet connectivity over the planet for a long time to come, to a simple function.

18 of 54

Wladimir van der Laan

(2014/8~) Bitcoin Lead maintainer

On the other hand a hardfork is extremely hard to coordinate. Even one that just involves changing one parameter. Everyone with a full node has to upgrade. This is not something that can be done regularly. Certainly not with such a near time horizon. Changing the rules in a decentralized consensus system is a very difficult problem and I don’t think we’ll resolve it any time soon.

19 of 54

China Great Firewall

Pan zhibiao(bitmain)

“I personally think that the blocksize topic has conflicts with the Firewall of China,I think the current BIP 100 proposal would be good, but we need a better solution for the Great Firewall of China.”

20 of 54

Chinese Mining Pools

21 of 54

중국에 대한 우려

Toomim (Bitcoin classic member)

“Most of the rest of the world can handle large blocks,China, though, cannot. We need to get Chinese pools to take their block transactions outside of China.”

having 65% of the total hashrate based in the region was a “problem”.

“The purpose [of The Great Firewall] is to censor and control information, and that has some problems for bitcoin. It makes me uncomfortable to have so much hashing power subject to that system,” he said.

22 of 54

중국 마이너들의 불만

“We’re getting close to something everyone can agree on, that doesn’t put us in a voting power position, and something that doesn’t scale too quickly,” Long(FinalHash) said.

“Before 2014, over half of the hashing power was in the US. But there was no worry about US committing a 51% attack,” F2Pool’s Wang said.

Zhibiao said. “The core developers shouldn’t have all the discussions and debate and then ask us to vote.”

23 of 54

Hongkong Agreement

2016년 2월 Hongkong Agreement

  • SegWit과 hard-fork의 방향성

2017년 5월 New York Agreement

  • Activate Segregated Witness at an 80% threshold, signaling at bit 4
  • Activate a 2 MB hard fork within six months
  • 58 companies located in 22 countries
  • 83.28% of hashing power
  • 5.1 billion USD monthly on chain transaction volume
  • 20.5 million bitcoin wallets

24 of 54

SegWit

  • Soft fork
  • Fix transaction malleability
  • 1.7~3.7 배의 효과
  • 이후 lightning network같은 offchain solution에 필요

25 of 54

Bitcoin Cash

26 of 54

SegWit2x의 문제

Replay protection 논란

  • Legacy bitcoin에서 만든 트랜잭션이 SegWit2x에서도 유효

Bitcoin Core 의 반대

  • 디자인 리뷰, 스펙 작성 등의 기존 개발 방식을 따르지 않음

27 of 54

SegWit

28 of 54

Review

  • Pubkey script
    • Tx out을 아무나 못 쓰도록 잠그는 역할
    • 코드에서 scriptPubKey라고 부름
  • Signature script, redeem script
    • Pubkey script를 풀어내는 script
    • 코드에서 scriptSig라고 부름

복습

29 of 54

SegWit

  • 하고 싶은 것
    • txid에서 signature script를 빼기
    • Soft fork
  • 영향
    • Transaction serialization format
    • 블록 사이즈 계산법이 바뀜
    • 새로운 standard script
    • Block의 merkle tree를 계산하는 방법

30 of 54

왜?

주 목적

  • 트랜잭션의 signature script를 수정해서 txid만 다른 valid한 트랜잭션을 만들지 못하도록 방지

31 of 54

Soft-fork

  • Backward compatibility를 유지하면서 업그레이드
  • 업그레이드 안한 노드와도 consensus를 유지
  • 대부분의 노드가 upgrade했다는 가정(75~95%)
  • SegWit도 soft fork를 하기 위하여 복잡한 방식을 사용

32 of 54

Serialization Format

  • txin안에 있던 signature 정보를 txin의 바깥으로 뺌
  • 바깥으로 빠진 signature 정보를 witness라고 부름
  • SegWit이전
    • [nVersion][txins][txouts][nLockTime]
  • SegWit 이후
    • [nVersion][marker][flag][txins][txouts][witness][nLockTime]

33 of 54

txid,wtxid

  • txid
    • block explorer에서 흔하게 볼 수 있는 transaction의 id
    • SegWit 이전 : Transaction을 serialization한 해시값
    • SegWit 이후 : 이전 방식대로 serialize한 정보의 해시값
  • wtxid
    • SegWit 이후의 방식으로 serialize한 정보의 해시값
    • transaction 변조를 막기 위하여 wtxid의 머클트리를 블록에 포함
    • wtxid의 머클트리는 coinbase의 scriptPubkey자리에 저장

34 of 54

Script 변화

  • Pubkey script에 새로운 규칙 추가
  • 1 byte push opcode와 2~40byte를 푸시하는 스크립트에 새로운 의미 부여
  • Pushed 1 byted : version byte
  • 2~40 byte data : witness program

35 of 54

P2PKH

Pay To Public Key Hash

scriptPubKey: OP_DUP OP_HASH160 <PubKeyHash> OP_EQUALVERIFY OP_CHECKSIG

scriptSig: <sig> <pubkey>

  • scriptSig 전까지 public key 공개되지 않음
  • 지갑에서 1로 시작하는 주소 (ex. 1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2)

복습

36 of 54

P2WPKH

  • version이 0일 때 && witness program의 크기가 20 byte인 경우
    • P2WPKH(pay-to-witness-public-key-hash)로 인식
    • Witness가 2 item이어야함 signature와 public key
    • Witness의 publickey가 HASH160(witness program)이어야함
    • Witness에 있는 signature와 publickey를 CHECKSIG op으로 검증

37 of 54

P2SH

Pay To Script Hash

scriptPubKey: OP_HASH160 <Hash160(redeem script)> OP_EQUAL

scriptSig: [sig...] <redeemScript>

  • 지갑에서 3으로 시작하는 주소 (ex. 3J98t1WpEZ73CNmQviecrnyiWrnqRhWNLy)

복습

38 of 54

P2WSH

  • Version이 0일 때 && witness program의 크기가 32 byte인 경우
    • P2WSH(pay-to-witness-script-hash)로 인식
    • Witness가 script의 input과 serialized script로 구성
    • SHA256(witnessScript)가 32 byte의 witness program이어야함
    • witnessScript가 deserialize되고,남은 stack data와 함께 실행됨
    • 실행 결과가 stack에 TRUE 하나만 남아있어야함

39 of 54

Soft-fork

  • Legacy node는 witness program을 누구나 가질 수 있는 program으로 인식

  • 실행 결과로 스택의 탑에 0이 아닌 값이 들어있기 때문

40 of 54

새로운 블록 사이즈 계산법

  • Legacy node에게 트랜잭션을 줄 때 signature정보를 빼고 주기 때문에 signature를 제외한 1MB조건만 만족시키면 됨
  • Base size : 이전의 transaction serialization방법으로 serialize했을 때 사이즈
  • Total size : SegWit 이후 serialize 방식을 썼을 때 size
  • Block weight : Base Size * 3 + Total size

41 of 54

새로운 블록 사이즈 계산법

  • 새로운 블락 리밋 : Block weight <= 4MB
  • 이전 방법이었다면
    • 4 * (signature + signature 아닌 데이터) <= 4MB
  • 이후 방법
    • Signature + 4 * signature 아닌 데이터 <= 4MB
  • Base size <= 1MB이므로 legacy node에서도 문제 없이 받아들임
  • 더 많은 데이터를 한 블록에 넣을 수 있음

42 of 54

새로운 블록 사이즈 계산법

이렇게 한 이유

  • Base size를 1MB이하로 유지시키면서 Block weight라는 하나의 값으로 fee를 측정할 수 있음
  • witness영역의 크기 제한과 비-witness영역의 크기 제한을 따로 둔다면 miner가 트랜잭션 선별하기가 어려움

43 of 54

Transaction Serialization of P2SH

44 of 54

블록 헤더

복습

45 of 54

Commitment Structure

  • Merkle tree에 witness 정보를 넣어야 블록에서 witness가 변조 안되게 막을 수 있음
  • 하지만 legacy node를 위해서 merkle tree를 만드는 방식을 바꾸어서는 안됨
  • Coinbase의 새로운 out의 scriptPubKey에 witness의 root hash를 넣는 방식으로 해결
  • Witness rot hash : hashMerkleRoot를 만드는 방식과 똑같은 방식으로 wtxid를 모아서 만듬

46 of 54

Transaction Malleability

  • txid를 계산할 때 signature가 들어간 게 문제
  • 트랜잭션을 전달하는 중 조금 수정하여 동작은 같지만 txid만 다른 트랜잭션을 만들어낼 수 있음

47 of 54

SegWit의 영향

48 of 54

Micropayment Channel

Alice가 Bob에게 잦은 빈도로 적은 양의 돈을 지불하고 싶어 함. 그러나 매 지불마다 트랜잭션을 발생시키면 지불할 양보다 수수료가 더 커지는 문제가 있음

Solution

결제 채널을 열고 닫는 2개의 트랜잭션만 블록체인에 올리고 그 사이에 Off-chain 트랜잭션을 무수히 수행할 수 있음

1 satoshi * 100

복습

49 of 54

Micropayment Channel

Alice가 Bob에게 채널을 열려고 함, 트랜잭션 2개를 생성만 하고 네트워크에 전파하지 않음

Tx 1 (Alice가 계약금을 예치)

Tx 2 (계약금을 Alice에게 환불)

Alice 지갑

Multisig

Multisig

Alice 지갑

scriptPubKey

2 <key A> <key B> 2 CHECKMULTISIG

복습

50 of 54

Micropayment Channel

일정 시간이 지나면 예치금이 환불될 수 있도록 Bob의 서명을 받음

Tx 1 (Alice가 계약금을 예치)

Tx 2 (계약금을 Alice에게 환불)

Alice 지갑

Multisig

Multisig

nSequence +12 시간

Alice 지갑

scriptSig: <sig A> <sig B>

서명 제공

복습

51 of 54

Micropayment Channel

Tx1이 네트워크에 전파되고 Bob은 이를 확인할 수 있음

Tx 1 (Alice가 계약금을 예치)

Tx 2 (계약금을 Alice에게 전액 환불)

Alice 지갑

Multisig

Multisig

Alice 지갑

네트워크에 전파

복습

52 of 54

Micropayment Channel

Tx1이 네트워크에 전파되고 Bob은 이를 확인할 수 있음

Tx 1 (Alice가 계약금을 예치)

Tx 2 (계약금을 Alice에게 전액 환불)

Alice 지갑

Multisig

Multisig

Alice 지갑

네트워크에 전파

네트워크에 전파 중

txid를 변조 가능

최악의 경우 환불 불가능

SegWit을 통하여 해결

53 of 54

Script Version Up

  • pubkey script : <version byte> <witness program>
  • 모르는 버전이 있으면 “누구나 풀 수 있는 스크립트”로 처리
  • 후에 새로운 종류의 스크립트를 추가할 때 간단한 soft fork로 처리 가능

54 of 54

Pruning

  • 검증이 필요 없는 경우 signature 정보를 전달하지 않아도 됨
  • SPV node에게 전달할 때 signature 빼고 전달
  • Checkpoint 이전의 블록들에서 witness 데이터 지우기