Skip to content

Instantly share code, notes, and snippets.

@shiki-tak
Last active May 4, 2023 20:18
Show Gist options
  • Select an option

  • Save shiki-tak/5d5524add821f125966d6a619bd6696d to your computer and use it in GitHub Desktop.

Select an option

Save shiki-tak/5d5524add821f125966d6a619bd6696d to your computer and use it in GitHub Desktop.
blockchain research

Abstract

BlockchainのScalability問題を解決するソリューションの1つとしてLayer2のState Channelがある。2015年にBitcoinのLayer2ソリューションとしてLightning Networkが提案された。 当初はBitcoinやEthereumのLayer2として語られていたが近年様々なState Channelソリューションが登場している。そこで本論ではBlockchainのScalability問題解決の有力なソリューションとされているState Channelについて調査し、まとめることにする。

Contents

  1. State Channel Overview
  2. Lightning Network
  3. Raiden Network
  4. IBC(Cosmos Network)
  5. OVM(Plasma)
  6. Substrate Off-Chain Workers
  7. Counterfactual

Reference

State Channelとは

BlockchainにおけるState Channelとは、「特定の参加者間で"Channel"を開き、On Chainに記録しないでOff Chainで状態遷移を繰り返し、最終的な状態だけを記録する技術」である。 On Chainにbroadcastするtransactionを減らすことでScalability問題解決のソリューションとして期待されるだけでなく、エンドユーザにとってはtransaction手数料の削減やレイテンシーの改善といったメリットがある。

基本的な流れ

State Channelの基本的な流れは以下の通り

  1. Channelをopenする 特定の参加者間でBlockchainのStateの一部をMultiSigやSmart Contractでロック(資産のdeposit)して、 参加者がそのStateの更新を同意の上で行えるようにする。

  2. Off Chainで状態遷移を行う 参加者はBlockchainに記載可能なトランザクションを用いて、Stateを更新する。ただし、この時点でBlockchainへの書き込みは行わない。 また、新しい更新は古い更新よりも優先される。

  3. Channelをcloseする 参加者は最終的なStateをBlockchainに書き込み、State Channelを閉じ、Stateのロックを解除する。

state_channel_flow

State Channelの種類

Payment Channel

  • 送金のためのChannel。最も歴史が長く、実装も進んでいる。 例)
  • Lightning Network
    • BitcoinのPayment Channel
  • Raiden
    • EthereumのPayment Channel。etherだけでなく、ERC20, 223にも対応している。
  • Sprites
    • Lightning NetworkやRaidenにおいてPayment Channel Networkを構成するために利用されるHashed Timelock Contract(HTLC)の改良案を提案しているプロジェクト。

Application-specific State Channel

  • (Payment以外の)特定のアプリケーションを利用するためのChannel。

例)

  • FunFair
    • Blockchainを用いた透明で公平なオンラインカジノプラットフォームを開発
    • State Channelでの乱数生成手法の開発も行う

Generalized State Channel

  • 特定のアプリケーションに依存しないChannel。より細かく定義すると「新しいアプリケーションを導入するにあたってOff Chainでの状態遷移が必要ないChannel」となる。
  • すでに別の目的で空いているChannelを他のアプリケーションを利用するときに活用できる。

例)

  • Counterfactual
    • L4 Mediaの提案するGeneralized State Channelフレームワーク
    • On Chainの処理をなるべく少なくする設計思想
    • Channelを開くときに必要なのはMultiSig Walletのdeployのみ
    • まだOn Chainに存在しないアプリケーションも利用できる

State Channelの仕組み

Off Chainの状態遷移の基礎

Commitment

CommitmentとはOff Chainで合意された状態をChannelの参加者がいつでもOn Chainで反映できるようにするもの。 例えば、Lightning NetworkではChannel参加者両方が署名したcommitment txを作ることで参加者がいつでもそれをbroadcastすることができ、Channel内で合意された送金結果をいつでもOn Chainで確定することができる。 「いつでもOn Chainで反映できるが、実際には反映しないままにしておく」というのがポイントで、これによりOn Chainの状態遷移をしなくても、Channel内で合意された状態遷移が実際に起こったかのように振る舞うことができる。 相手が全く応答しなくなった場合などはいつでもCommitmentを提出してOn Chainで反映することができる。 Bitcoinの場合はtransactionの形でCommitmentを作るが、Ethereumの場合は任意のデータ形式に対する署名を検証できるので、Commitmentの形は自由に決めることができる。例えばRaidenでは、以下のようなJSONフォーマットとなる。 (nonce: Off Chainの状態遷移のバージョンナンバー、transferred_amount: 送付されたトークン量、channel_address: Channelの識別子、signature: 署名)

{
   "nonce":13,
   "transferred_amount":15000,
   "channel_address":"0x87F5636c67f2Fd4F11710974766a5B1b6f33FB1d",
   (略)
   "signature":"0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
}

Commitmentを提出する場合はこのようなメッセージをOn ChainのContractに渡す。そしてそのContractがメッセージの署名検証を行い、記載された内容の通りにトークンのtransferを行う。

Challenge

Commitmentを提出することでChannel内で合意された状態を確定できるが、ここで古い(最新ではない)Commitmentが提出されてしまうという問題が発生する。 例えば、悪意のある人がOff Chainで送金をしたのに、送金前の状態のCommitmentを提出するということが可能になる。そのため古いCommitmentが提出された場合にそれが古いと主張する「チャレンジ」の仕組みが必要になる。 具体的には以下の通り。

  • Commitmentが提出された場合、その内容をすぐに反映するのではなく、ブロック数などで定められた一定の期間待つようにする
  • 期間内にそれより新しいCommitmentを提出すれば古いCommitmentを却下する
  • チャレンジ期間が終了したら、提出された最も新しいCommitmentの内容をOn Chainに反映する また、古いCommitmentを提出したと証明された場合は、提出者のdepositを没収するなどのペナルティを設計することも考えられる。

基本プロトコル

Open: Channelをopenする

  • 取引に使う資産をChannelにdepositする
  • depositは参加者全員の署名がないと動かせないようにする

Update: Off Chainでの状態遷移

  • Off Chainの状態を参加者全員の合意のもと更新する
  • Commitmentを作り全員で署名する

Cooperative Close: 協力的なclose

  • 全員の合意のもと、Stateのロックを解除し、Off ChainのStateをOn Chainに反映する
  • 以下で説明するUncooperative Closeとは異なり、On Chainに即時に反映される

Uncooperative Close: 非協力的なclose

  • Cooperative Closeとは異なり、全員の合意なしにOff Chainの状態をOn Chainに反映させること
  • 通常はCooperative Closeができることが望ましいですが、相手が応答しなくなった(オフラインになったなど)のときに、Channelから資産を引き出すべく用いられる
  • 例えば賭けゲームをしていて相手が負けそうになって逃げてしまった、といったケースで使用されることが考えられる

Challenge: チャレンジ

  • 古いCommitmentが提出されたときに、それより新しいCommitmentを提出することで最新ではない状態がOn Chainで反映されることを防ぐ

Splicing: スプライシング

  • Channelをcloseすることなしに、depositした資産を引き出したり、追加で資産をdepositすること
  • もともと予定していた額以上を送金するためにdepositを増やしたい場合などにChannelを閉じて開き直すのに比べて低コストになる

Raiden Networkとは

  • BitcoinのLayer2 ソリューションであるLightning NetworkのEthereum版
  • ERC20規格に準拠したものが送受信可能
  • Raiden -> n:nのネットワーク, μRaiden →1:nのネットワーク

Getting Started

  • using virtualenv
# sync ethereum ropsten testnet
❯ geth --testnet --syncmode fast --bootnodes "enode://7df4f8fa037f82cc03ba0c1acd3fccba4ae40fc03704283979f074cadf37cc5b70845d1acee4161c3432eb6934ba3020cbaf9cc2ba841cdfb03d113ebeef5b79@172.104.5.185:30303" --rpc --rpcapi eth,net,web3,txpool,personal
INFO [11-15|17:40:48.707] Maximum peer count                       ETH=50 LES=0 total=50
INFO [11-15|17:40:48.734] Starting peer-to-peer node               instance=Geth/v1.9.2-stable-e76047e9/darwin-amd64/go1.12.5
INFO [11-15|17:40:48.734] Allocated trie memory caches             clean=256.00MiB dirty=256.00MiB
INFO [11-15|17:40:48.734] Allocated cache and file handles         database=/Users/shiki-tak/Library/Ethereum/testnet/geth/chaindata cache=512.00MiB handles=5120
INFO [11-15|17:40:48.892] Opened ancient database                  database=/Users/shiki-tak/Library/Ethereum/testnet/geth/chaindata/ancient
INFO [11-15|17:40:48.900] Persisted trie from memory database      nodes=355 size=50.67KiB time=894.387µs gcnodes=0 gcsize=0.00B gctime=0s livenodes=1 livesize=0.00B
INFO [11-15|17:40:48.901] Initialised chain configuration          config="{ChainID: 3 Homestead: 0 DAO: <nil> DAOSupport: true EIP150: 0 EIP155: 10 EIP158: 10 Byzantium: 1700000 Constantinople: 4230000 Petersburg: 4939394 Istanbul: <nil> Engine: ethash}"
INFO [11-15|17:40:48.901] Disk storage enabled for ethash caches   dir=/Users/shiki-tak/Library/Ethereum/testnet/geth/ethash count=3
INFO [11-15|17:40:48.901] Disk storage enabled for ethash DAGs     dir=/Users/shiki-tak/Library/Ethash count=2
INFO [11-15|17:40:48.901] Initialising Ethereum protocol           versions=[63] network=3 dbversion=7
INFO [11-15|17:40:48.970] Loaded most recent local header          number=6364240 hash=472552…8ef808 td=22937494932553041 age=2mo5d21h
INFO [11-15|17:40:48.970] Loaded most recent local full block      number=6364240 hash=472552…8ef808 td=22937494932553041 age=2mo5d21h
INFO [11-15|17:40:48.970] Loaded most recent local fast block      number=6364240 hash=472552…8ef808 td=22937494932553041 age=2mo5d21h
INFO [11-15|17:40:48.971] Loaded local transaction journal         transactions=0 dropped=0
INFO [11-15|17:40:48.971] Regenerated local transaction journal    transactions=0 accounts=0
WARN [11-15|17:40:48.971] Switch sync mode from fast sync to full sync
INFO [11-15|17:40:49.053] New local node record                    seq=13 id=f26442330264ea29 ip=127.0.0.1 udp=30303 tcp=30303
INFO [11-15|17:40:49.053] Started P2P networking                   self=enode://c5261eaa7776c4e734404d3037ee83dd4672c19df6deae8ee733fbfa4abedee2156ee5d7513f11569c8910b70dc9db9a4cd6789c0149b3147fcc85af40cb5daf@127.0.0.1:30303
INFO [11-15|17:40:49.055] IPC endpoint opened                      url=/Users/shiki-tak/Library/Ethereum/testnet/geth.ipc
INFO [11-15|17:40:49.056] HTTP endpoint opened                     url=http://127.0.0.1:8545 cors= vhosts=localhost
INFO [11-15|17:42:29.055] Block synchronisation started
INFO [11-15|17:42:37.262] Imported new chain segment               blocks=2 txs=46 mgas=9.795 elapsed=737.887ms mgasps=13.274 number=6364242 hash=5cbf59…dd730f age=2mo5d21h dirty=1.25MiB
 
 
# attach geth console and create account
❯ geth attach rpc:http://localhost:8545
INFO [11-15|17:40:02.383] Bumping default cache on mainnet         provided=1024 updated=4096
Welcome to the Geth JavaScript console!
instance: Geth/v1.9.2-stable-e76047e9/darwin-amd64/go1.12.5
at block: 6364240 (Tue, 10 Sep 2019 20:39:14 JST)
 modules: eth:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0
> personal.newAccount()
Password:
Repeat password:
"0x8231abff138456fbea9b2ab330eb32af6618c478"
> eth.accounts
["0x8231abff138456fbea9b2ab330eb32af6618c478"]
 
 
# launch Raiden with the default testnet keystore path
❯ raiden --keystore-path  /Users/shiki-tak/Library/Ethereum/testnet/keystore --network-id 3

Smart Contract for the Network

Overview

  • TokenNetwork
    • channelとdepositをon chainで管理するsmart contract
    • 各TokenNetworkは特定のERC20 tokenで動作し、address間のchannelを管理する
    • deployされたTokenNetworkは保管されたtokenを管理し、raidenのchannelに関する全てのon chain operationの主要なcontact point。
  • TokenNetworkRegistry
    • userがtokenからdeployされたTokenNetworkを検索するcontract
  • SecretRegistry
    • どのblockでどのsecretが明らかにされたのかを追跡するcontract
    • 一つのdeployされたSecretRegistryでblockchain上のraiden network全体にサービスを提供できる

Reference

What's is IBC?

  • Standard for exchanging information between different blockchains, centering on Cosmos Hub ibc_concept

Steps

  1. Zone1 commits a message to send TokenA to Hub1
  2. When agreed in Zone1, it is passed to the IBC module
  3. A packet is created and added to Zone1's send queue
  • Packet contents
    • Reference to committed block (Token information and to, from address information)
    • Source channel / connection
    • Destination channel / connection
    • Timeout
  1. Relayer detects the packet addition and sends it to Hub1
  2. Hub1 sends a receipt to Relayer as proof of receipt of the message from Zone1
  3. Relayer sends it to Zone1
  4. Zone1 deletes the corresponding packet from the queue, and informs Hub1 through Relayer that the packet has been deleted.
  5. Hub1 verifies the certificate and creates TokenA

Data Flow

IBCTransferCmd

  • If you want to transfer coins from another Zone1 (fromChain) to Zone2 (toChain), execute IBCTransferCmd and commit the transaction within fromChain. IBCTransferCmd

IBCRelayCmd

  • When relaying a Coin, execute IBCRelayCmd to monitor the zone transaction. IBCRelayCmd

  • Packet contains destination address, amount of coin to be issued, destination chainId

  • Confirm it and issue a transaction in the destination chain

  • At this time, the key used for the transaction signature is the key of the destination chain

Elements

Packet

  • Relayed from one blockchain to another by the relayer process.
  • The modules which send and receive IBC packets decide how to construct packet data and how to act upon the incoming packet data,and must utilize their own application logic to determine which state transactions to apply according to what data the packet contains.

Channel

  • Channels are payload-agnostic.

Connection

  • Protocol for securely establishing a connection between two chains and closing the connection completely

Consensus

  • Specifies the properties that must be satisfied by the chain consensus algorithm that implements the blockchain communication protocol.

Relayer

  • Relayer is a monitoring process for receiving data.
  • Off-chain process protocol that relays data between two chains running the IBC protocol.

Reference

Optimistic Virtual Machine(OVM)とは

  • Plasma Groupによって提唱されたすべてのLayer2(L2) protocolをサポートするように設計されたVirtual Machine
  • L2のFraud ProofによるDisputeを抽象化している概念
  • ある命題(Property)が正しいことがOff chain情報によって保証できることがL2の本質であるという考え方
  • L2のDisputeを抽象化するための記法(述語理論)を提唱

ovm_architecture

  • Propertyの記述例(State ChannelのExit)
    • exitするときに必要なpropertyを以下のように定義する 「exitしたいメッセージのnonceがnであるとき、nが両者の署名を持っているメッセージのnonceのうち最大の値であること」
      • 存在量化子を用いると以下の命題の否定として記述できる 「exitしたいメッセージのnonceがnであるとき、nより大きいnonceを持つ、両者の署名を持つメッセージが存在する」
      • 全称量化子を用いると以下のように記述できる 「exitしたいメッセージのnonceがnであるとき、すべてのnより大きいnonceを持つメッセージは両者の署名を持っていない」
  • このPropertyが正しいと認められたらnonce nのstateをexitすることができる
  • userはn+1以上のnonceを持つ両者の署名付きのメッセージを提出することでこのPropertyを棄却することができる

用語集

Dispute(紛争)

  • L2のソリューションでは、不正なExitに対してそれは不当なExitであるという異議を申し立てができなければならない。
    • 例えば、PlasmaのOperatorが不当にお金をExitしようとしたら、それに対して異議を申し立てることができる。

Fraud ProofとValidity Proof

  • Fraud Proof
    • 不正なStateに対してそれが不正であるという証拠を提出する。不正なStateがexitされたときにのみ行えばよい。Interactiveなやりとりが必要となる。
  • Validity Proof
    • 正しいStateに対してそれが正しいという証拠を提出する。State updateのたびに行う必要がある。提出すればok。
  • State Channel, PlasmaはExit時に紛争期間(Dispute period)を設けて、Fraud Proofによる検証を行う。Dispute periodを過ぎれば、正しくないことが証明されたことになる。

一階述語理論

  • 命題論理に量の概念を加えたもの
  • 「すべてのxについてyである」、「あるxに対してyである」のような命題が扱える
    1. 全称量化記号(universal quantifier)
    • 例: すべての猫はかわいい
      • かわいくない猫を証拠として提出すれば否定できる
    1. 存在量化記号(existential quantifier)
    • 例: ある猫には翼が生えている
      • 翼の生えた猫を証拠として提出すれば証明できる

L1 Contract + Client Decider

  • Universal Adjudication Contract
    • OVMのCore, すべてのL2スケーリング構築ロジックに対する単一のコマンド理論
  • Deposit & Exit Contract
    • L2へのゲートウェイ, deposit requestを処理し、最終結果をexitする一般的なcontract
    • userはL2での取引を開始する前にL1から資産と初期状態をdepositする
  • Predicate Contract
    • 提出されたpropertyをvalidate / disputeするためにUniversal Adjudication Contractによって呼び出され、常にtrueもしくはfalseを返す
  • ForAllSuchThat predicate
    • ForAllSuchThat predicateは、claimを証明する基本的なpredicateの1つ、ネストされたすべてのpropertyがtrueを返す必要がある
    • L1では、このclaimを却下するために必要な矛盾は1つだけでよい
  • ThereExistSuchThat predicate
    • ネストされたpropertyから真のないdispute periodを過ぎた場合、ThereExistSuchThat predicateは、少なくとも1つのネストされたpropertyがtrueを返して、証明されたclaimの有効性を確認する必要がある
  • Not predicate
    • 1つのproperty Aの論理否定を要求する
  • And predicate
    • And(A、B)の論理否定を要求する場合、Not(A)またはNot(B)を証明する必要がある
  • Or predicate
    • Or(A、B)の論理否定を主張する場合、Not(A)およびNot(B)を証明する必要がある
  • Quantifier
    • claimが有効かどうかを判断するために必要な状態またはメッセージのセットを抽出する
  • Decider
    • predicateごとにtrue / falseを決定するpredicate固有のcontract
    • L2のDBに保存されている有効なstateを構成するものを定義するロジックが含まれている
    • 決定を下すには、数量詞によって抽出された情報が必要になる場合がある

Substrate Off-Chain Workers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment