124
BC 2 Jeremy Rubin

Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BC2

Jeremy Rubin

概要Overview

bull 3つの課題

1 Bitcoin開発プロセスの紹介

2 Bitcoin Improvement Proposals (BIP) の紹介

3 Bitcoin性能の開発

bull 3 Major Sections

1 Intro Bitcoin Development Process

2 Intro to Bitcoin Improvement Proposals

3 Bitcoin Performance Engineering

Bitcoin開発プロセスの紹介

Intro to Bitcoin Development

BitcoinデベロッパーになるのかSo You Want to Be a Bitcoin Developer

bull 基礎bull 開発環境bull はじめての Bitcoinコードbull 貢献bull 基本アドバイス

bull Foundationsbull Development Environmentbull Beginning to Code Bitcoinbull Contributingbull General Advice

基礎FOUNDATIONS

開発の考え方を理解するUnderstand Development Philosophy

bull 様々な Bitcoinユーザをリスペクトするbull 自分の問題は自分で解決するbull Bitcoinの利用は言論の自由bull ゆっくりと着実なbull 同じプロジェクトでもそれぞれの目的は違うかも

bull Respect all kinds of Bitcoin usersbull Scratch your own itchbull Bitcoin use is free speechbull Slow and steadybull Not everyone has same goal for project

コミュニケーションCommunications

bull おそらく誰かが同じ質問を聞いた

bull 他のデベロッパーは現在何をディスカッションしているのかに気を使う

ndashいろんなオンラインフォーラムは Bitcoin開発HQと思われる

bull Someone already probably asked your question online

bull Be respectful of what other developers are working on or currently discussing

ndash The various forums are like Bitcoin Dev HQ

コミュニケーションCommunications

bull bitcoincoreslackcomに参加するbull IRC チャネル

ndash bitcoin bitcoin-wizards bitcoin-core-devndash 週1回の会議は bitcoin-core-devにて

bull githubcombitcoinbitcoinをフォローするbull Linux Foundation のメーリングリストに参加する

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

bull Join bitcoincoreslackcombull IRC channels

ndash bitcoin bitcoin-wizards bitcoin-core-devndash Weekly meeting in bitcoin-core-dev

bull Follow githubcombitcoinbitcoinbull Join Linux Foundation mailing lists

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 2: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

概要Overview

bull 3つの課題

1 Bitcoin開発プロセスの紹介

2 Bitcoin Improvement Proposals (BIP) の紹介

3 Bitcoin性能の開発

bull 3 Major Sections

1 Intro Bitcoin Development Process

2 Intro to Bitcoin Improvement Proposals

3 Bitcoin Performance Engineering

Bitcoin開発プロセスの紹介

Intro to Bitcoin Development

BitcoinデベロッパーになるのかSo You Want to Be a Bitcoin Developer

bull 基礎bull 開発環境bull はじめての Bitcoinコードbull 貢献bull 基本アドバイス

bull Foundationsbull Development Environmentbull Beginning to Code Bitcoinbull Contributingbull General Advice

基礎FOUNDATIONS

開発の考え方を理解するUnderstand Development Philosophy

bull 様々な Bitcoinユーザをリスペクトするbull 自分の問題は自分で解決するbull Bitcoinの利用は言論の自由bull ゆっくりと着実なbull 同じプロジェクトでもそれぞれの目的は違うかも

bull Respect all kinds of Bitcoin usersbull Scratch your own itchbull Bitcoin use is free speechbull Slow and steadybull Not everyone has same goal for project

コミュニケーションCommunications

bull おそらく誰かが同じ質問を聞いた

bull 他のデベロッパーは現在何をディスカッションしているのかに気を使う

ndashいろんなオンラインフォーラムは Bitcoin開発HQと思われる

bull Someone already probably asked your question online

bull Be respectful of what other developers are working on or currently discussing

ndash The various forums are like Bitcoin Dev HQ

コミュニケーションCommunications

bull bitcoincoreslackcomに参加するbull IRC チャネル

ndash bitcoin bitcoin-wizards bitcoin-core-devndash 週1回の会議は bitcoin-core-devにて

bull githubcombitcoinbitcoinをフォローするbull Linux Foundation のメーリングリストに参加する

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

bull Join bitcoincoreslackcombull IRC channels

ndash bitcoin bitcoin-wizards bitcoin-core-devndash Weekly meeting in bitcoin-core-dev

bull Follow githubcombitcoinbitcoinbull Join Linux Foundation mailing lists

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 3: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Bitcoin開発プロセスの紹介

Intro to Bitcoin Development

BitcoinデベロッパーになるのかSo You Want to Be a Bitcoin Developer

bull 基礎bull 開発環境bull はじめての Bitcoinコードbull 貢献bull 基本アドバイス

bull Foundationsbull Development Environmentbull Beginning to Code Bitcoinbull Contributingbull General Advice

基礎FOUNDATIONS

開発の考え方を理解するUnderstand Development Philosophy

bull 様々な Bitcoinユーザをリスペクトするbull 自分の問題は自分で解決するbull Bitcoinの利用は言論の自由bull ゆっくりと着実なbull 同じプロジェクトでもそれぞれの目的は違うかも

bull Respect all kinds of Bitcoin usersbull Scratch your own itchbull Bitcoin use is free speechbull Slow and steadybull Not everyone has same goal for project

コミュニケーションCommunications

bull おそらく誰かが同じ質問を聞いた

bull 他のデベロッパーは現在何をディスカッションしているのかに気を使う

ndashいろんなオンラインフォーラムは Bitcoin開発HQと思われる

bull Someone already probably asked your question online

bull Be respectful of what other developers are working on or currently discussing

ndash The various forums are like Bitcoin Dev HQ

コミュニケーションCommunications

bull bitcoincoreslackcomに参加するbull IRC チャネル

ndash bitcoin bitcoin-wizards bitcoin-core-devndash 週1回の会議は bitcoin-core-devにて

bull githubcombitcoinbitcoinをフォローするbull Linux Foundation のメーリングリストに参加する

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

bull Join bitcoincoreslackcombull IRC channels

ndash bitcoin bitcoin-wizards bitcoin-core-devndash Weekly meeting in bitcoin-core-dev

bull Follow githubcombitcoinbitcoinbull Join Linux Foundation mailing lists

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 4: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BitcoinデベロッパーになるのかSo You Want to Be a Bitcoin Developer

bull 基礎bull 開発環境bull はじめての Bitcoinコードbull 貢献bull 基本アドバイス

bull Foundationsbull Development Environmentbull Beginning to Code Bitcoinbull Contributingbull General Advice

基礎FOUNDATIONS

開発の考え方を理解するUnderstand Development Philosophy

bull 様々な Bitcoinユーザをリスペクトするbull 自分の問題は自分で解決するbull Bitcoinの利用は言論の自由bull ゆっくりと着実なbull 同じプロジェクトでもそれぞれの目的は違うかも

bull Respect all kinds of Bitcoin usersbull Scratch your own itchbull Bitcoin use is free speechbull Slow and steadybull Not everyone has same goal for project

コミュニケーションCommunications

bull おそらく誰かが同じ質問を聞いた

bull 他のデベロッパーは現在何をディスカッションしているのかに気を使う

ndashいろんなオンラインフォーラムは Bitcoin開発HQと思われる

bull Someone already probably asked your question online

bull Be respectful of what other developers are working on or currently discussing

ndash The various forums are like Bitcoin Dev HQ

コミュニケーションCommunications

bull bitcoincoreslackcomに参加するbull IRC チャネル

ndash bitcoin bitcoin-wizards bitcoin-core-devndash 週1回の会議は bitcoin-core-devにて

bull githubcombitcoinbitcoinをフォローするbull Linux Foundation のメーリングリストに参加する

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

bull Join bitcoincoreslackcombull IRC channels

ndash bitcoin bitcoin-wizards bitcoin-core-devndash Weekly meeting in bitcoin-core-dev

bull Follow githubcombitcoinbitcoinbull Join Linux Foundation mailing lists

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 5: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

基礎FOUNDATIONS

開発の考え方を理解するUnderstand Development Philosophy

bull 様々な Bitcoinユーザをリスペクトするbull 自分の問題は自分で解決するbull Bitcoinの利用は言論の自由bull ゆっくりと着実なbull 同じプロジェクトでもそれぞれの目的は違うかも

bull Respect all kinds of Bitcoin usersbull Scratch your own itchbull Bitcoin use is free speechbull Slow and steadybull Not everyone has same goal for project

コミュニケーションCommunications

bull おそらく誰かが同じ質問を聞いた

bull 他のデベロッパーは現在何をディスカッションしているのかに気を使う

ndashいろんなオンラインフォーラムは Bitcoin開発HQと思われる

bull Someone already probably asked your question online

bull Be respectful of what other developers are working on or currently discussing

ndash The various forums are like Bitcoin Dev HQ

コミュニケーションCommunications

bull bitcoincoreslackcomに参加するbull IRC チャネル

ndash bitcoin bitcoin-wizards bitcoin-core-devndash 週1回の会議は bitcoin-core-devにて

bull githubcombitcoinbitcoinをフォローするbull Linux Foundation のメーリングリストに参加する

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

bull Join bitcoincoreslackcombull IRC channels

ndash bitcoin bitcoin-wizards bitcoin-core-devndash Weekly meeting in bitcoin-core-dev

bull Follow githubcombitcoinbitcoinbull Join Linux Foundation mailing lists

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 6: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

開発の考え方を理解するUnderstand Development Philosophy

bull 様々な Bitcoinユーザをリスペクトするbull 自分の問題は自分で解決するbull Bitcoinの利用は言論の自由bull ゆっくりと着実なbull 同じプロジェクトでもそれぞれの目的は違うかも

bull Respect all kinds of Bitcoin usersbull Scratch your own itchbull Bitcoin use is free speechbull Slow and steadybull Not everyone has same goal for project

コミュニケーションCommunications

bull おそらく誰かが同じ質問を聞いた

bull 他のデベロッパーは現在何をディスカッションしているのかに気を使う

ndashいろんなオンラインフォーラムは Bitcoin開発HQと思われる

bull Someone already probably asked your question online

bull Be respectful of what other developers are working on or currently discussing

ndash The various forums are like Bitcoin Dev HQ

コミュニケーションCommunications

bull bitcoincoreslackcomに参加するbull IRC チャネル

ndash bitcoin bitcoin-wizards bitcoin-core-devndash 週1回の会議は bitcoin-core-devにて

bull githubcombitcoinbitcoinをフォローするbull Linux Foundation のメーリングリストに参加する

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

bull Join bitcoincoreslackcombull IRC channels

ndash bitcoin bitcoin-wizards bitcoin-core-devndash Weekly meeting in bitcoin-core-dev

bull Follow githubcombitcoinbitcoinbull Join Linux Foundation mailing lists

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 7: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

コミュニケーションCommunications

bull おそらく誰かが同じ質問を聞いた

bull 他のデベロッパーは現在何をディスカッションしているのかに気を使う

ndashいろんなオンラインフォーラムは Bitcoin開発HQと思われる

bull Someone already probably asked your question online

bull Be respectful of what other developers are working on or currently discussing

ndash The various forums are like Bitcoin Dev HQ

コミュニケーションCommunications

bull bitcoincoreslackcomに参加するbull IRC チャネル

ndash bitcoin bitcoin-wizards bitcoin-core-devndash 週1回の会議は bitcoin-core-devにて

bull githubcombitcoinbitcoinをフォローするbull Linux Foundation のメーリングリストに参加する

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

bull Join bitcoincoreslackcombull IRC channels

ndash bitcoin bitcoin-wizards bitcoin-core-devndash Weekly meeting in bitcoin-core-dev

bull Follow githubcombitcoinbitcoinbull Join Linux Foundation mailing lists

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 8: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

コミュニケーションCommunications

bull bitcoincoreslackcomに参加するbull IRC チャネル

ndash bitcoin bitcoin-wizards bitcoin-core-devndash 週1回の会議は bitcoin-core-devにて

bull githubcombitcoinbitcoinをフォローするbull Linux Foundation のメーリングリストに参加する

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

bull Join bitcoincoreslackcombull IRC channels

ndash bitcoin bitcoin-wizards bitcoin-core-devndash Weekly meeting in bitcoin-core-dev

bull Follow githubcombitcoinbitcoinbull Join Linux Foundation mailing lists

ndash bitcoin-core-dev bitcoin-dev bitcoin-discuss

bull Bitcoin StackExchange

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 9: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

開発環境DEVELOPMENT ENVIRONMENT

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 10: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

フォーククローンビルドFork Clone Build

bull `git clone gitgithubcombitcoinbitcoingit`ndashそれとも自分のフォークでやる

bull `git checkout ndashb my-devel-branch`

bull ビルド手順通りにビルドする(1回目は時間がかかる)

bull `git clone gitgithubcombitcoinbitcoingit`

ndash or your own fork

bull `git checkout ndashb my-devel-branch`

bull Follow build instructions (first build is slow)

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 11: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Bitcoin Nodeを実行するRun Bitcoin Nodes

bull 先ほどコンパイルしたバイナリーをコピーするndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench`はノードを実行する `bitcoin-cli`を使ってテストする

bull Testnet ノード `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`

bull 複数のサーバが持ってれば便利

bull Copy the binaries you just compiledndash srcbitcoind and srcbitcoin-cli

bull `bitcoind -debug=bench` will run a node use `bitcoin-cli` to test itbull Testnet node `bitcoind -testnet -debug=bench` `bitcoin-cli -testnet`bull Useful if you have a few servers to develop on

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 12: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

はじめてのBITCOIN開発BEGINNING TO CODE BITCOIN

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 13: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

良いのldquo悪い考えrdquoを選ぶPick a Good ldquoBad Ideardquo

bull 私のはじめてのプロジェクトndash DoSを防ぐためにDBのエントリーをランダム化するndash 概念実証を応用するndash デベロッパーからフィードバックを聞く

bull 悪いことndashいつかDBは反復が出来る順番は欲しいかもndash悪いアクセスのパターンを証明できない

bull 良いことndash勉強の経験

bull My First Projectndash Randomize order of a databases entries to prevent DoS on bad DB access patternndash Implemented a proof of conceptndash Asked a developer for feedback

bull Badndash We may eventually want DB iterable in orderndash Couldnrsquot demonstrate an example of bad access pattern

bull Goodndash Learning experience

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 14: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

C++技術を高めるBuild C++ Expertise

bull BitcoinはC++11で書かれた

bull 始めながらC++11をよく勉強する(最初の25章ぐらい1日1~2章)

bull cppreferencecom

bull C++読むはldquo簡単rdquo書くはldquo難しいrdquo

bull Bitcoin is written in C++11

bull Learn C++11 well as you start (first ~25 chapters or so a chapter or two a day)

bull cppreferencecom

bull C++ ldquoeasyrdquo to read ldquohardrdquo to write

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 15: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

ctags を使うUsing ctags

bull Bitcoinのコードは多い ctagsで早めに見れるbull Vim ですがEmacsAtom 同じことがある

ndash src dir中に `ctags ndashR ` で generate するndash `C-]`で定義に飛んで行く複数のところであれば

`ts`で選択するndash `C-t`で前のところへ行く

bull Bitcoin has a lot of code ctags helps you browse it quicklybull Vim specific but EmacsAtom has equivalent

ndash `ctags ndashR ` in src dir to generate ndash Hit `C-]` in vim to jump to definition `ts` to select if there are multiple

possible locationsndash Hit `C-t` to go back to prior location

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 16: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BitcoinをテストするTesting Bitcoin

bull `make check`でユニットテストを実行するbull `qapull-testerrpc-testspy`でRPCテストを実行するbull Travis CI を設定すると自動的にやっている

bull 新しいテストを書くことと古いテストを読むことでコードの理解を深めるndash Bitcoinのテスト網羅度は良くないけど良くなっているndash 単調な作業じゃないよ

bull `make check` runs unit testsbull `qapull-testerrpc-testspy` to run rpc testsbull Enable Travis CI on your fork for testing to happen automaticallybull Writing new tests amp reading old ones is a great way to ensure you understand how

the code worksndash Bitcoin test coverage is not great but getting betterndash Itrsquos not grunt work

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 17: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

gdblldbを使うUse gdblldb

bull 短いチュートリアルbull 基本的に

ndash 1段ずつコードを見るndash バグを探すndash 実行しているプログラムを検討する

bull 注意コンパイラーがだますことがある

bull Brief Tutorialbull Basically

ndash See what your code is doing step-by-stepndash Find bugsndash Inspect running programs

bull Warning Compiler can play tricks on you

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 18: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

`g++ -std=c++11 -g maincpp`をコンパイルする

Compile `g++ -std=c++11 -g maincpp`

1 void fn(intamp x)

2 ++x

3

4 int main()

5 int x = 0

6 fn(x)

7

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 19: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

これを実行するNow Run

1 gdb --args aout

ndash starts gdb running with aout

2 b fn

ndash sets a breakpoint at fn

3 r

ndash runs aout

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 20: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

gdbノートgdb cheatsheet

bull updownndash jump updown function

callstack

bull continuendash resume executing code till

next breakpoint

bull stepndash take one step through the

program

bull b functionndash breakpoint at function

bull rndash start executing

bull b filelinenondash breakpoint at location

bull p ltxgtndash prints out the variable x

bull info threadndash lists running threads

bull thread ltngtndash switches debugger to

thread n

bull C-X C-andash Shows source code

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 21: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

他のコードをレビューするReview Othersrsquo Code

bull githubcombitcoinbitcoinpulls を見るbull 勉強になること

ndash他の人は何の課題に作業するかndashどんな方法でフィードバックをあげるndashどんなフィードバックをもらえる

bull 役に立てるフィードバックをあげればもらう人はハッピーになる

bull Look through githubcombitcoinbitcoinpullsbull Yoursquoll learn

ndash What topics people are working onndash How people communicate feedbackndash What kinds of feedback people get

bull If you leave useful feedback for someone they will be happy

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 22: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

何が盛ん出るのかを見てみましょうLetrsquos See Whatrsquos Hot

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 23: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

これは私の一つの例Herersquos One of Mine

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 24: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

何が起きたかを見ましょうLetrsquos See What Happened

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 25: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

何が起きたかを見ましょうLetrsquos See What Happened

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 26: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

貢献CONTRIBUTING

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 27: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Bitcoinへの大事な貢献Important Contributions to Bitcoin

bull ドキュメンテーションbull 斬新なアイデアと研究bull 他の人のコードとアイデアのレビューbull 綿密なテストbull カンフェレンス コミュニティの運営bull デベロッパー向けのツールbull 新しいコードを書く

bull Documentationbull Novel ideas and researchbull Review othersrsquo code amp ideasbull Rigorous Testingbull ConferenceCommunity organizingbull Tools for developersbull Write new code

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 28: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

良いコードを書くWrite Good Code

1 大事だと思っている課題を探す2 書く

1 問題を解決できるパッチ2 明確なドキュメンテーション3 コードを含まれるテスト

3 自分のフォークのブランチにプッシュする

1 Find an issue that you think is important2 Write

1 Patches that you think solves it2 Clear documentation3 Tests that cover the code

3 Push to a branch on your fork

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 29: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

早い段階でフィードバックを探すSeek Early Feedback

bull この人にメッセージを送るndash 似たようなことをやっているBitcoinコントリビュータ

ndash TheBlueMatt theuni jonasschnelli と私は優しい窓口

ndash bitcoin-core-devにフィードバックを依頼する

bull 心を広げましょう作業したものの批判はあなた自体の批判じゃない

bull Write a message to

ndash A Bitcoin contributor who works on similar things

ndash TheBlueMatt theuni jonasschnelli and myself are friendly default contacts

ndash ping bitcoin-core-dev with a request for feedback

bull Be gracious Negativity on your work is not negativity to you

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 30: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

新しいノードを実行するRun New Nodes

bull メインとテストネット

ndash違うサーバを使う

ndashデフォルトノードのデバッグログを比較して見てあなたのバージョンの方が良い正しい

bull Main and test net

ndash Recommend using a different server

ndash Compare debug logs to compare to your default nodes Is your version bettercorrect

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 31: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

コード変更の再構築Restructuring Code Changes

bull テストは別のコミットにしましょうndash lsquoTests after Codersquo か lsquoCode after Testsrsquo

bull 意味をなす小さいコミットにしましょうndash 時々いらないコードを書きなおすべきになる

bull 1つのpull-requestに入れすぎないようにndash 10x 改善のコードは1つの2xプラス後の5xの方が良い

bull `git rebase ndashi`を良く使いましょう

bull Tests should be a separate commitndash Either lsquoTests after Codersquo or lsquoCode after Testsrsquo

bull Small commits that individually make sensendash Sometimes you rewrite code you donrsquot actually need to make that work

bull Donrsquot pack too much in one pull-requestndash Better to leave a 10x improvement to an initial 2x and a follow up 5x later

bull `git rebase ndashi` is your friend

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 32: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Githubでpull-requestを開くOpen a Pull-Request on Github

bull 自分のブランチのフォークにTravisが成功したことを確認する

bull 変更の理由と説明を明確に書く

bull 参考のために他のmergeされたPRを見る

bull Make sure Travis is enabled and passing on your fork for your branch

bull Write up a few paragraphs motivating and describing the changes

bull Look at other merged PRs for examples

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 33: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

待つことWaiting Game

bull レビューは時間かかる

bull フィードバックをもらう時点に返事をする

bull Review takes time

bull Respond to feedback as you get it

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 34: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

初めての貢献Your First Contribution

bull 低いリスクでBitcoin PRプロセスを体験するbull これをやって見てください

ndash ドキュメンテーションを追加するndash テストを追加するndash タイプミスを直す

bull 宿題今週末小さいPRをやってねbull 貢献のガイドを読む

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-

notesmd

bull Experience Bitcoin PR process with low stakes trialbull Try to

ndash Add documentationndash Add testsndash Fix typos

bull Homework Do a small PR this weekend bull Read Official Contribution Guides

ndash httpsgithubcombitcoinbitcoinblobmasterCONTRIBUTINGmdndash httpsgithubcombitcoinbitcoinblobmasterdocdeveloper-notesmd

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 35: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

基本アドバイスGENERAL ADVICE

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 36: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

読んだほうが良いGood to Read

bull Bitcoin SoK Paper [Felten et al]bull Pull RequestsIssues on Repobull Bitcoin Improvement Proposal notes [BIPs]bull Kanzurersquos Archive [diyhplus~bryanpapers2bitcoin]bull Peter Toddrsquos Blog [petertoddorg]bull Computer Systems Security (6858 6857 6875)

[csscsailmitedu]bull Game Theory with Engineering Applications [OCW]bull Follow CCSOaklandCryptoFChellip conferencesbull Scaling Bitcoin Archive [scalingbitcoinorg]bull Twitter

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 37: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

読まないほうが良いBad to Read

bull 大体避けたほうが良い

ndash Redditのコメント

ndash NYTEconomistetcからのBitcoinの開発の記事

bull ldquo読んだほうが良いrdquo ものは十分ある

bull Mostly Avoid

ndash Comments on reddit

ndash Articles in NYTEconomistetc about Bitcoin development

bull Therersquos enough ldquoGood to Readrdquo to keep you busy and happy

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 38: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

交流しましょうSocialize

bull 喋られる良い人はいっぱいいる

bull Scaling Bitcoinのカンファレンスへ行く

bull ローカルのBitcoin Meetup (来週にやります太郎さんに聞いてね)

bull Twitter

bull Lots of really great people to talk to

bull Go to Scaling Bitcoin conference

bull Local Bitcoin Meetups (Ask Taro-San Next Week)

bull Twitter

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 39: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

我慢して落ち着きましょうBe Patient

bull Bitcoinはセキュリティに中心するソフト

ndash開発はゆっくりで行くhellip

ndashデベロッパーはコードを厳しくチェックするhellip

ndash壊れたコードでムカついているhellip

ndashでもhellipあなたの作業は強い影響を持つ

bull Bitcoin is security focused software

ndash Development will be slowhellip

ndash Developers will nitpick your codehellip

ndash Broken code will upset youhellip

ndash buthellip Your work is high impact

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 40: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

質問 休憩時間QuestionsBreak Time

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 41: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BIPのプロセスThe BIP Process

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 42: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Bitcoin Improvement Proposals

bull 大きなアーキテクチャーの変更bull httpsgithubcombitcoinbips にあるbull 準公式なプロセス

ndashこの方法で開発進めることが多いこれではない方法で開発進めることも多い

bull Process for large architectural changes to Bitcoinbull Kept at httpsgithubcombitcoinbipsbull Semi-Formal Process

ndash Lots of development happens this way lots of development doesnrsquot

詳しくは httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki にてDetails following from httpsgithubcombitcoinbipsblobmasterbip-0002mediawiki under license listed therein

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 43: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BIPとはhellipA BIP Can Behellip

1 新しい機能の提案

2 ある課題に関するコミュニティの意見

3 既に決まったデザインのドキュメンテーション

1 A New Feature Proposal

2 Community Input on an Issue

3 Documenting Design Decisions that have gone into Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 44: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BIPはこれじゃないhellipA BIP Shouldnrsquot behellip

1 非標準かインプレメンテーションに頼る小さい機能2 前に議論して却下されたアイデア3 重複の作業4 形が間違えている BIP5 モチベーションが無いもの6 幅が広いすぎるもの7 リファレンス実装が無いもの

1 Small Features that are non-standard or implementation dependent2 Ideas previously discussed and rejected3 Duplicated Efforts4 Malformatted BIPS5 Without Motivation6 Overly Broad7 Without Reference Implementations

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 45: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BIPの基本の形Basic BIP Skeleton

bull ヘッダー

bull 要約

bull スペック

bull モチベーション

bull 解釈

bull 前のバージョンの互換性

bull リファレンス実装

HeaderAbstractSpecificationMotivationRationaleBackwards compatibilityReference implementation

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 46: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

3種類のBIPThree Kinds of BIP

bull スタンダードトラックndash ほぼ全部のBitcoinのインプレメンテーションに影響がある

bull ネットワークのプロトコルbull ブロック トランザクションの有効性のルール変更bull Bitcoinを用いるアプリの総合運用性に影響がある変更

ndash 2つのパーツbull デザインの資料bull リファレンス実装

bull 情報ndash Bitcoinのデザインそれとも一般的なやり方の説明ndash 新しい機能の提案じゃないndash コンセンサスじゃない

bull プロセスndash Bitcoinのガバナンスの課題

bull Standards Trackbull Informationalbull Process

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 47: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BIPのライフサイクルBIP Life

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 48: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

小さなBIPレビューSmall BIP Review

bull 3つのBIPを見てみましょう

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

bull Letrsquos take a look at three BIPs

1 BIP9 VersionBits

2 BIP141 Segregated Witness

3 BIP32 Hierarchical Deterministic Wallets

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 49: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BIP 9 VERSION BITS

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 50: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Version Bits

bull 情報のBIPndash meta Standards Trackのフォークの作成方法

bull Bitcoinの32-Bitバージョンフラグを利用して同時に複数soft-forkを実行する方法

bull Soft forkは名前ビット(0~28)開始時間タイムアウトを持っている

bull 前の2016ブロックはそのビットを設定したのかをチェックする

bull Informational BIPndash meta how to make Standards Track Forks

bull Describes how to use Bitcoinrsquos 32-Bit version flag to deploy simultaneous soft-forksbull Soft fork has a name a bit (0-28) a start time and a timeoutbull Check that 95 of the preceding 2016 blocks set the bit

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 51: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

バージョンビットのデプロイVersion Bit Deployment

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 52: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BIP 141 SEGWIT

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 53: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Segregated Witness

bull Standards Trackbull Bitcoinの2つの問題を解決

ndash ブロックサイズ(ブロックごとにもっとTx入れる)ndash Transaction Malleability(トランザクション展性)

bull 署名が無効にならなくてもTxの変更はかなり出来るbull Segregated Witness

ndash 全部の署名データは別のところになる

bull Standards Trackbull Fix two problems in Bitcoin

ndash Block Size (slightly more transactionsblock)ndash Transaction Malleability

bull Transactions that can be changed significantly without invalidating signaturesbull Segregated Witness

ndash All Signature data is separately committed to

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 54: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

SegWitの実装SegWit Implementation

Before Segwit

bull txid = H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid ||

witness

bull Txの連鎖は署名に依存している

bull Chain of transactions is dependent on the signatures

After Segwitbull txid =

H([nVersion][txins][txouts][nLockTime])ndash txin = previous txid || witness

bull wtxid =h([nVersion][marker][flag][txins][txouts][witness][nLockTime])

bull ブロックの中に別のwtxidsのcommitment

bull Txの連鎖は署名と依存していない

bull Separate commitment to wtxids in block

bull Chain of transactions is independent of the signatures

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 55: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

SegWit実装BIP9 VersionBitsSegWit Deployment BIP9 VersionBits

bull name ldquosegwitrdquo

bull bit 1

bull start time midnight 15 November 2016 UTC

bull timeout midnight 15 November 2017 UTC

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 56: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

これはまずいですかIs this Bad

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 57: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BIP 32 HIERARCHICAL DETERMINISTIC WALLETS

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 58: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Hierarchical Deterministic Wallets

bull 情報のBIP

bull 親のldquomaster keyrdquoから子供の鍵が作れる

bull ldquoユーザrdquo 側のコードコンセンサスとネットワークじゃない

bull でもここの標準でセキュリティを高める

bull Informational BIP

bull Allow deriving a tree of keys from a root ldquomaster keyrdquo

bull ldquoUserrdquo code not consensus or network

bull Still standards here improve user security

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 59: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

質問休憩時間QuestionsBreak Time

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 60: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Bitcoin性能の開発Performance Engineering Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 61: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

このセクションの概要This Section

bull Bitcoinのパフォーマンスエンジニアリングについて

bull CuckooCache

bull Discuss Performance Engineering in Bitcoin

bull CuckooCache

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 62: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull スケーラビリティのためにより速くなるべき

ndashスピードが上がるとUXがよくなる

ndash TXsが向上する

bull Bitcoin needs to be faster to scale

ndash Faster is Better User Experience

ndash Handle more TXs

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 63: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull ldquo簡単rdquoに始められる

ndashプロファイリングで測ることができる

ndash Bitcoinに関する知識のハードルが低い

bull 調査しながら勉強する

ndash小さくて大きな問題

bull ldquoEasyrdquo to get started

ndash Can measure objective quantity by profiling

ndash Donrsquot need to know much about Bitcoin to start

bull Learn through investigation

ndash Small scale amp large scale problems

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 64: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 多様なエンジニアが関われる問題

ndash署名の検証

ndashネットワークリレー

ndashデータベースキャッシング

ndashウォレットのスキャニング

bull Many ldquoOpenrdquo Problems for engineers of different backgrounds

ndash Signature Validation

ndash Network Relay

ndash Database Caching

ndash Wallet Scanning

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 65: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

パフォーマンスエンジニアリングの必要性Why Performance Engineering

bull 楽しいから

bull Itrsquos fun

多分だけど

maybe

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 66: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

CUCKOOCACHE

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 67: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

署名Signatures

bull 署名というのは verify(sig pubkey)がtrueになる文字列 sig

bull 署名の検証は決定論的ndash verify(sig pubkey)がtrueなら何度実行しても同じ結果( true )になる

bull 署名を計算するのはコストが高い

bull A signature is a string sig such that verify(sig pubkey) is true

bull A signature verification is deterministic

ndash if verify(sig pubkey) is true then running it again will also be true

bull A signature is expensive to compute

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 68: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

MempoolのバリデーションMempool Validation

bull Mempoolのバリデーションのプロセスではトランザクションの中の全ての署名をチェックする

bull Mempool validation process checks all signatures in a transaction

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 69: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

ブロックのバリデーションBlock Validation

bull ブロックのバリデーションではブロックの中の全てのトランザクションをチェックする

bull トランザクションのチェックではトランザクションの中の全ての署名をチェックする

bull Block validation process checks all transactions in the block

bull Checking a transaction checks all signatures

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 70: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Can we avoid checking signatures 2x

署名を2回チェックするのは避けられるか

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 71: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

署名のキャッシュSignature Cache

bull verify(sig pubkey) がtrueの時にSHA256(sig || pubkey) をHash Setにを保存する

bull ハッシュを検索するのは署名のチェックよりコストが低い

bull if verify(sig pubkey) then save SHA256(sig || pubkey) in a hash table

bull Hash table is cheaper than a signature check

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 72: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 73: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セットunordered_set

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 74: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 75: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

a

c

j b p

d

z

H(k)

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 76: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セット unordered_setinsert(k)

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(k)

c

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 77: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セット unordered_setfind(f) == false

0 1 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 78: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 79: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 80: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 81: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

非整列セット unordered_setfind(f) == false

10 2 3 4 5 6 7

k

a

j b p

d

z

H(f)

c

探索時間は個数に比例

O(n)

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 82: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Bitcoinのナイーブ(イマイチ)な実装Bitcoinrsquos Naiumlve Implementation

bull unordered_setltHashgt set を利用bull unordered_setにはオーバーヘッドメモリ確保間接参照がたくさんあるbull もし DynamicMemoryUsage(set) が制限値を超えると

ndash 制限の範囲に収まるまでランダムにsetの要素(バケット)を捨てるndash 無限ループは可能

bull 同時並行性(16コアで実行する方が8コアよりひどい)ndash 追加時の書き込みロックndash 読込時の読み込みロックndash 削除時の書き込みロックndash 読込成功する都度setからその要素を削除

bull use unordered_setltHashgt setbull unordered_set bad overhead allocation and indirectionbull if DynamicMemoryUsage(set) gt limit

ndash Discard random buckets of elements until lt= limitndash Could loop forever

bull Concurrency (Worse to run on 16 Cores than 8 )ndash Read Lock to readndash Write Lock to insertndash Write Lock to erase ndash erase on every successful read

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 83: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Cache Wish Listbull 必要な時にだけ削除するbull いっぱいなったら一番古いエントリーを先に削除するbull 同時並行性が良いbull 関節参照が少ないbull メモリー負担が少ないbull 無限ループ(の可能性)がないbull メモリーの割り当てが少ないbull RAMキャッシュの競合が少ないbull 検索時間の改善

bull Only erase when new space neededbull When full delete less needed entries firstbull Improve Concurrencybull Decrease Indirectionbull Decrease Memory Overheadbull No (potentially) Infinite Loopsbull Decrease Memory Allocationbull Decrease RAM Cache Contentionbull Improve Lookup Runtime

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 84: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

全部直すことは出来るCAN WE FIX IT ALL

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 85: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

基本のアイデアカッコーハッシュBase Idea Cuckoo Hashing

bull アルゴリズムはシンプルndash 配列 hash a[NELEMS]ndash ハッシュ関数 hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull a[h(k)] に k2があればndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull 繰り返しがO(log(NELEMS)) になったらテーブルサイズを倍にするndash lookup(k) return a[H1(k)] == k || a[H2(k)] == k

bull 性能が良いハッシュ関数をH3H4 hellipと増やせば特に (証明は難しいhellip)

bull Very simple algorithmndash array hash a[NELEMS]ndash hash functions hash H1(elem e) hash H2(elem e)ndash insert(k h = H1 iterations = 0)

bull if a[h(k)] is occupied by k2ndash a[h(k)] kndash insert(k2 H1(k2) == h(k) H2 H1 iterations+1)

bull if hit O(log(NELEMS)) iterations double table sizebull Performs very well especially with more hashes H3 H4hellip (complicated proofhellip)

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 86: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーテーブルcuckoo table

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 87: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 88: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 89: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーテーブルcuckoo tableinsert(k)

a j c d p z b

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 90: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーテーブルcuckoo tableinsert(k)

j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 91: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーテーブルcuckoo tableinsert(k)

k j c d p z b a

H1(k)

H(a)

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 92: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーテーブルcuckoo tablefind(f) == false

k j c d p z b a

H1(f) H2(f)

個数が増えても探索時間が一定

O(1)

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 93: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーキャッシュCuckooCache

bull 固定サイズのハッシュテーブルを構築し(2倍にしない)ndash O(log(NELEMS)) の反復制限で最後の様子を削除する

bull ハッシュ関数 H1hellipH8 を利用するndash SHA256は32bytesだから32 bytes4 bytes = 8

bull アトミックなパックしたビット配列を保持するndash 「削除可能」をマーキングするためndash 新しいデータまでに様子を削除しない

bull 「世代」のマーキングのためのパックしたビットを保持するndash テーブルはいっぱいになったら世代交代するndash 制限を超えたら世代を上げる

bull Fixed size table (no doubling)ndash drop last element at O(log(NELEMS)) recursion limit

bull Use H1hellipH8 hash functionsndash because SHA256 is 32 bytes4 bytes = 8

bull Keep a array of atomic bit-packed bytesndash for marking erasablendash donrsquot erase element until new data

bull Keep a array of bit-packed bytes for generationndash retire generations when table gets crampedndash Age when older than THRESHOLD

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 94: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーキャッシュCuckooCache

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 95: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーキャッシュCuckooCacheinsert(x)

k j c d p z b a

0 1 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

ハッシュ結果が空き(削除済)の枠

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 96: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーキャッシュCuckooCacheinsert(x)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

H1(x)

そこに格納して使用中に

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 97: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 98: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

0 0 0 1 0 1 0 1

old new new old new old old newGeneration

Erased

( new ampamp erased) gt THRESHOLD

「新」世代の使用中の数が閾値を超過

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 99: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

old new new old new old old newGeneration

Erased

Erase Old

「旧」世代の使用中を削除済=空きに

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 100: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

カッコーキャッシュCuckooCacheinsert(y)

k x c d p z b a

1 0 0 1 0 1 1 1

new old old new old new new oldGeneration

Erased

Retire Generation

世代交代「新」を「旧」に「旧」を「新」に

「新」世代は全て空き

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 101: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

どんな結果が出ましたかHowrsquod We Do

別スレッドでのエントリー追加時に遅延削除する ボーナスReorgの時にパーフォマンスが上がる

古いエントリーから先に削除することを世代で保証できる 古い要素rarr必要性が低い

読込時と削除時にロックが不要となる 関節参照はほぼゼロとなる メモリーの負担はほぼゼロとなる (lt 1) 全ての処理が必ず終了する メモリーの追加の割り当てはゼロとなる 16コアで40早くなる O(1)の検索

Lazy erasure on future inserts Bonus Better performance during Reorgs

Generations ensure older entries deleted first Older Less needed

Zero locks needed for Reads and Erases Almost Zero indirection Almost Zero memory overhead (lt 1) All operations terminate Zero memory allocation 40 faster on 16 cores O(1) lookup

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 102: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 103: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

ヒットレートは最適に近いNear Optimal Hit Rate

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 104: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

低い分散Low Variance

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 105: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

(degdeg)︵古いより小さいサイズより良いパフォーマンス

Old Less Size Better Performance

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 106: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Howrsquod I know I did better

bull 色々なシチュエーションで新旧の実装を比較できるキャッシュシミュレータ

bull 証明ためのグラフィックbull 最初に作ったものはシンプルなシミュレータだった

bull ネットワークに接続しているノードのシミュレーションは大変大事ですがより難しいもっと良い開発ツールが必要hellipndash 歴史を持っているビットコインネットワーク上でシミュレーションするために前は一般公開では無いツールを使った

bull Cache simulator to compare old amp new implementations across situationsbull Graphical demonstrationbull A simulator was one of the first things I didbull Networked node simulation is very important but harder to do Better dev tools

neededhellipndash non-public tools to simulate historical bitcoin network

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 107: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

テストTesting

bull シミュレータを使って

ndashキャッシュのパフォーマンスの悪化を防ぐ

ndashプロパティの正しさを確保する

bull Used the simulator to

ndash prevent cache performance regression

ndash ensure correctness properties

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 108: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

レビューのプロセスのタイムラインReview Process Timeline

bull コードの始まり2016年夏bull PRを開いた2016年10月5日

ndash コメントランダムなプラットフォームのエラーhellip

bull 「世代」の追加2016年10月20日bull 10月21日のコメント

ndash sipa2nのサイズに変更しbitmaskを使ってね(an)は遅いから

bull 11月9日のコメントndash Deprecated フラグの珍しいビルドのエラー

bull PRはmergeされた2016年12月14日bull sipaは2nの制限を外した2017年1月12日bull Code Started Summer 2016bull PR Opened Oct 5th 2016

ndash Comments Random Platform Errorshellipbull Added Generations Oct 20th 2016bull Oct 21st Comments

ndash sipa please fix size to 2n and use bitmask (an) is slowbull Nov 9th Comments

ndash More esoteric build errors with deprecated flagsbull PR Merged Dec 14th 2016bull Power of 2 restriction lifted by sipa Jan 12th 2017 -gt (ab) ~~ (((uint64_t) a)n)gtgt32

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 109: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

覚えておくべき点Takeaways

bull Bitcoinではアルゴリズムの改善できるところは多い

bull 全部はトレードオフでは無い

bull 測定基準を先に決める

ndash最初はこのコードがあまり改善にならないと思って捨てようと思った

bull レビューされるの時に諦めないで

ndash長い時間かかるから

bull Bitcoin is ripe with opportunity for purely algorithmic improvements

bull Not everything needs to be a tradeoff

bull Set up metrics first

ndash I almost threw away this code because I wasnrsquot sure if it would help much

bull Donrsquot Get Demotivated in Review

ndash It takes a long time

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 110: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

コードCode

bull httpsgithubcombitcoinbitcoinpull8895

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 111: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

BITCOINの紳士録BITCOIN WHOrsquoS WHO

ボーナス

Bonus Section

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 112: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

laanwj

bull Wladimir J van der Laan

bull Bitcoin Coreの Lead Maintainer

bull MIT DCIの研究員

bull Wladimir J van der Laan

bull Bitcoin Core Lead Maintainer

bull Employed by MIT DCI

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 113: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

sipa

bull Pieter Wuillebull 大量な貢献のBitcoinデベロッパー

ndash SegWitの発明者

bull BlockStream Co-Founderbull httppieterwuillefactscom

ndash Pieter Wuilleが1回SHA-2を反転したでもそれは無理との証明だ

bull Pieter Wuillebull Prolific Bitcoin Developer

ndash Made SegWitbull BlockStream co-founderbull httppieterwuillefactscom

ndash Pieter Wuille once inverted SHA-2 But that just proves that its impossible

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 114: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

gavinandresen

bull Gavin Andresen

bull 元 Lead Maintainer

bull 元MIT DCI

bull 今の活動

bull Gavin Andresen

bull Ex-Lead Maintainer

bull Ex-MIT DCI

bull Current Activities

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 115: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

theuni

bull Cory Fields

bull Bitcoin Core デベロッパー ビルドシステムのエクスパート

bull MIT DCIの研究員

bull 良く言われる

ndash ldquoCoryが居なくなったら誰もバイナリービルドできないrdquo

bull Cory Fields

bull Bitcoin Core Developer build system guru

bull Employed by MIT DCI

bull Oft Repeated

ndash ldquoNo one would be able to build the bitcoin binary if Cory went awayrdquo

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 116: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

TheBlueMatt

bull Matt Corallobull Bitcoin Core デベロッパーbull BlockStream Co-Founderbull Relay Network のエクスパート

ndash Compact Blocksの発明者bull 髪がとてもブルー

bull Matt Corallobull Bitcoin Core Developerbull BlockStream co-founderbull Relay Network Guru

ndash invented Compact Blocksbull Very Blue Hair

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 117: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

jonasschnelli

bull Jonas Schnelli

bull ウォレットとUXのコードに注目する

bull Bitcoinのハードウェアウォレットを作っている

bull Jonas Schnelli

bull Largely works on wallet amp UX code

bull Building a bitcoin hardware wallet

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 118: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

morcos amp sdaftuar

bull Alex Morcos amp Suhas Daftuar

bull Chaincode Labsの Founder

bull Alex Morcos amp Suhas Daftuar

bull Founders of Chaincode Labs

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 119: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

gmaxwell

bull Greg Maxwell

bull あなたが考えたことは全部 Gregが既に発明しbitcointalkに投稿した

bull BlockStreamの Co-Founder

bull Greg Maxwell

bull Almost anything you can think of Greg invented it in a post on bitcointalk

bull BlockStream co-founder

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 120: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

petertodd

bull Peter Todd

bull Bitcoinの天邪鬼

bull Peter Todd

bull Bitcoinrsquos Top Contrarian

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 121: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Adam Back

bull BlockStream CEO

bull デベロッパーじゃないけど一流科学者である

bull HashCashの発明者

bull BlockStream CEO

bull Not a developer but a leading scientist

bull Invented HashCash

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 122: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

Satoshi Nakamoto

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help

Page 123: Digital Garage BC2 Workshop - Blockchain Core Camp...概要 Overview •3つの課題 1. Bitcoin 開発プロセスの紹介 2. Bitcoin Improvement Proposals (BIP) の紹介 3. Bitcoin

ここで名前書いてない人々Omitted People

bull もっといるですが上記の名前を見たら遠慮なく声をかけてね

bull There are lots more but the above are names yoursquoll see around amp can ask for help