<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chen YanLong on Medium]]></title>
        <description><![CDATA[Stories by Chen YanLong on Medium]]></description>
        <link>https://medium.com/@chen_yanlong?source=rss-32f3623574bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zs5XI8SS_K8aENjZFYI6Mg.jpeg</url>
            <title>Stories by Chen YanLong on Medium</title>
            <link>https://medium.com/@chen_yanlong?source=rss-32f3623574bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:39:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chen_yanlong/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[經驗補充包：自動交易程式]]></title>
            <link>https://medium.com/@chen_yanlong/%E7%B6%93%E9%A9%97%E8%A3%9C%E5%85%85%E5%8C%85-%E8%87%AA%E5%8B%95%E4%BA%A4%E6%98%93%E7%A8%8B%E5%BC%8F-df443e821d9e?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/df443e821d9e</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[trading-bot]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Tue, 18 Mar 2025 09:38:31 GMT</pubDate>
            <atom:updated>2025-03-18T09:43:52.358Z</atom:updated>
            <content:encoded><![CDATA[<p>本篇內容更像是一篇著重過程的流水帳，有一點技術層面，但不會提供原始碼，如果你想要的是這個的話，回頭回頭。</p><p>Published on March 18, 2025 by Chen-YanLong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*td2iKLcSbPm5vX6z" /><figcaption>Photo by <a href="https://unsplash.com/@ninjason?utm_source=medium&amp;utm_medium=referral">Jason Leung</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>好大張哈哈哈。</p><p><strong>table of contents.</strong></p><ul><li>Intro.</li><li>Speed up communication</li><li>About trading bot</li><li>AWS WTF</li><li>Outro.</li></ul><h4>Intro.</h4><p>回到半年前，我在某個接案平台上接到了某個人的委託，內容是要做台指期的自動交易程式。我那時候跟他談了一個小時後，想說，哇靠這個也太簡單了吧，這個比我大二上的商管程式設計的一次作業還簡單。</p><p>那既然這是別人的委託，我就有絕對的責任要保護個資以及內容（畢竟人家有給我錢）。以至於我寫到這裡的時候，我真的不知道底下的內容會有多破碎，肯定是很亂很亂的流水帳，所以如果你還願意繼續看下去的話，裝備撿起來，走了。</p><h4>Speed up communication</h4><p>我覺得要跟一個人在某個項目上的討論速度更快，就是知識量的集體提升。底下幾個是我幫助自己在與不懂程式設計的人加快討論速度時，會先跟對方介紹的東西。</p><ul><li><strong>電腦。</strong></li></ul><p>肯定的吧。但其實更準確來講，作業系統。我強烈建議大家都有一台 unix 系統的電腦啦，可以幫助你減少很多很多不必要的過程。這件事情蠻有趣的是，客戶的電腦是 Windows，所以我得要在 mac 上開發之後，想辦法幫客戶在他的電腦上裝起一樣的服務。務必要跟對方解釋「不同系統一定會遇到不同問題」這件事，免得好像你寫的東西漏洞百出。但當然，我可是用 windows 打過幾次黑客松（並且每次都會用到生氣）的人，我當然知道他有多難搞。</p><ul><li>vscode</li></ul><p>不必多說的是我要開發用的。要多說的是，客戶的電腦裡也要裝這個，為什麼，因為有很多檔案格式是很難開的，所以你最好的方式，就是儘量讓客戶的電腦環境跟你是一樣的。不然你還要搞半天打不開 .env.example。vscode 可以開終端機，所以你不用特別再教終端機要怎麼開，你甚至可以直接設定讓對方的 vscode 預設終端機是 git bash。</p><ul><li>Git</li></ul><p>Git 是一定要有的東西，你不可能再用隨身碟把你寫好的程式碼摳過去他的電腦，不要鬧了，這不是單單效率的問題，是會不會被笑的問題。同時你的維運更新要可以三秒鐘在他的電腦重現，尤其是像我一樣漏洞百出的人，每次的更新都一定要要求對方知道 git pull 怎麼用。另一個優點就是，你的 commit 紀錄可以在你想要寫文章的時候看一下自己到底為什麼搞了那麼久。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*agC2nDn-iP49Q2V0Z-eJlQ.png" /><figcaption>when ur code really got problems</figcaption></figure><ul><li>Log</li></ul><p>不是對數，print(“Hello world”) 會跑出來的 log。在跟客戶溝通的時候，你很難叫客戶從 error code 裡面跟你說 error 是什麼，如果他可以的話，他就自己去寫就好了。所以最好的方式，就是在你的程式裡面安插小間諜，把所有 log 都記錄下來，當客戶跑完有問題的時候，就把那包 log file 傳給你，簡單又好用。</p><h4>About trading bot</h4><p>簡單的交易機器人流程：追蹤價格＆計算 -&gt; 觸發條件 -&gt; 下單</p><p>最簡單的程式交易我用過的，莫過於 tradingview （以下簡稱TV）自動觸發條件之後傳送到幣安 api 下單，瓦賽那老快的，五分鐘就寫完了。</p><p>簡單來說，你在 K 線圖上（下面那張圖）畫了一條綠線，你跟 TV 說：「欸，如果有哪條線穿過那條綠線，幫我把手上的以太幣賣掉。」（所有人都應該把以太垃圾幣賣掉） 那你就完成了簡單的交易機器人流程。TV 幫你追蹤價格，TV幫你偵測條件有沒有被觸發，TV幫你跟幣安下單。你要做的事前準備是什麼：設計條件。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*ZOv_uCmaCAKymOozVpYYUg.png" /></figure><blockquote><strong><em>設計條件（策略）</em></strong></blockquote><p>今天我做的事情當然不包括這個，不過既然是流水帳，就提供一些我四年炒幣（搞笑）經驗的乾貨。</p><p>策略的設計當然要由客戶提供，可以是簡單的 123 反轉買入、突破趨勢線賣出、可以看指標、看 MACD、結合看 MACD 跟 RSI、等等等等。但當你今天想要寫出一隻程式來幫你交易，你給的策略就要夠明確。以程式設計師的角度來講，你要給我的是「如果怎樣，那就怎樣」而不是「欸抖我想一下，賣，欸欸揪抖，不要好了，他會不會漲上去啊？」。程式交易的原則就是接受虧損，但你知道這個策略長期是穩賺的。你用會賠的風險換取它會漲更多的機率，如是而已矣。</p><p>講太多了，回來。</p><blockquote><em>交易所</em></blockquote><p>追蹤價格要 api，下單要 api 。不管你要交易股票、指數還是幣，最快的方式就是找到一間有提供 api 的交易所，他最好同時擁有追蹤價格的功能以及下單的功能。我不知道追蹤價格能不能用爬蟲的，我真的不知道，我不會爬蟲。不過下單一定要有 api ，那既然關乎到你的錢，那一定要有 api key ，更甚者，這次出現了憑證這個東西，這個東西在後期的開發中造成我非常大的困擾。</p><p>我這次用的是這個傢伙，我得要說，document 寫得還挺差，不過有一個 tg 群讓大家瘋狂問問題，整體來說我 respect 這個團隊。那我最困擾的點是 Shioaji 我每次都打成 Shiaoji，然後跳錯誤說你沒裝這個東西啊，我想說，我就裝了，我真的有裝啊。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*50_YEc4Yt2OI9npgFaZNEg.png" /><figcaption>shiaoji</figcaption></figure><blockquote><em>計算</em></blockquote><p>計算還挺簡單的，主要會遇到幾個問題</p><p>比如說你想知道昨天美國某個指數收盤表現怎麼樣，你要另外找 api 去抓，那這邊推薦 yfinance。至少有找到我要的東西。</p><p>那比如說你要 MACD 的資料，但 api 沒有提供，那你可能要自己算。但其實也蠻簡單的，就是去找這個指數的數字怎麼算出來的，然後自己刻出來，也不會花多久時間。最主要是模組化要做好，不然你要修改或者是要拼湊的時候會很想死，但這本來就是基本的，所以。</p><blockquote><em>時間</em></blockquote><p>我覺得程式交易很大的一個新奇點在於，時間要被嚴格的考慮進去。</p><p>比如說今天休市，或是今天收盤時間不一樣，或是程式在奇怪的時間被打開，這些是很多問題會出現的地方。因為我們自然而然的會覺得程式應該會在正確的時間被跑起來，但很多時候都不會。既然攸關到錢，這件事情就不能馬乎。</p><p>那還有很多問題是，程式在跑的時候，要設定很多 time.sleep 這類的東西，或是用到 async await，這些都是比較容易出現問題的地方。</p><p>還有一個重要的問題是，如果你在 aws 上面跑的話，時間是用 GMT 哦。</p><p>就這樣，簡單的交易流程。</p><p>整個 coding 過程沒有出現太大的問題，我只花兩天就寫完了，該有什麼問題就網路上查，當一次程設作業在寫。</p><h4>AWS WTF</h4><p>重頭戲來了，程式交易的最終極就是我也不用打開電腦，我也不用讓他跑，他有一個 schedule，我好幾個月都不用看他。最後，我的錢變多。</p><p>像不像夢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*swF_A0f1Bx_uyoyNPkW_SA.jpeg" /><figcaption>imagination</figcaption></figure><p>那我這次選的是 AWS ，沒為什麼，因為我剛好想學。老實說我根本沒碰過，我甚至不知道怎麼用 docker （因為我的舊 windows 用不了docker ），這樣真的很丟臉，所以我借機學了一下。結論是 docker 我也只會用毛皮，aws 真的 wtf 功能超級多，介面很不人性化，但我還是有架起來。</p><blockquote><em>Docker</em></blockquote><p>簡單來說，今天有一包程式碼，我不想在不同的電腦跑的時候就出現系統不一樣或者是套件不一樣的問題。那我就用 Docker 把他包成一包東西，用到什麼套件我都全部包進去，要跑的時候我就在裡面跑。很像在每個人電腦裡面開一個領域展開，你的條件適用於這個領域裡面。這樣。我也沒很懂，所以請糾正我如果我講錯的話。</p><blockquote><em>Secret</em> <em>Manager</em></blockquote><p>.env 裡面的東西不該直接包在 Docker Image 裡面，所以這次用了 aws 的 secret manager，可以用來存這些不能被看到的東西，什麼 api key、ca、iam.json，通通丟進來。很好笑的事情是，我發現這個功能是唯一會真的跟我收錢的功能。</p><blockquote><em>IAM</em></blockquote><p>aws 在權限管理上好像有蠻大的空間。比如說我是一間公司擁有這一個 aws root 帳戶，今天我要讓底下的工程師做某個功能的時候，我總不能直接把帳號密碼給他。這時候就可以開一個 IAM User（其實他好像不建議這麼做，不過我不沒有去了解他，因為我就一個人用也不怕），給他他該用到的權限。我會用到這個有兩個地方。第一個是我的電腦本地端要推 Docker Image 上去的時候需要有權限，第二個是我讓程式自動在上面跑的時候要給「它」一個權限。</p><blockquote><em>Fargate</em></blockquote><p>AWS Fargate 相對於 EC2 是一種無伺服器運行容器的方式，不需要維護底層伺服器，對於我們這些簡單的小程式非常夠，也比較好部署，閒置的時候也不用費用</p><blockquote><em>EventBridge</em></blockquote><p>就想像成他是一個 schedule，一個 cron。可以設定在什麼時候該啟動程式去跑。</p><p>以上這些都還有很多細節，有興趣的各位就自己去補坑吧哇哈哈。不得不說還蠻有趣（也蠻煩）的，可以知道很多系統的架設細節。</p><h3>Outro.</h3><p>以上就是我這半年在做的其中一件事情的小遊記，希望大家都有所收穫。</p><p>前幾天跟兩個朋友聊天的過程中偶然覺悟，生成式 AI 那麼快的現在，其實就算你什麼都不會，你也什麼都會。所以想做什麼就什麼都去做就好了，都有人去開飲料店了說。當初會接這個案子的契機除了覺得這樣可以賺錢超級有趣，也覺得反正過程中一定會學到東西的啦，就這樣經過了半年，說真的也學了不少。</p><p>延續一月在學的東西，大家下次看到我可能是我寫一個 ios 糞 game，誰知道，拭目以待，我也是。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df443e821d9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PCS: Binius explained]]></title>
            <link>https://medium.com/taipei-ethereum-meetup/pcs-binius-explained-23c978031464?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c978031464</guid>
            <category><![CDATA[snark]]></category>
            <category><![CDATA[binius]]></category>
            <category><![CDATA[zero-knowledge-proofs]]></category>
            <category><![CDATA[polynomial-commitment]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Sun, 20 Oct 2024 01:32:02 GMT</pubDate>
            <atom:updated>2024-10-20T01:32:02.671Z</atom:updated>
            <content:encoded><![CDATA[<p>本文將介紹由 Irreducible (原Ulvetanna) 所提出的 binary field 中建立 SNARK 的方法 Binius。</p><p>Published on Oct 20, 2024 by YanLong Chen.</p><blockquote>Special thanks to <a href="https://medium.com/u/9b73fea85d46">Kevin Mai-Hsuan Chia</a>, <a href="https://medium.com/u/5c031577a87d">Chih-Cheng Liang</a> and <a href="https://medium.com/u/19d9bc2da99b">Kimi Wu</a> for reviewing.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ZnaBhWNC9a2RzYsMQNYHSA.jpeg" /><figcaption>Photo by Eva Gorobets on Unsplash</figcaption></figure><h4><strong>table of contents.</strong></h4><ul><li>Intro.</li><li>A little recap of PCS</li><li>Binary Tower</li><li>Reed-Solomon erasure code</li><li>Kronecker product</li><li>Binius example by Vitalik</li><li>Summary</li><li>Ref.</li></ul><h3>Intro.</h3><p>傳統的 SNARK 通常會在 256 位元以上的有限體中做運算，為了在這麼大的有限體中做運算，電路中的數字就必須用這麼多的空間來儲存，你可以想像在你的電路當中有一堆只需要 1 位元就能表示的 1 佔用了 256 位元會有多浪費空間。</p><p>那麼既然在那麼大的有限體中運算很耗資源，我們為什麼不將有限體縮小，縮小到極致，也就是只剩下 0 跟 1 的 binary field（GF(2)）。而 Binius 就是在 binary field 中運算的 SNARK，更準確地來說，Binius 是在 binary field 中的 polynomial commitment scheme。</p><h3>A little recap of PCS</h3><p>現代組成 SNARK 的方式是把 IOP (Interactive oracle proof) 和 PCS (Polynomial commitment scheme) 結合在一起，其中我要講的是 polynomial commitment。</p><p>Polynomial commitment 是一個可以代表多項式的表示方法。Prover 可以將一個多項式 commit 成一個 polynomial commitment，並在之後向 Verifier 證明這個多項式上的某個點的值，而不用公開整個多項式。</p><p>而證明的方式會使用高中學過的餘式定理，如果我要證明 P(z) = a，那我只需要證明 (P(x)-a)/(x-z) 是一個多項式就好了。原因如下，如果 P(z) = a，那麼根據餘式定理就滿足 P(z)=(x-z)* q(x)+a，經過一番移項會得到 (P(z)-a)/(x-z)=q(x)，也就是以上說的 (P(x)-a)/(x-z) 是一個多項式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CFJTl9b2K9CQzFNu-0ZZtw.jpeg" /></figure><p>簡單回顧一下 KZG commitment。</p><p>KZG 的第一個步驟是 trusted setup，由一個或多個人完成。先取一個秘密 s，（這個秘密 s 在完成 trusted setup 之後要被丟棄），以及兩個橢圓曲線的 Generator G_1 和 G_2，創造出兩組數列 [G_1, G_1* s, G_1* s², …, G_1*s^n]、[G_2, G_2* s, G_2* s², …, G_2* s^n]，這些數字被稱為 proving keys。</p><p>第二個步驟是 commit。 Prover 將多項式 P 轉換成 commitment，方法是將原多項式的 x^n 以 G_1*s^n 代換掉。我們用 [P] 來代表 P 的 commitment。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZ1VYVcnu0ygwC3T84XySA.jpeg" /></figure><p>最後一步是證明，Verifier 只要確認兩組橢圓曲線上的 Pairing 相等，就能被說服 P(z)=a。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQIKhGd_93wSeOZTNKyQBw.jpeg" /></figure><p>由於 KZG 並不是本文重點，所以就不多做背後數學邏輯的解釋，讀者只需要知道 Polynomial commitment 的用途即可。</p><h3>Binary Tower</h3><p>這部分會碰到比較難懂的抽象代數，而 Binius又在這之上進行了改良，由最基本由 0 和 1 組成的二進位體（binary field or Galois Field GF(2)）, 進一步延伸出 GF(2^n)。</p><p>最傳統的 GF(2^n) 使用的是單變數的多項式運算，而為了加速運算，Binius 將單變數運算改成了多變數運算，變成了所謂的 binary tower (出自<a href="https://www.fq.math.ca/Scanned/26-4/wiedemann.pdf">An iterated quadratic extension of GF(2) by Weidemann(1986)</a>)。</p><p>我們會從最基本的binary field 開始介紹，我相信這樣會更容易理解 binary tower 在做什麼。</p><h4>binary field</h4><p>有限體（域） Finite Fields，又稱 Galois Fields，時常簡寫為 GF(p)，代表的是一個由 1 到 p-1 所組成的集合，所有在這個有限體中的運算都要 mod p。在這裡需要注意的是 Galois Field 的 p 必須是質數或是質數的某個次方。舉個例子來說，GF(7) 由 {0,1,2,…,6} 組成，其中所有的運算都要除以 7 取餘數，也就限制了所有運算的結果最終都會回到這個集合內。</p><p>Binary Field，也就是 GF(2)，只由兩個元素 {0,1} 組成，所有運算的結果都是 0 或 1，我們可以將所有運算寫在下表，左邊是加法，右邊是乘法：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKlNnQJdxoigPPAeV2cPXg.jpeg" /><figcaption>addition and multiplication in binary field</figcaption></figure><p>你可以發現在 binary field 中的加法就是 XOR ，更方便的事情是減法就是加法。我們會想要在所有運算中擁有這些優點，這會讓運算速度非常快。</p><p>那麼如果我們今天想要處理 3 個 bit 的運算時，也就是我想要在 {0,1,2,3,…,7} 中做運算時會發生什麼問題（這裡不能說是 GF(8) 因為 p 必須是質數）。</p><p>如果你像上面一樣把整個加法表跟乘法表寫出來，你會發現在加法表裡面沒什麼問題，在乘法表裡就會出問題了。在乘法表中，所有數字的出現頻率是不一樣的，也就是說如果你的加密系統建立在這樣的“有限體”中（當然他不能被稱為有限體），攻擊者有很高的機率可以利用頻率分析來破解。第二個問題是，在這樣的“有限體”當中，某些元素不存在乘法反元素，也就是不能進行除法。</p><p>為了解決這樣結構的缺陷，又想要保留加法跟減法都是 XOR 的優點，我們需要介紹 GF(2) 的擴展域 GF(2^n)。</p><h4>extension field</h4><p>GF(2^n) 是 GF(2) 的擴展域，包含 2^n 個元素，每個元素可以用長度為 n 的二進位數表示。舉個例子：GF(2³) ，由 {000,001,010,011,100,101,110,111} 組成，你會想說這跟原本的有限體差在哪，不就是把原本的數字轉成二進位表示法。其實不太一樣，在這裡我會建議大家先不要把他看成是一個二進位表示法，111 就是 111，不要想成 7（雖然後面我們還是會這麼做），因為每一個位元代表的是一個多項式的係數。加法跟乘法都不是原先想像的加法跟乘法，且運算仍然是二進制的。</p><p>先跳到結論，這樣的建構可以讓乘法表中的每個數字出現頻率相等、每個元素都有相對應的乘法反元素、並且加法等同於減法。</p><p>在這樣的有限體當中，每一個元素都被看成是一個多項式，其中每個位元代表的是 x 的某個次方的係數。這有點像是小時候剛學多項式的除法時，我們為了簡化只會寫多項式的係數一樣。所以在 GF(2³) 中的元素，其實是如下表所示的多項式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g555IzsmidHeGiiGvmSmhQ.jpeg" /></figure><p>寫成這樣之後就好解釋了，只要把兩個數字都變成多項式，再進行加法跟減法，並且記得使用二進位，運算結果再變回係數表示法，所有的運算都會變得非常合理。</p><p>加法的部分比較簡單，我舉了個例子如下。應該不難看出，加法的結論就是XOR。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_WykK6Y919zagATPFyrbQ.png" /></figure><p>乘法的部分比較複雜一點點，但只要帶入不可約多項式（Irreducible polynomial）的概念，所有問題都會迎刃而解。不可約多項式其實就是在這個有限體中的模數。在原本的有限體中我們 mod p，而在擴展域中我們就 mod 不可約多項式。在這個例子當中，x³ + x + 1 就是不可約多項式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V9sIHxDjI0uPX6U8ykpgWA.jpeg" /></figure><p>透過這樣的運算，我們可以寫出整張加法表和乘法表，再把二進位數字的想法搬回來（111=7）。就會出現 7 + 5 = 2, 7 * 5 = 6 這樣，看似奇怪但很合理的結果。</p><h4>binary tower</h4><p>我們定義另外一種 binary field 的建構方式，稱之為 binary tower。之所以叫做 tower，是因為每個擴展域都像是上一個擴展域疊加上去，GF(2¹²⁸) 像是兩個 GF(2⁶⁴) 結合在一起，而 GF(2⁶⁴) 又像是兩個 GF(2³²)結合在一起，這樣一層一層的感覺就好像一個塔一樣。你可以一直無限疊加上去，端看你的需求。</p><p>跟原本的 GF(2^n) 一樣，每一個位元都表示著一個小的多項式，只是在 binary tower 中，這個小多項式是多變量的，也就是由 {x_0, x_1, x_2,…,x_k} 組成。</p><p>在 binary tower 當中的每個元素可以表示成左半邊加上右半邊乘上 x_k，舉個例子來說：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m0qGsl-X0y_SnksloqZWsw.png" /></figure><p>而其中的 1100 跟 1010 又可以切成一半：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cFKaKWTkOv-Doa4gpHaMg.png" /></figure><p>再切一半就可以得到：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W-L5R1KI_0juwHSPy9PKKw.png" /></figure><p>利用同樣的算法，我們可以算出每一個位元所代表的多項式，我畫了一張圖希望更能體現那種塔的感覺，也順便標示出在每個擴展域當中的各個位元代表的多項式是什麼：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uh6u5fOO-hQT780dyx5zbQ.jpeg" /></figure><p>而這麼做的好處在於，當我要進行乘法的時候，我可以將兩個數字都拆成更小的兩個數字，彼此做相乘，然後再拆成更小的數字，這樣無限遞迴下去，最後用很簡單的數字完成乘法。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KBa16psSnx_dbXcd3gUEdw.png" /><figcaption>screenshot from <a href="https://www.youtube.com/watch?v=eTCjVTWqjj0">https://www.youtube.com/watch?v=eTCjVTWqjj0</a></figcaption></figure><p>那在這之中會產生一個問題就是，如果次方超過的話怎麼辦。如同上面的解法，我們同樣要定義不可約多項式。換個表示方法，就是把那些有次方的數代換掉：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6vzL3W-r9DIv9Ob0nDwICw.png" /></figure><p>所以舉個例子：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGVsRTlQe_lUb_uyuY1AnQ.png" /></figure><p>補充說明一下，這裡的二進制表示方法是顛倒過來的，所以 001 代表的是 4 不是 1。那麼根據這樣的算法我們可以寫出 GF(2⁴) 之間的加法表和乘法表。讀者可以在表中挑一個來手算看看，相信會更容易理解：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VY4Ko3ZxD_-FQxkvN29lUA.png" /><figcaption>screenshot from vitalik’s website</figcaption></figure><p>使用有別於傳統建構方式的 binary tower 可以更有效的支援各種長度資料之間的運算，在這裡我指的是不同 data type 的長度，1 可以就是 1 位元，不用塞到一個 256 位元的空間中。</p><h3>Reed-Solomon erasure code</h3><p>Reed-Solomon (以下簡稱RS) 是一種錯誤更正碼（Error Correction Codes），所謂的錯誤更正碼是一種用於在數據傳輸和存儲過程中檢測和糾正錯誤的技術。在數據傳輸或儲存過程中，由於噪音、干擾或其他原因，可能會發生數據的損壞，而我們會利用錯誤更正碼來多傳一些附加的資訊，讓我們可以利用這個資訊檢測並將損壞的數據回復成正確的資訊。</p><p>RS 的做法是將要傳的數據看成直角坐標上的點，將這些點計算成為一個唯一的多項式(用拉格朗日插值法)，並多傳幾個多項式上的點作為更正碼。這樣一來收到數據的人就可以利用多傳的更正碼還原出原始的多項式，並檢查出數據是否有損壞。能承受幾個數據損壞由多傳了幾個數據來決定。</p><h4>Lagrange Interpolation</h4><p>這裡簡單解釋一下拉格朗日插值（Lagrange Interpolation）。給定 k+1 個點，你可以寫出一個唯一的多項式：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RRc-HXPN3PtW4CD_jNGHtw.png" /></figure><p>其中：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_7frDqKwRod7s4nrAm8Yg.png" /></figure><p>舉個例子：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WqSMqjwLCpDZ9roaAzVHPw.png" /></figure><p>你可以得到：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wVhOBOZMpwpAh6U2i6XBGA.png" /></figure><p>最後組起來：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9IVYu6YKd1HV2T-TMVXPxw.png" /></figure><p>透過拉格朗日差值法，我們可以在給定任意數量的點時快速的算出唯一的多項式。</p><h4>a RS example</h4><p>現在假設我們要傳的資料是 (3, 7, 13)，我們可以讓要傳的資料剛好是某個多項式代 1,2,3 時的值。也就是我們令一個方程式的：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-acSqysUwXT9wxzLHua7w.png" /></figure><p>用拉格朗日插值我們可以得到這個二次方程式是 x² + x + 1。接著我們算出另外兩個點（或更多個點）：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gvWWHr0nAXraLTiSRAlRig.png" /></figure><p>接著把（3, 7, 13, 21, 31) 一併傳出去，這麼一來，只要傳送過程中資料損壞數量在2以下，我們就有能力算出同一個多項式並把數據還原回來。比如說今天的第二個數據在傳送過程中不小心從 7 變成了 2，我就可以用其他幾個點算出原本的 7 (嚴格說起來只需要額外的一個點):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DThDyZWdk4ULOUy-pZBPig.jpeg" /></figure><h3>Kronecker product</h3><p>這裡介紹一個 Binius 會用到的小小數學工具，Kronecker product。</p><p>Kronecker product 是對兩個任意大小的矩陣之間的運算，他是一種張量積（tensor product）的特化，以 ⊗ 表示。Kronecker product 會用兩個矩陣生成一個更大的矩陣。舉個簡單的例子，如果 A 和 B 分別是：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dlEpnvW7UtW9fb4s3-QOhg.png" /></figure><p>那麼它們的 Kronecker product A ⊗ B 為：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09yRKsVIHLucgYWQYt2Dyw.png" /></figure><p>其實他的概念就是把兩個矩陣中的元素兩兩相乘，變成一個更大的矩陣而已。在 Binius 中我們只會用到兩個陣列中的 Kronecker product，所以其實只需要了解底下這個例子即可：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUAYu1JsrECqYU8soaxteQ.png" /></figure><h3>Binius example by Vitalik</h3><p>在這裡介紹 Binius 的整個流程。如果有搞懂上面所說的幾個概念的話，這張圖基本上可以秒殺。我們來一個步驟一個步驟看。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*Qf_sD-ge5xhBRDHZMT-HOQ.png" /><figcaption>small example binius, screenshot from vitalik’s post</figcaption></figure><p>不同於 KZG commitment scheme，Binius 使用的是多變量的多項式，也就是說要 commit 的多項式不只是平面上的一個曲線，而是一個超方形（hypercube）。你只要想像成原本 commit 的多項式是 f(a)，而現在則是 f(a, b, c, d)。只是前者圖像化之後是一個平面上的曲線，後者則是一個五維超方形中的四維超方形。</p><p>我們首先將這個超方形拍平成一個 4*4 的表（左上角 Flatten 的部分）。在真實的 Binius 將會是一個更大的表，不過為了方便解釋，我們拿一個小例子來說明。</p><p>接著我們將拍平後的表兩兩看作一組，在更大的 binary field 中做 Reed Solomon extension，之後再把 extend 的結果變回 binary。舉例來說第一列 [0, 0, 1, 1] 看成 [00, 11] = [0, 3]，對其做 RS，也就是把它看成 y = 3x，得到 x 代 2 跟 3 的值 [1, 2] 再把他轉換回 [1, 0, 0, 1]。依序對每一列做這樣的事情。注意到，在這個例子中的所有數字運算都是在 GF(2²) 之中，所有的乘法跟加法都是使用 binary tower 之中多變量的運算，所以如果你想用手算的話，查表比較快。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVRXYns_IvKsL-7hE0wWCQ.jpeg" /><figcaption>RS part of binius</figcaption></figure><p>在舉第二行為例子將 [1, 2] 進行拉格朗日差值法會得到 y = 3x + 1（算法如下圖）。代 [2, 3] 會得到 RS 後的 [0, 3]。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6wLRplMjoSl5-e1YxPOCQ.png" /></figure><p>最後將每一行看作是雜湊樹的 leaf，算出一個雜湊樹根，就可以得到運用 binius 運算的 commitment。</p><p>接著當 prover 要證明在這個 hypercube 之中點 r = (r_0, r_1, r_2, r_3) = (2, 0, 3, 4) 的值是 14，也就是 f(2, 0, 3, 4) = 14 ，的時候，他會需要做一些運算。</p><p>首先他取後面兩位 (r_2, r_3) = (3, 4)，運算 (1 + r_2, r_2) ⊗ (1 + r_3, r_3) = (2, 3) ⊗ (5, 4) = (10, 15, 8, 12)。接著我們將得到的陣列跟拍平後的表格相乘得到 [11, 4, 6, 1]：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fpXqAo1O_cwuEyB8rzzDQ.png" /></figure><p>Prover 將 [11, 4, 6, 1] 、以及 RS 後的表格中隨機挑選的幾行數字及其 merkle proof 傳給 Verifier 作為 proof。在這個例子我們選最後一行給 Verifier 驗證。</p><p>Verifier 要做的驗證有兩個，第一個是驗證 merkle root 的正確性。Verifier 拿 Prover 提供的陣列 [11, 4, 6, 1] 進行 RS、以及拿 Prover 隨機挑選的幾行RS 後的表格乘上 [10, 15, 8, 12] (Verifier 可以自己算這個)，這兩者算出的結果應該要一樣。如果一樣就說明 merkle root 是正確的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkX2GUjb--0N9oBUuCaZzQ.jpeg" /><figcaption>verification process I.</figcaption></figure><p>Verifier 要做的第二個驗證是驗證 (2, 0, 3, 4) 的值真的是 14。他要拿<br>首先他取前面兩位 (2, 0)，運算 (1 + r_0, r_0) ⊗ (1 + r_1, r_1) = (3, 2) ⊗ (1,0)=(3,2,0,0)，接著和 Prover 提供的 [11, 4, 6, 1] 相乘得到 3*11 + 2*4 = 14。證明了 Prover 所說的 (2, 0, 3, 4) 的值是 14。這樣就完成了整個證明的過程。</p><p>那麼現在再回來看這張圖，讀者應該可以完全知道裡面的每一個過程跟數字是怎麼來的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*Qf_sD-ge5xhBRDHZMT-HOQ.png" /></figure><h3>Summary</h3><p>Binius 透過在 GF(2^n) 中運算，可以有效的減少空間的浪費，並且在表現上比 plonky2 快了 50 倍。</p><p>在四月的時候，Irreducible 又推出了一版 FRI-Binius，將原本用 Brakedown 改良的 Binius 改成結合 FRI 和 BaseFold，降低了整個 proof size。而在今年七月的時候，Irreducible 更宣布要和 Polygon Labs 合作建立 Binius-based zkVM。之後應該會有更多與 Binius 結合的成品出現。</p><h3>Ref.</h3><ul><li><a href="https://www.irreducible.com/posts/binius-hardware-optimized-snark">Binius blog post by Irreducible</a></li><li><a href="https://eprint.iacr.org/2023/1784">Binius research paper</a></li><li><a href="https://www.youtube.com/watch?v=eTCjVTWqjj0">Binius explained by Ben Diamond (video)</a></li><li><a href="https://vitalik.eth.limo/general/2024/04/29/binius.html">Binius explained by Vitalik</a></li><li><a href="https://vitalik.eth.limo/general/2019/09/22/plonk.html">Understanding PLONK</a> by Vitalik</li></ul><p>你可以在 <a href="https://github.com/chen-yanlong/blogpost/blob/main/binius/binius.md">github</a> 找到這篇文章的 md 檔。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c978031464" width="1" height="1" alt=""><hr><p><a href="https://medium.com/taipei-ethereum-meetup/pcs-binius-explained-23c978031464">PCS: Binius explained</a> was originally published in <a href="https://medium.com/taipei-ethereum-meetup">Taipei Ethereum Meetup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[賽局論補充包 Game Theory Big Pack II.]]></title>
            <link>https://medium.com/@chen_yanlong/game-theory-big-pack-2-5aa3f491a338?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5aa3f491a338</guid>
            <category><![CDATA[nash-equilibrium]]></category>
            <category><![CDATA[game-theory]]></category>
            <category><![CDATA[zero-sum-game]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 07:29:18 GMT</pubDate>
            <atom:updated>2024-10-08T13:04:42.853Z</atom:updated>
            <content:encoded><![CDATA[<p>閱覽此補充包以將賽局理論安裝至你的系統。<br>第二份補充包：零和遊戲</p><p>Published on Oct 8, 2024 by Chen YanLong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gpEFQ__QEcqw0dRA" /><figcaption>Photo by <a href="https://unsplash.com/@mparzuchowski?utm_source=medium&amp;utm_medium=referral">Michał Parzuchowski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Table of contents</h4><ul><li>Intro</li><li>Stategic form</li><li>Security level</li><li>Minimax and Maximin</li><li>Summary</li><li>Ref.</li></ul><h3>Intro.</h3><p>經歷了五個月，已經從即將畢業的大五生，變成了已經畢業的社會新鮮失業人口，想說是時候來更新賽局知識了，於是這是第二份關於零和賽局的補充包。零和遊戲指的是一方的收益等於另一方的損失，也就是你的錢就是我的錢，我的錢還是我的錢。毫無疑問，他是一種 strictly competitive game。過年常玩的射龍門就是一種零和遊戲，所有人贏的錢等於所有人輸的錢，沒有多也沒有少，順帶一提，不要玩射龍門，太邪門了我每次都撞柱。</p><p>對了，如果你還沒看過上一篇，建議你讀讀 <a href="https://medium.com/@chen_yanlong/%E8%B3%BD%E5%B1%80%E8%AB%96%E8%A3%9C%E5%85%85%E5%8C%85-game-theory-big-pack-i-0b8118133b67">賽局論補充包 Game Theory Big Pack I.</a>。我們會講到裡面 value 的概念。</p><h3>Strategic form</h3><p>簡單說明一下零和遊戲的策略形式，我們只介紹兩個人的零和遊戲。</p><p>因為在零和遊戲當中，你的損失就是我的收益，所以寫成寫成策略形式大概會長程下面這個樣子，兩個人 payoff 的總和要等於 0。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JeL_Z6HIGBJoVc_FLitnUA.jpeg" /></figure><p>既然我們知道兩個人 payoff 的總和要等於 0，那麼多寫一個數字就顯得雜亂也不好分析，所以我們只寫一方的 payoff，有就是以下的形式：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rGKh5jGpWSXvLqd1FTusjw.jpeg" /></figure><h3>Security Level</h3><p>Security Level 中文翻作安全水準，意思是“無論對方出什麼招，我可以保證自己至少可以獲得多少”。這是一個很悲觀的想法，因為你要一直考慮對手對你的最大威脅，然後選出這些威脅之中你能獲得的最好結果。</p><p>比如說 A 股票最多跌 50%，B 股票最多跌 30%，C 股票最多跌 10%，一定要買一支的話，C 股票的跌 10% 就是我的安全水準。我們不管裡面哪一支最多可以漲到哪，我們要以最悲觀的想法去分析，在這些跌到最慘的股票當中我們可以安全到什麼程度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vulgqDSoNZt7Nu4O2ST46w.jpeg" /></figure><p>在上圖當中我標出了 player1 的 payoff，我們要找出安全水準是多少。當player1 出 s1 的時候，player2 能給出的最大威脅是 t2，也就是 0。player1 出 s2 的時候是 t3，也就是 2。出 s3 的時候是 1。那在 {0, 2, 1} 當中最大的是 2。所以 player1 的安全水準是 2。</p><p>用同樣的方法，我們可以找出 player2 的安全水準是 3。如果你算出 1 的話，確認一下我們的數字只表示 player1 的 payoff，所以在你找 player1 能給的最大威脅時，要以 player2 的角度來找最大值。那如果你算出其他數字的話，應該是我說錯了。</p><h3>Minimax and Maximin</h3><p>我們要介紹的概念是由 Von Neumman 在 1928 年所提出的 Minimax Theorem，用來解零和賽局的均衡。但這節我們著重於 pure strategy。</p><p>在上一個小節中，我們算了兩個 player 的安全水準。回想一下 player1 的安全水準，我們在最小值中找到最大值：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HK0022ieZT8y7zj_H17qjw.png" /></figure><p>我們稱這個 m̲ 為 maximin。<br>而另一方面，player2 的安全水準是在最大值中找最小值：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7ZrD64e05A9-qSVzAgZJg.png" /></figure><p>我們稱 m̅ 為 minimax。</p><p>那為什麼 minimax 是 m̅，而 maximin 是 m̲，原因是 minimax ≥ maximin，也就是 m̅ ≥ m̲。原因很簡單，我們想像 m̅在第 j 行，m̲ 在第 i 列。m̅ 是 j 行中最大的，所以他大於 m_ij，m̲ 是 i 行中最小的，所以他小於 m_ij。所以 m̅ ≥ m_{ij} ≥ m̲。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e9g7XjvSWF7JbNzndhp0ug.jpeg" /></figure><p>我們來想一想 minimax 跟 maximin 代表的是什麼意思。maximin 對 player1 來說就是一個 “我保證賽局的結果不差於 maximin”。反過來 player2 也可以 “保證賽局的結果不差於 minimax”。是不是很耳熟，當兩個人都能保證對他來說的結果不差於 v，那 v 就是這場賽局的 value。所以當 maximin 等於 minimax 的時後，那個值就是 value，而 value 就是 saddle point。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XpJvLPwN1RwryYDlggoXw.jpeg" /></figure><h4>Minimax Theorem</h4><p>在這裡簡單介紹 Von Neumann 的 Minimax Theorem，因為我會碰到繁瑣的代數運算（並且需要知道混合策略的運算邏輯），所以我就直接講結論了。</p><blockquote>如果我們允許玩家使用混合策略的話，Maximin 和 Minimax 會趨於一致。</blockquote><p>也就是在混合策略底下，絕對會有 value。<br>結束這回合。</p><h3>Summary</h3><p>從一開始我們介紹了 Zero-Sum game 的策略形式，然後我們談到了安全水準，表示一個玩家在不管對手出什麼的情況下至少可以拿到多少。接著結合 Maximin 和 Minimax 的概念，提到 value 在什麼時候會存在，最後簡單介紹了 Von Neumann 在 1928 年提出的 Minimax Theorem，描述在混合策略中的結果。</p><p>這篇比我想像中的短很多很多，因為我一開始沒有注意到這部分的大部分都是數學證明。不過我相信想知道賽局的人的大部分人應該不會想知道太艱澀的數學證明，所以我就直接講結論啦。</p><p>下一個補充包：重複賽局。</p><h3>Ref.</h3><ul><li><a href="https://plato.stanford.edu/entries/game-theory/">Game Theory</a></li><li><a href="https://www.bookfinder.com/search/?isbn=978-0195300574&amp;submitBtn=Search&amp;mode=isbn&amp;st=sr&amp;ac=qr">Playing for Real: A Text on Game Theory</a></li></ul><p>✨Donate me if you like my article: 0xddAdE2642C66A757e3850d6E8F89B02F9c63f659</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5aa3f491a338" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[賽局論補充包 Game Theory Big Pack I.]]></title>
            <link>https://medium.com/@chen_yanlong/%E8%B3%BD%E5%B1%80%E8%AB%96%E8%A3%9C%E5%85%85%E5%8C%85-game-theory-big-pack-i-0b8118133b67?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b8118133b67</guid>
            <category><![CDATA[nash-equilibrium]]></category>
            <category><![CDATA[chess]]></category>
            <category><![CDATA[subgame]]></category>
            <category><![CDATA[game-theory]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Tue, 07 May 2024 08:32:39 GMT</pubDate>
            <atom:updated>2024-10-06T09:01:56.429Z</atom:updated>
            <content:encoded><![CDATA[<p>閱覽此補充包以將賽局理論安裝至你的系統。<br>第一份補充包：每本書都會有的，後半段不太一樣。</p><p>Published on May 7, 2024 by Chen YanLong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwSI6QcBdiQ6iURozKXj2w.jpeg" /><figcaption>Photo by Riho Kroll on Unsplash</figcaption></figure><h3>table of contents</h3><ul><li>Intro.</li><li>Basics</li><li>Nash Equilibrium</li><li>Win-or-Lose Game</li><li>Value</li><li>Strictly Competitive Game</li><li>Summary</li><li>Ref.</li></ul><h3>Intro.</h3><p>待在經濟系五年下來，其實花了超過一半的時間在修系外的課，不過唯有一堂課我可以一修再修，那就是賽局論（Game Theory）。一個很重要的原因是我認為賽局是無論在何處都會用到的，當然一整個經濟學本身也是，不過賽局更令人著迷一點，而且也在我所要繼續前往的道路上有很大的需要。所以接下來會以一個快要畢業的經濟系大學生的角度來跟大家介紹一下我所知道的賽局論，以不那麼數學、也不那麼嚴謹的方式（希望）。途中若有任何我講錯或你不認同的地方。請直接在留言區吐槽不要客氣，你的吐槽是我前進的動力。</p><h3>Basics</h3><h4>History</h4><p>講到賽局理論，我相信大家唯一聽過的名字應該是 Nash 均衡的 Nash，不過在 John von Neumann (唸法是 noimen) 發表論文 《On the Theory of Games of Strategy》的時候他也才剛出生，事實上在柏拉圖的文章中就已經出現賽局的概念。賽局理論在 1944 年時由 von Neumann 和 Oskar Morgenstern 提出了數學形式，但在當時論文提出的概念只適用在特定的條件底下（零和賽局），而後在 1950 年 John Nash 才提出 Nash Equilibrium ，且證明了更普遍的賽局中皆存在納許均衡。</p><h4>Game</h4><p>何謂賽局，賽局的組成要素是什麼。<br>剪刀石頭布其實是一個很難的賽局，不過因為大家都知道，所以我用這個來解釋。<br>首先要猜拳，非得要有兩個人來猜，這兩個人稱為參賽者（players），參賽者可以出剪刀、石頭、布，這稱為行動（actions），接著行動會造成贏或輸的結果（outcomes），結果會帶有報酬（payoffs），在猜拳中的報酬可能是成就感，可能是贏了可以偷吃你的冰淇淋一口，可能是明天你要代替我去打老師的頭一下，不知道，但就是這件事在你心中的份量有多少。</p><p>所以我們大致上可以將賽局分成幾個元素：</p><ul><li>players</li><li>actions</li><li>outcomes</li><li>payoffs</li></ul><h4>Assumptions</h4><p>經濟學最大的假設就是所有人都是理性的，而在賽局中也毫不例外，正所謂不要跟瘋子玩賽局。瘋子不可理喻，不在乎自己獲得多少的人是不能拿來討論的，這其實也是賽局一個很大的問題，在某種程度來說我們都是瘋子，因為我們都不是完全理性的，也就是說，很多時候我們不知道結果對我們來說的效用（payoffs）是多少。我不知道我吃水餃會比較開心還是吃烏龍麵會比較開心，ううん，ダメです。</p><p>賽局假設的是所有參賽者都要想盡一切辦法最大化自己的效益，換句話說，每個人都要知道怎麼「算」自己的效用。對不起，我們只跟聰明人玩賽局。</p><h4>Type</h4><p>賽局有好多好多種 Type（所以應該很好追吧，沒）。<br>1. 合作 v.s. 非合作</p><p>這個應該很淺顯易懂，就是兩個人是否可以串通。大家所熟知的囚犯困境（不要再只會囚犯困境了）如果是合作賽局的話，整個結論都會大不相同。</p><p>2. 同步 v.s. 非同步</p><p>這個應該也很淺顯，就是兩個參賽者做決定是同時做決定還是不同時。</p><p>3. 完美 v.s 不完美（perfect v.s. imperfect）</p><p>這個應該也很，不淺顯。這大概是我聽過那麼多次之後，每一次都還要回去確認到底是什麼意思的賽局。這裡的完不完美指的是訊息，不完美賽局指的是後面行動的人並不知道前面行動的人做了什麼行動。</p><p>4. 完全 v.s. 不完全（complete v.s. imcomplete）</p><p>完全不完全指的也是訊息，這下你知道為什麼我每次都要再確認一次了。<br>不完全信息指的是我不知道對手的 type 是什麼，我不知道他做這個決定對他來講的 payoff 是多少。我不知道閃我大燈的計程車司機是不是土匪，所以我很難決定我要轉身扁他還是不要，大概是這種感覺。</p><p>請別太擔心這些分類，事實上當你看到一個賽局的時候一瞬間就會理解了，無須太在意他的形容詞。</p><h4>Form</h4><p>當我們想要系統化的研究一個賽局的時候，我們必須把文字傳達的故事內容轉換成能夠分析的形式，以下提供兩種形式。</p><ol><li>Normal form</li></ol><p>Normal form 是以矩陣的方式展示每個參賽者的策略以及其對應到的效益，這是一個沒辦法展示出行動先後順序的形式。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hmo6EDRl_U9eWuw-668mZw.jpeg" /><figcaption>normal form</figcaption></figure><p>以上是 chicken game 的 normal form。左側的Ｃ、Ｄ代表的是 player 1 的策略，上方的則是 player 2 的。先看 Ｄ／Ｃ 這格中的 (8, 2)，他代表的是當１玩Ｄ且２玩Ｃ時，１會獲得８，且２會獲得２。</p><p>2. Extensive form</p><p>Extensive form 以樹狀圖的方式表示，可以表示出行動的先後順序。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIP69FecVV49agI04vY74Q.jpeg" /><figcaption>extensive form</figcaption></figure><p>這個應該不難理解，１先決定要出Ｃ或Ｄ，而後２才做決定。<br>而在 Extensive form 中有時候會看到用虛線連在一起。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciUA5OrFhfW3zvBQyVHN1A.jpeg" /><figcaption>information set</figcaption></figure><p>以上表示的是在虛線連起來的兩個點中，2並不知道自己在上面那個點還是下面這個點，也就是說，他並不知道 1 做了什麼行動。也就相當於1、2是同時做決定的。</p><p>需要注意，Normal form 和 Extensive form 並沒有一對一的對應，端看你的需求而使用不同的形式。</p><h3>Nash Equilibrium</h3><p>不免俗的要談論一下納許均衡 Nash Equilibrium。<br>定義一下 NE：</p><blockquote>每個策略都是其對手策略的最佳回覆的一組策略對。</blockquote><p>白話一點來說，當我看到你出策略 a 時，我應對 a 最好的方式是出策略 b，而剛好對你來說，出策略 a 是你應對 b 的最好策略。那（a, b）就是一個 NE 。有點像是我們在策略上達成了一個共識，使得對雙方來說，相互都做到了他能做的最好策略。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4R95cnd0ssqHpuaqAx6_uA.jpeg" /></figure><p>再拿這個賽局出來說明。當２使出Ｃ這個策略時，對１來說，玩Ｃ可以得到６，玩Ｄ可以得到８。所以我的最佳回應是出Ｄ。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltfzUPWj6m7U8tQJmPF0iw.jpeg" /></figure><p>而當１玩Ｄ這個策略時，對２來說玩Ｃ會得２，玩Ｄ會得０。所以最佳回應是玩Ｃ。在這裡兩個玩家就得到一個策略上的共識，也就是上面說的，１Ｄ對付２Ｃ最好，而２Ｃ對付１Ｄ也是最好，於是就產生了一個均衡，也就是ＮＥ。</p><p>用同樣的方式，讀者可以自己嘗試在這裡面找到第二個ＮＥ。</p><p>以上的ＮＥ我們稱為 純策略 pure strategy NE。也就是這個策略 100% 只玩Ｃ或Ｄ，這裡要介紹 混合策略 mixed strategy NE，也就是我有一定的機率玩Ｃ，另外一個機率玩Ｄ。</p><p>這裡我不打算解釋如何解出 mixed strategy，只提出這個概念。在這個chicken game 中 ((1/2, 1/2), (1/2, 1/2)) 是一個 mixed strategy NE，意思是１有 1/2 的機率玩Ｃ或Ｄ，２也同樣有 1/2 的機率玩Ｃ或Ｄ，兩個策略對彼此來說都是最佳回應。</p><h3>Win-or-Lose Game</h3><p>在我們思考那些 payoff 是怎麼算出來的時候，我們不妨先把賽局再更簡化一點，只有贏或輸的賽局：Win-or-Lose Game。</p><p>這裡我們定義這個賽局</p><ul><li>參賽者有兩位：Alan、Blan</li><li>規則：Alan 丟硬幣，Blan 猜硬幣，猜中的話 Alan 輸，否則 Alan 贏。</li><li>W 代表 Alan 贏，Ｌ代表 Alan 輸。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwiSrQgCl2rG2PfC2wtshw.jpeg" /></figure><p>以上的這個圖少了一個東西，所以是錯的。如果有仔細看前面的讀者會知道我們少了一條虛線。不過先不論那條虛線，這樣的賽局是什麼意思。意思是當 Blan 做決定時，他已經知道 Alan 丟的硬幣是朝上還是朝下。有可能 Blan 是全知全能的神，也有可能 Alan 笨到沒有把硬幣蓋好被偷看到了。</p><p>總之，這樣的賽局應該很容易解，我們會使用到一個稱為 backward induction 的技巧，也就是從後面來。</p><p>Blan 在做決定時，肯定要讓自己是贏的，也就是在這裡的Ｌ。所以當 Blan 在上半部的節點時，他應該要選擇Ｈ。而在下半部節點的 Blan 應該要選擇Ｔ。那回推到最左邊節點的 Alan 做選擇時，他知道自己不管丟了Ｈ或Ｔ，Blan在下一階段都會贏，所以他是輸定了。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fh28QbxEnWjhuDtYdwSGcA.jpeg" /></figure><p>當然 Alan 不是笨蛋，他當然要蓋好自己的硬幣，所以上面這個才是正確的圖，也就是增加了 information set (那條虛線)。Blan 當然不會知道 Alan 丟出什麼硬幣，換言之就是不知道自己正處在上面的節點還是下面的節點。</p><p>我們可以把上面的 Extensive Form 轉換成 Normal Form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*iiTqTUlAStFfd4Hv-PrGcg.jpeg" /></figure><p>讀者可以用先前的方式找看看有沒有 pure strategy NE。</p><p>你可能會發現，不管怎麼樣都沒有一個互為最佳回應的最佳策略，於是你可能會想那應該有混合策略均衡吧。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8MYXPzGPIJYrhYfSo2tiQ.jpeg" /></figure><p>沒錯！不過會是多少呢，其實回到遊戲本身，拋開這些系統化的表格，你可能也會知道答案就是猜一半一半吧。</p><h3>Value</h3><p>我們再更深入解釋上面的 backward induction。</p><h4>Subgame</h4><p>子賽局，表示的是一個節點以及其後繼的所有部分，而這個初始節點不能被包在information set 中，也就是下圖中 G3 中下一個節點不能算是一個子賽局的初始節點。照這樣的定義來說，Ｇ本身也是一個子賽局，而這整個賽局擁有４個子賽局。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xy9TEEYcqpbWn2LsrTBadQ.jpeg" /></figure><h4>Winning strategy</h4><p>必勝策略，意思是在這個子賽局當中，無論對方做什麼行動自己都能贏。<br>回想一下前面的 win-or-lose game（如下圖），這個賽局中有三個子賽局。我們定義 value，如果在子賽局 H 中 player 1 有必勝策略，那這個子賽局的 value 就是 Ｗ。</p><p>在底下這張圖中的子賽局Ｇ1，Blan 有必勝策略Ｈ，所以 v(G1)=L。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vgpZestzBNDknABSYFlsg.jpeg" /></figure><p>接著我們可以簡化這個賽局如下面所示。<br>也就是將子賽局 G1、G2 替換成 value。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vx8PAXpDDZooh292wbNyOA.jpeg" /></figure><p>接著就可以很清楚的知道 v(G)=L，也就是在賽局Ｇ中，Blan 有必勝策略。</p><p>我們可以得到一個結論，在一個完美訊息且有限的 win-or-lose 賽局中必定存在 value。</p><h3>Strictly Competitive game</h3><h4>Chess</h4><p>西洋棋，如果你不知道西洋棋的話，你得去玩，那是我最愛的棋盤遊戲。</p><p>結論是西洋棋有 value。</p><p>西洋棋不是 win-or-lose game，他存在著和局，除了 W、L 之外還有一個 D（Draw）。這裡要介紹另一種賽局，稱為 strictly competitive game，簡單來說，對手如果較喜歡一種結果，那你就較討厭那種結果，你們對結果的偏好是完全相反的。</p><p>在下圖中是 player1 跟 player2 在賽局結果上的角力，越左邊的結果player1 越喜歡，相對的 player2 就越討厭。在這樣 strictly competitve 的賽局中，player1 如果可以保證自己可以做到結果不差於 v ，而 player2 也可以保證做到結局不差於 v，那這場賽局的 value 就是 v。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lYqVRXbQTKShHQcE9YxSsA.jpeg" /></figure><p>而數學家已經證明了一件事，在完美訊息的賽局中，一定能夠保證 “player1 能夠保證結局落在Ｔ中” 或 “player2能夠保證結局落在非Ｔ中”。其中 T 代表的是一個結果組合。</p><p>這個證明了 win-or-lose game 中必定有 value。結果有 Ｗ 或 Ｌ，要嘛 player1 能保證結局落在 Ｗ 中，或是 player2 能夠保證結局落在 L 中。</p><p>綜合以上，西洋棋的雙方會保證 value 存在。</p><h4>Saddle Point</h4><p>以下是一個 strictly competitive game 的 normal form，其中數字對 player1 和 player2 來說偏好是完全相反的，player1 希望數字越大越好， player2 則相反。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQW6RAt1nibroYjJlPnvIQ.jpeg" /></figure><p>利用上一小節的結論在， player1 在 2、5、2 中可以做出保證結果不差於 5 的策略，而 player2 在 6、5、6 中可以做保證結果不差於 5 的 策略，於是這裡產生了一個 saddle point，意思是同時是一個方向上的最高點也同時是另一個方向的最低點。saddle point 的值就是 value 的概念。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9YvB9SO5CUdEEanscWt2A.png" /><figcaption>saddle point, from wikipedia.</figcaption></figure><p>而在 strictly competitive game 中，這樣的點也同時是 NE。</p><p>雖然 value 跟 NE 注重的概念不一樣，一個注重結果，一個注重策略組合，但是他們的結論是一樣的。</p><h3>Summary</h3><p>第一包補充包。補充了一些賽局的基礎，歷史，形式，解賽局的方式。後面我們先進入沒有數字的世界，解釋單純只有輸贏的 win-or-lose game ，接著稍微用一點數字解釋了比 win-or-lose game 更大一點的 strictly competitive game，稍微串起了 NE 跟 value 的關係。</p><p>下一個補充包：零和賽局。</p><h3>Ref.</h3><ul><li><a href="https://plato.stanford.edu/entries/game-theory/">Game Theory</a></li><li><a href="https://www.bookfinder.com/search/?isbn=978-0195300574&amp;submitBtn=Search&amp;mode=isbn&amp;st=sr&amp;ac=qr">Playing for Real: A Text on Game Theory</a></li></ul><p>✨Donate me if you like my article: 0xddAdE2642C66A757e3850d6E8F89B02F9c63f659</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b8118133b67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Forerunner: Ethereum transaction speedup]]></title>
            <link>https://medium.com/swf-lab/forerunner-ethereum-transaction-speedup-4de9d041559e?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/4de9d041559e</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[speed-up]]></category>
            <category><![CDATA[speculative-execution]]></category>
            <category><![CDATA[os]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Mon, 14 Nov 2022 16:38:46 GMT</pubDate>
            <atom:updated>2022-11-14T17:01:32.685Z</atom:updated>
            <content:encoded><![CDATA[<p>在共識階段推測多未來並預先執行，基於限制的實際執行加速技術。<br>整理自由多名微軟研究員刊登於操作系統原理研討會 SOSP 2021 的<a href="https://dl.acm.org/doi/10.1145/3477132.3483564">《Forerunner: Constraint-based Speculative Transaction Execution for Ethereum》</a>論文。</p><p>Published on November 15, 2022 by Chen YanLong.</p><p><em>*Special thanks to ChiHaoLu for reviewing.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NVO98bwE6XuAqQXZX31Pew.png" /></figure><h4>Table of contents</h4><ul><li>Intro.</li><li>Background</li><li>Architecture</li><li>Design</li><li>Implementation results</li><li>Conclusion</li><li>Ref.</li></ul><h3>Intro</h3><p>Forerunner 可以做為一個節點的擴充功能運行，在接收各個地方傳出的交易請求後，在共識階段與執行階段中的空檔預測各種可能的未來（簡稱多未來，multi-future），並預先執行、記憶各種未來的結果，形成一個如迴路般的路徑，用以加速在狀態確定後的執行速度。</p><p>不像傳統的預測執行預測單一個未來，Forerunner 預測多種可能的未來，並將 EVM 指令在本地轉換成團隊自行研發的簡化版指令-「S-EVM 指令」方便執行。有 Forerunner 運行的節點的執行結果可以達到原先執行速度的 6.06 倍。</p><p><strong>名詞解釋：</strong></p><ul><li>預測執行（speculative execution）：是一種最佳化技術，電腦系統會根據現有資訊，提前執行一些將來可能用得上也可能用不上的指令。</li><li>S-EVM：由團隊自行研發的 register- based 類 EVM 虛擬機。</li></ul><h3>Background</h3><p>以太坊裝有準圖靈完備（quasi-Turing complete）的虛擬機 EVM（Ethereum virtual machine），使用者可以藉由編寫智能合約（smart contract, 其實就是 code）進行交易，經由 EVM 執行後更改整個以太坊的狀態（state）。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*5E5FvL6Pzwpdw6_RjHjN0w.png" /></figure><p>以太坊的共識機制在每一區塊的打包中分為兩個階段。一是共識階段，驗證節點接收從各個地方傳出的交易請求並各自打包。在舊的 PoW 共識下由最快達成雜湊後條件的節點得到打包權，新的 PoS 則由系統決定。二是執行階段，獲得打包權的節點會將交易執行，並將新的世界狀態廣播給所有其他節點。</p><p>在這樣的機制（文中稱為 Dissemination-Consensus-Execution (DiCE)）底下，交易訊息「被知道的時間」與「被執行的時間」之間的落差，可以被用來預測執行（speculative execution）交易內容，加速以太坊的交易速度。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*dBB_t0Q8Lid7lXsz2PWCEQ.jpeg" /></figure><p>因為每個節點所打包的區塊可能因為延遲、或是 gas fee 的不同而有所不同，各個交易在不同節點可能有不同的順序，而又沒有任何人可以知道哪一個節點會被「選」中，造就以太坊在共識階段有著多未來的狀態，沒有人可以預先知道下一個世界狀態為何。</p><p>在每個循環（共識階段 + 執行階段）當中，有就是每個區塊被打包的時候，交易只能在有限時間的執行階段中被執行，因此執行階段能夠處理的交易量，就是整個系統的吞吐量。Forerunner 想做的事就是加快這段期間的執行速度，達成整個以太坊系統的加速。</p><h3>Architecture</h3><p>這裡主要先介紹整個技術的架構，下一個段落會細講每一個部分。</p><p>Forerunner 由三個主要的元件組成：<br>1. multi-future predictor</p><ul><li>預測較可能被打包的交易內容</li><li>將這些交易內容整理成各種可能的 future context（FC）</li></ul><p>2. speculator</p><ul><li>預先執行 predictor 傳來的各種 FC</li><li>紀錄執行中寫入或讀取的資訊</li><li>使用 specialization 和 memoization 建構 constrained fast-path 確保 CD-equivilant</li></ul><p>（1, 2 會建構出一個 Accelarated Program（AP））</p><p>3. transaction execution accelerator</p><ul><li>在執行階段運行 AP program</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*qtAB6S0z42_qwPeacRoLyQ.jpeg" /></figure><h3>Design</h3><h4>Example used: Price oracle</h4><p>預言機是將鏈下資產的價格更新在鏈上的一種方式，這裡不探究他的動機引誘機制，單純作為方便介紹 Forerunner 流程的範例。以下是使用 solidity 撰寫的智能合約（gist 用 .js 純粹為了美觀）。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de1e0b5986b2ef2d3a3ccf66b1f73cfc/href">https://medium.com/media/de1e0b5986b2ef2d3a3ccf66b1f73cfc/href</a></iframe><p>呼叫此合約的人使用第 7 行的 submit()，提交當下的 price和 roundID 。而執行此交易（稱 Tx_e）需要讀取在打包當下的 block.timestamp（line 8），合約才能判定當下是不是在同一個 round當中，進而有不同的執行（if-else）。因此，不同的打包就會有不同的執行結果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*PEKJw91D3W9WWkXzkbKtgQ.jpeg" /></figure><p>如上圖所示，除了各個交易的順序不同之外，每個 FC 中的交易內還有可能因為該 FC 的 timestamp 不同而有所不同。</p><h4>A. Synthesis of APs（Accelerated Programs）</h4><p>下圖是整個 AP 產生的流程，每一個可能的 FC 都會產生單一 AP，而最後將這些 AP 合成在一起，成為最終由 Transaction execution accelarator 的 AP。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQq0P-dbX_UmFt7TNlklwQ.jpeg" /><figcaption>workflow for synthesizing AP</figcaption></figure><p><strong>1. Program specialization with S-EVM</strong></p><p>上述智能合約中的submit() 可以轉換成 88 個 EVM 的指令（opcode 對應到的指令），Forerunner 紀錄這些指令及其順序，並將這些指令轉換成 S-EVM （團隊自行推出的版本）指令。</p><p>EVM 與 S-EVM 的差別在於， EVM 是一個 stack-based 的虛擬機， 而 S-EVM 是 register-based。每個 S-EVM 的指令只滿足 EVM 指令中「讀、寫、計算」的其中一項功能，而轉換後的指令有助於 AP 的生成。</p><blockquote><strong>Stack-based v.s. Register-based VMs</strong><br><strong>stack-base</strong><br>運算元是以 stack 的方式儲存，運算方式會先將 stack 最上面的運算元 pop出來進行運算，再 push 回去。因此操作的指令會較為複雜，因為指令中並沒有包含儲存地址，需要將資料一個一個 pop 出來<br><strong>register-based:</strong><br>運算元以 CPU 暫存器的方式儲存，因此指令須包含運算元位置，在運算上較為快速。<br><strong>example</strong><br>在此舉一個簡單的例子: c = 20 + 7</blockquote><blockquote>stack-based :<br>pop 20<br>pop 7<br>add 20, 7, c<br>push c</blockquote><blockquote>register-based :<br>add R1, R2, R3 （其中 7 存在 R1, 20 存在 R2, 將結果存在 R3）<br>可以看到 stack-based 不紀錄位置，而是以堆疊的方式依順序拿取；而 register-based 的指令是直接指定運算元存取的位置，因此指令會較長但指令數少。</blockquote><p>將 stack-based 的 EVM 指令轉換成 register-based 的 S-EVM 指令會經過四個步驟：</p><ol><li>Decomposition 分解：將 EVM 的指令分解成更低階的指令。文中舉例將SHA256指令分解成 讀取資料 及 運算hash 的指令。</li><li>stack to register translation</li><li>Register promotion：分配資料於暫存器之中。</li><li>Control flow elimination: 刪除有關流程控制的指令，因為這個由第二步的 constaint generation 控制。</li></ol><p>經過以上的流程，以 FC1 來說，會將原先的 88 個 EVM 指令結果轉換成 S-EVM 指令，最終執行結果存於 12 個暫存器位置當中。（如下圖中的左半邊長方框內所示，v 為 register, n 為 instructions）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*0VPL5xzZgp9S34fKSzMg8Q.jpeg" /><figcaption>AP synthesis from FC1</figcaption></figure><p>而圖中的菱形框內（n5 及 n8）則為接下來要介紹的第二步生成的 constraint。</p><p><strong>2. Constraint generation</strong></p><p>為了保障 CD-equiv.，需要在 AP 的流程當中置入 “guard”。</p><blockquote><strong>CD-equivalent</strong><br>C 和 D 分別代表 control flow 和 data flow，論文指出只要兩個不同的 FC 是 CD-equiv. 的，那麼他們所遵循的指令順序就會是相同的。也就是說不同節點打包的區塊可能可以適用於同一個指令序列。<br><strong>舉例來說</strong>：<br>所有滿足300 &lt; block.timetamp &lt;= 599 &amp;&amp; activeRoundID == roundID 的 FC 都可以分類為同一種，也都遵循同樣的指令及順序。CD equiv. 可以將所有可能的未來分類，只要在該分類中有任一個 FC 被拿來做跟蹤，那跟蹤後產生的 AP 就可以預測到所有在該分類中的 FC。</blockquote><p>上圖中的 n5 及 n8 即為 control flow 的 guard。舉 n5 來說，就是控制下面這段程式碼的流程，檢查存在 v4 （也就是 EQ ( v3, roundID )） 暫存器中的資料是否為 true ，若是，則准許流程繼續往下走。若否則會停止整個 program ，如同程式碼所指示的 revert。</p><pre>if (roundID != curRoundID) {revert();}</pre><p><strong>3. Dead code elimination</strong></p><p>所有不影響 guard 判定的指令（也就是不會被 IF-ELSE 使用的 variable 賦值）都會被移除。</p><p><strong>4. Rollback-free execution</strong></p><p>在第三點被移除的指令會被丟到所有 guard 都被執行完之後，也就是 fast path 的部分，因其不會影響 guard 的判定，將他們移到後面再執行可以減少不會通過 guard 之 FC 操做多餘的指令。</p><p><strong>5. Memoization</strong></p><p>藉由預先執行並記憶化結果，當程式判定一個 FC 在某一個指令的結果和預測時跑過的結果一樣，則可以直接跳過許多已算過的指令，直接讀取已經計算好的結果，這部分稱為 shortcuts ( AP 圖中 m 的部分).</p><p><strong>6. AP merging</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*tog-cWioewqcOwjtWyrN-w.jpeg" /><figcaption>merged AP</figcaption></figure><p>經過以上五個步驟，單個 FC 可以產出如上圖這樣一個 AP，將每一個 AP 合成在一起，即成為最中實際運行的 merged-AP。</p><p>Forerunner 的技術可以做到讓執行 N 個 AP 合成起來的時間複雜度跟 N 無關，也就是可以以處理單個未來的效率處理 N 個未來。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*C-1tzIUjS7z4toJHPH7YXQ.jpeg" /></figure><p>從上圖可以看到經過 AP 的製作過程，程式碼大約減到了原本的 8.95% 。</p><h4>B. Predictor</h4><p>Predictor 會從以太坊所有待打包的交易池中挑出較可能被打包的交易，並建構可能的未來 （FC）。這些建構好的 FC 才會被丟到由以上所組成的 Speculator 製造 AP。</p><p>Predictor 會優先納入以下兩種交易：</p><ul><li>gas fee 較高者</li><li>礦工自行提出的交易</li></ul><h4>C. Prefetcher</h4><p>先到以太坊鏈上存取可能使用到的 read-set 方便 AP 運行時更快速的找到需要使用的值。</p><h3>Implementation results</h3><p>團隊使用 Geth 將 Forerunner 架設為一個運行節點，進行為期十天的測試，同時將整個過程（live traffic）記錄下來方便以相同的環境測試不同版本的 Forerunner，在這段期間之中發生了 1300 萬筆交易。而因為在真實的 Ethereum 上運行， Forerunner 必需在實際交易的有限時間之內完成。</p><p>Forerunner 可以有效運作的條件是交易訊息廣播與交易被執行之間的時間差，下圖表為時間差的反向 CDF （Cumulative distribution function, 累積分配函數）圖，說明有超過 90% 交易的時間差超過四秒 =&gt; Forerunner 是有機會有效的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*tVdHrYYJBKEXiCKL.jpg" /></figure><p>下表表示的是 Forerunner 與普通節點之間的差異，可以看到有99.16% 的交易是有經過 AP 加速的，而平均加速是普通節點的 8.39 倍。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*7YO6fjLpKiOr9D3Z.jpg" /></figure><p>在這 8.39 倍的加速之中，有些是由極端值造成的加速，有 0.53% 的交易倍加速了 50 倍以上，甚至有些超過 1000 倍。而最多交易加速了 4 倍。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*SJhEcLkimDjAM8Nr.jpg" /></figure><p>下圖表示了 gas fee 與 speedup 之間的關係。其中 gas fee 越高可以推測其程式碼的複雜度越高，可以看到程式碼複雜度越高加速程度越高的趨勢。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/0*L0XffaCFPzIr09TJ.jpg" /></figure><p>然而 Forerunner 的運行，相比普通的節點（Geth），CPU 使用度為 3.33 倍，記憶體使用量為 2.5 倍。需要花原先 12.19倍 交易執行的時間來建立 AP 及運行。</p><h3>Conclusion</h3><p>Forerunner 在以太坊這種 DiCE 模型的分散式系統中是有效的。經過 AP 的建立，可以將程式碼大約縮減到原先的 10% ， 有效的加速可以來到原先的 8.39 倍，而考量未被加速的交易之下還是有 6.06 倍的加速。</p><h3>Ref.</h3><ul><li><a href="https://www.microsoft.com/en-us/research/publication/forerunner-constraint-based-speculative-transaction-execution-for-ethereum/">Forerunner: Constraint-based Speculative Transaction Execution for Ethereum</a></li><li><a href="https://www.youtube.com/watch?v=6mh5nZPSdhw&amp;ab_channel=Veritasium">SOSP 2021: Forerunner: Constraint-based Speculative Transaction Execution for Ethereum</a></li><li><a href="https://www.codeproject.com/Articles/461052/Stack-Based-vs-Register-Based-Virtual-Machine-Arch">Stack-Based vs Register-Based Virtual Machine Architecture, and the Dalvik VM</a></li><li><a href="https://medium.com/@blockchain101/solidity-bytecode-and-opcode-basics-672e9b1a88c2">Solidity Bytecode and Opcode Basics</a></li><li><a href="https://www.usenix.org/legacy/events%2Fvee05%2Ffull_papers/p153-yunhe.pdf">Virtual Machine Showdown: Stack Versus Registers</a></li><li><a href="https://ethereum.github.io/yellowpaper/paper.pdf">Ethereum: a secure decentralised generalised transaction ledger berlin version</a></li><li><a href="https://ethereum.org/en/developers/docs/transactions/">Ethereum.org/transactions</a></li></ul><p>本文中出現的所有圖表（除第一張來自以太坊官網）皆出自 Forerunner 論文。本文的 Hackmd 原稿請參考<a href="https://hackmd.io/@chenyanlong/ryJjrEA4s">這裡</a>，有任何錯誤請不吝指教。</p><p>p.s. 這是我【111–1 Operating System】的期中報告。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4de9d041559e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swf-lab/forerunner-ethereum-transaction-speedup-4de9d041559e">Forerunner: Ethereum transaction speedup</a> was originally published in <a href="https://medium.com/swf-lab">SWF Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tornado Cash — with code]]></title>
            <link>https://medium.com/swf-lab/tornado-cash-with-code-3035d98076ce?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3035d98076ce</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[circom]]></category>
            <category><![CDATA[tornadocash]]></category>
            <category><![CDATA[zkp]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Wed, 12 Oct 2022 07:40:36 GMT</pubDate>
            <atom:updated>2022-10-12T09:41:36.180Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tornado Cash — with code</h3><p>隱藏交易訊息的解方：混幣協議 — Tornado Cash 的背後運作原理。<br>(本篇文章不包含任何對美國制裁的評論，單就技術層面進行介紹。)</p><p>Published on October 12, 2022 by Chen YanLong.</p><h4>Table of contents</h4><ul><li>Intro</li><li>Architecture</li><li>Code</li><li>Conclusion</li><li>Ref.</li></ul><h3>Intro</h3><p>以太坊，或者說整個區塊鏈都擁有的一個完美特性：透明化，是 Tornado Cash 想解決的問題。想像你的錢包裡有一百萬，你想把這些錢打到其他錢包裡，但是如果有人知道你擁有這個錢包，那他就可以在 Etherscan 上輕鬆的看到「你」把錢打進其他錢包裡。如果你想要隱藏你的交易訊息，那你可以使用混幣器： Tornado Cash。</p><p>可以想像 Tornado Cash 是一個巨大的金庫，任何人都可以使用 A 錢包存規定的固定金額（比如說100USDT、1000USDT之類的）進去(當然你可存很多次來滿足你的需求)，而協議會生成一張支票，你可以拿著這張支票用 B 錢包提領你存入的金額。當然以上只是簡化過的舉例說明，ZKP 會保證沒有人可以知道 B 錢包領出的錢是從哪一個錢包存入的。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSqcuZ8G9cDEwjYHPEI5_g.jpeg" /></figure><ul><li>當使用者越多時，交易資訊就越難以辨識。相對的，如果使用者只有一個，那就喪失隱藏交易資訊的功能。</li><li>固定金額讓交易資訊更難辨識</li></ul><h3>Architecture</h3><p>Tornado Cash 使用 <strong>Solidity</strong> 撰寫智能合約，透過 <strong>circom</strong> 編譯成的 zkSNARKs 零知識證明達成鏈上的匿名交易。</p><p>使用者存款時，需要提供 commitment 的 hash。commitment 包含兩樣東西，一個是nullifier，一個是 randomness ( 在 github 中稱做 secret )。這兩項 concat 之後成為 preimage，再 hash 之後成為 commitment。前者在提款時需要由提款人提供給合約，用於確保此個 commitment 只能使用一次；後者則增加亂數。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fkVTQBKRGanshPHds3tbng.jpeg" /><figcaption>Pedersen ( 圖中寫錯 )是一種 hash function</figcaption></figure><p>Tornado Cash 收到 commitment 之後，會將其儲存在合約內的 Merkle tree 之中。合約會更新 Merkle root，並傳回所存入之 leaf 的 index。等待提款者提款。</p><p>使用者提款時，需要提供 proof，證明其 commitment 確實存於此 merkle tree 當中。以及須一併提供 nullifier 供合約驗證此存款是否被提領過。合約確認此存款未被提領過後，便會將存款轉給使用者，並將 nullifier 存在合約當中，確保不會再有人使用同一個 nullifier 進行提領。</p><blockquote>因為有 Gas 的問題， 提款者可能會想使用 <strong>Relayer</strong>。<br>想要完全的隱藏交易訊息最好的方式 就是建立一個新的錢包去提領。由於在提款的時候合約會向提款者收取 gas fee。如果用舊錢包打幣給新錢包，那這筆打幣的交易就容易成為追蹤的對象。於是<strong>為了使 gas fee 不要成為隱藏交易訊息的敗因</strong>，使用者可以請 Relayer 代為執行提領的動作並預先支出 gas fee，扣除 gas fee 及服務費之後，Relayer 再將剩下的金額退還給使用者。</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChLi_ClikzNm8eRKg2lm4g.jpeg" /></figure><h3>Code</h3><p>Tornado Cash 在 2022 八月遭到美國政府制裁，原因是其洗錢功能過於強大，甚至連 github 的<a href="https://github.com/tornadocash/tornado-core">原始碼</a>都曾被封存。所幸近期又開放讀取。</p><p>Tornado Cash 的原始碼中包含 contracts 和 circuits 及其他資料夾，前者存放合約，後者則是存放產生零知識證明的 .circom 檔案。</p><p>整個 Tornado Cash 最主要做的事情就是 Deposit 和 Withdraw，以下會跟著這兩件事情看程式在背後做了哪些事。</p><h4>Deposit</h4><p>deposit 的函數接收一個參數 _commitment，由 Pedersen 雜湊函數將 nullifier 與 secret concat 加雜湊產生。這些東西要在線下產生。</p><pre>function deposit(bytes32 _commitment) external payable nonReentrant {<br>require(!commitments[_commitment], “The commitment has been submitted”);</pre><pre>uint32 insertedIndex = _insert(_commitment);<br>commitments[_commitment] = true;<br>_processDeposit();</pre><pre>emit Deposit(_commitment, insertedIndex, block.timestamp);<br>}</pre><p>第四行 _insert( ) 這個函數存於 MerkleTreeWithHistory.sol 中，這個檔案裡面處理所有有關 Merkle Tree 的事件，其中 Merkle tree 的建立使用了 MiMC 雜湊函數。</p><blockquote>這裡需要注意一點，Tornado Cash 所使用的是 Sparse Merkle Tree，他跟普通的 Merkle Tree 不一樣的是他在初始設定時先將每個 leaf 設定好了預設值。換言之，在儲存資料之前這棵樹已經「長」好了。</blockquote><pre>function zeros(uint256 i) public pure returns (bytes32)</pre><blockquote>zeros( )這個函數裡面寫好了每一層的預設值。</blockquote><p>_insert( ) 做的事情是將傳入的 commitment 存入已存在的 Merkle Tree 當中的其中一個 leaf 並回傳所存入的 index</p><pre>function _insert(bytes32 _leaf) internal returns (uint32 index)</pre><h4>Withdraw</h4><p>Tornado 最難達成的就是 withdraw，為了確保交易資訊的隱密性，Tornado Cash 不能接收到原始的 nullifier 與 secret，也就是 preimage。否則有心者就可以藉此推敲出交易的資訊。</p><p>因此這方面要由 withdraw.circom 在線下建立一個 ZK proof ， 再交由合約做驗證並提款。</p><pre>template Withdraw(levels) {<br> signal input root;<br> signal input nullifierHash;<br> signal private input nullifier;<br> signal private input secret;<br> signal private input pathElements[levels];<br> signal private input pathIndices[levels];</pre><p>Withdraw( )首先接收數個參數（我僅列出有使用到的），他的功能是證明使用者提供的 secret 和 nullifier 所組合成的 commitment 真的存在於 Merkle Tree 之中。</p><p>可以注意到 nullifier 和 secret 是以 private 的方式傳入，所以再傳入一個 nullfierHash 因為合約真的不知道 nullifier 的值是多少。</p><ul><li>pathElements[levels] 存的是目標 leaf 要計算到 root 中間需要 hash 過的元素。</li><li>pathIndicies[levels] 是由 {0, 1} 組成的 array，標示 path 所經過的位置要concat 在左邊或右邊。</li></ul><pre>component tree = MerkleTreeChecker(levels);<br> tree.leaf &lt;== hasher.commitment;<br> tree.root &lt;== root;<br> for (var i = 0; i &lt; levels; i++) {<br> tree.pathElements[i] &lt;== pathElements[i];<br> tree.pathIndices[i] &lt;== pathIndices[i];</pre><p>經由以上的運算後證明用 private 變數算出來的 root 和 public root 的結果是一致的。將 circom 產生的 proof 交由 Tornado.sol 的 withdraw( )進行驗證。</p><pre>function withdraw(<br> bytes calldata _proof,<br> bytes32 _root,<br> bytes32 _nullifierHash,<br> address payable _recipient,<br> address payable _relayer,<br> uint256 _fee,<br> uint256 _refund<br> ) external payable nonReentrant {</pre><p>首先確認傳入的 nullifierHash 未被使用過，若沒有使用過，合約會將這個nullifierHash 標示為已使用；若是使用過，則合約會報錯。</p><pre>require(!nullifierHashes[_nullifierHash], “The note has been already spent”);</pre><p>接著確認傳來的 root 確實是在過去的某一個時點存在過的。<br>Tornado Cash 的合約中存有歷史上所有的 merkle root，意即每次執行完_insert( ) 時都會更新新的 merkle root 在 roots[ ]裡頭。</p><pre>require(isKnownRoot(_root), “Cannot find your merkle root”);</pre><p>最後交由 verifiyProof( ) 驗證 \_proof 的真實性。此函數使用到密碼學中 Pairing 的概念，詳細的邏輯我也沒有到非常清楚。總之這個函數若是傳回 true 則代表 \_proof 是真的，false 則否。</p><pre>require(<br> verifier.verifyProof(<br> _proof,<br> [uint256(_root), uint256(_nullifierHash), uint256(_recipient), uint256(_relayer), _fee, _refund]<br> ),<br> “Invalid withdraw proof”<br> );</pre><p>若一切都沒有問題，合約就會進行轉帳的部分，結束這個交易。</p><pre> _processWithdraw(_recipient, _relayer, _fee, _refund);</pre><h3>Conclusion</h3><p>Tornado Cash 在2022年8月被列入 OFAC 的 SDN 制裁名單當中，禁止所有美國人與該協議或相關錢包地址進行互動 ( <a href="https://www.blocktempo.com/tether-wont-freeze-tornado-cash-addresses/">link</a> )。目前除了原始碼重新開源沒有其他更進一步的消息。不過 Tornado Cash 還是一個學習 ZKP 很好的教材。</p><p>Circom 所產生的零知識證明可以保證在沒有擁有真實的 preimage 的情況之下你很難做出正確的 proof。而如果你擁有真實的 preimage，則在不透漏真實的preimage 之下你可以證明自己知道這個 preimage ，這方面可以相信密碼學家的奧妙，也就是零知識證明的厲害的地方。</p><h3>Ref.</h3><ul><li>TornadoCash whitepaper v1.4</li><li><a href="https://betterprogramming.pub/understanding-zero-knowledge-proofs-through-the-source-code-of-tornado-cash-41d335c5475f">Understanding zero knowledge proofs through the source code of tornado cash</a></li><li><a href="https://medium.com/taipei-ethereum-meetup/zkp-study-group-tornado-cash-fdbb84d44b93">[ZKP 讀書會] Tornado Cash</a></li><li><a href="https://github.com/tornadocash/tornado-core">Tornado Cash github</a></li></ul><p>本篇所有圖片皆為本人製作。<a href="https://hackmd.io/@chenyanlong/BkwYrF6Gj">Hackmd原稿</a>在此。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3035d98076ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swf-lab/tornado-cash-with-code-3035d98076ce">Tornado Cash — with code</a> was originally published in <a href="https://medium.com/swf-lab">SWF Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quadratic Funding 平方募資]]></title>
            <link>https://medium.com/swf-lab/quadratic-funding-%E5%B9%B3%E6%96%B9%E5%8B%9F%E8%B3%87-465b5da3b3c9?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/465b5da3b3c9</guid>
            <category><![CDATA[liberal-radicalism]]></category>
            <category><![CDATA[quadratic-voting]]></category>
            <category><![CDATA[quadratic-funding]]></category>
            <category><![CDATA[social]]></category>
            <category><![CDATA[liberal]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Mon, 15 Aug 2022 06:40:13 GMT</pubDate>
            <atom:updated>2022-11-14T16:29:58.146Z</atom:updated>
            <content:encoded><![CDATA[<p>平衡個體效用差異與財富影響力的資金分配機制 — 從由以太坊聯合創辦人、哈佛經濟學家、微軟首席研究員共同提出的「激進自由機制（Liberal Radical Mechanism）」談起。</p><p>Published on August 15, 2022 by Chen YanLong.</p><p><em>*Special thanks to Chih-Cheng Liang for reviewing.</em></p><h3>目錄</h3><ul><li>前言</li><li>LR （Liberal Radical Mechanism）</li><li>LR 機制的結論</li><li>LR ⇒ CLR（QF）</li><li>平方募資的特性</li><li>小結</li></ul><h3>前言</h3><p>首先得要明確的告知讀者：</p><p>這篇文章的受眾有兩種，一種是經濟學相關的讀者，另一種不是。</p><p>如果你是經濟學相關的讀者，只要有修過個體經濟學，那麼以下內容應該不至於造成太大的負擔。但如果你不是，建議可以跳過打星號的部分*（<em>打星號部分為需要用到個經基礎的數學內容）</em>，我會盡力講的淺顯易懂。</p><p>以下進入正文。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGmpv-v5ysma-RoPMYrJLA.png" /></figure><p>平方募資的想法是由以太坊共同創辦人 Vitalik 和其他兩位經濟學家在論文 <strong>Liberal Radicalism： A Flexible Design for Philanthropic Matching Funds</strong> <strong>（中譯：激進的自由主義）</strong>中提出的，想法來源自該論文的其中一位作者 Glen Weyl 寫的書《Radical Markets》裡所提出的一個想法：Quadratic voting，平方投票法。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iHeoCpt7cRfJnQts0-wsHA.jpeg" /><figcaption><a href="https://www.amazon.com/Radical-Markets-Uprooting-Capitalism-Democracy/dp/0691177503">https://www.amazon.com/Radical-Markets-Uprooting-Capitalism-Democracy/dp/0691177503</a></figcaption></figure><p><strong>平方投票法是一種投票方法</strong>，他想要解決的問題是現今社會「一人一票，票票等值」（以下簡稱1p1v, 1 person 1 vote）的問題。1p1v 是很公平，但票票等值似乎不太合理。</p><p>如果以上的言論很激進，那就對了。但先別那麼快下定論。</p><p>假設今天蔡英文當選我會賺到20元 ，張三會賺10元，而李四會賠50元。那在一人一票的基礎之下， 李四肯定要賠50元了，因為一人一票的機制不允許李四擁有更大的聲量，就算他願意多付錢。也就是說，這樣的機制不允許我們因為自己會獲得的效用多寡決定自己願意付多少錢。</p><blockquote>個體應該要可以決定自己是否願意付出更多來換取更大的投票權。</blockquote><p>再一次，以上的言論確實是蠻激進的，但是是不是有一點合理</p><p>。</p><p>平方投票法最初的想法是「<strong><em>購買平方投票法（Quadratic vote buying）</em></strong>」</p><p>他的執行方式是這樣的：投票者付錢買票數，要買幾票，就要付票數的平方的價格購買。比如說你買兩張票要付4塊，買三票要9塊，四票16塊 … 依此類推。這樣的方式可以更好的將人的偏好反映在價格上：你越重視，就可以花更多錢買票，但又限制住超級有錢的人不會投太多票。</p><ul><li>其實更準確來說，是第 <em>n</em> 單位的票付出 <em>n</em> 元，因此購買 <em>m</em> 票，需要付出總共 m²/2 元。</li></ul><p><strong>平方募資想要解決的問題有一部分跟平方投票相同</strong>，他想解決個體偏好差異應該要對發言權有所影響這件事，但這只是其中一項。另一個重要的議題，就是解決公共財的搭便車行為。</p><h3>公共財難題一：搭便車問題</h3><p>QF （Quadratic funding）的介紹文通篇一律要從公共財提起，因為 QF 就是一個為了解決公共財搭便車問題的解方。那又因為大家不知道什麼是公共財+搭便車又是怎麼回事，所以這裡勢必要介紹一番。</p><p><em>（經濟系的同學</em><strong><em>可以直接跳過</em></strong><em>這段，這會聽起來有點繁瑣。）</em></p><h4>公共財</h4><p>我覺得這裡不需要拿出解釋公共財的那個四宮格來提醒大家其實高中的公民課我們都有學過，但是為了方便解釋還是搬出來一下，但是我簡化了一下。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*wQlUABTDz19hUOiF6VSoPA.png" /></figure><p>左下跟右上兩個叉叉並不是不存在，而是在今天不太重要。</p><ul><li><strong>排他</strong>：付錢才能用</li><li><strong>競爭</strong>：你用了別人就不能用</li></ul><p>以上解釋不完全正確，公民老師們可能還會吐血，不過為了方便解釋所以。</p><p>私有財其實聽名字很好理解是什麼，我們身邊的鉛筆、擦子、財產基本上都是私有財。公共財是那些你不能限制誰可以使用、也不是你在用別人就不能用，比如說公園、陽光…。</p><p>公共財因為有這樣的性質，所以他在效益的計算上跟私有財不一樣，私有財的效益很容易計算，因為只有一個人能使用，效益很明顯就是消費的那個人使用這個物品所獲得的效用。但公共財不一樣，<strong>他的效益要是該單位公共財對所有人的效用加總，而且每個人獲得的效用都不同，所以很難計算</strong>。舉例來講，你家門前要蓋一個公園，對你的效用是5，對隔壁老王的效用是10，那這個公園的效用就是 5 + 10 = 15。當人數龐大時，總效益就會變得難以估計。</p><h4>搭便車問題</h4><p>延續上面的舉例，如果蓋一個公園的成本是8，那你會蓋嗎？（不會）</p><p>隔壁老王會蓋嗎（會），為什麼？（因為他付出 8 可以獲得 10 的效用）</p><p>OK，所以老王會出錢蓋公園，那你可以用嗎？（可以，因為公園是公共財）</p><p>那麼誰在搭便車，誰是那個不出錢又可以爽爽用公園的人？（你）</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*bkWz6eAkqnU0pW5Hm6Wrvw.jpeg" /><figcaption><a href="https://medium.com/powershare/elinor-ostrom-on-tragedy-of-the-commons-a47bedcc4c2e">https://medium.com/powershare/elinor-ostrom-on-tragedy-of-the-commons-a47bedcc4c2e</a></figcaption></figure><p>所以我們得出了一個結論：公共財如果由個人提供，會由對公共財比較<strong>重視</strong>的人提供。</p><p>以上的例子稍嫌極端了一些，不過在正規的數學證明之下可以導出一個更重要的結論：</p><blockquote>由個人所提供的公共財不會最大化總體效益。</blockquote><p>也就是說隔壁老王蓋的公園大小不會讓總體效益最大化。因為人都是自私的，他只會顧慮到公園夠不夠他用。</p><p>其實再更貼近一點的例子，就是<strong>我現在在寫的這篇文章，其實也是一種公共財</strong>。</p><p>這篇文章發佈到網路上所有人都可以看，也都不需要付錢。大家可以獲得整理過後的知識（獲得效用），而我需要付出大量時間撰寫這篇文章。所有人獲得的效用加總或許很大，但大家獲得的效用其實不會回到我身上，撇除掉我會獲得的關注或是日後流量對我的好處不講，自私一點來說，我幹嘛要寫。（所以快捐款給我~）</p><p><em>（</em><strong><em>經濟系可以回來了</em></strong><em>）</em></p><p>公共財的提供就是這麼一個大難題，公共財被建立好之後所提供的效用非常大，但沒有人會願意提供。</p><p>於是我們出現了募資的方式。比如說基金會募款、紅十字會募款等等。藉由大眾提供資金的方式去為了一個更大的好做貢獻。</p><p>但是簡單的募款操作仍然存在一些問題。如同我最一開始所提的例子，個體偏好的差異也應該要納入考量，才能最大化募資的效益。而如果我獲得的效益很大，但我卻沒有足夠的資金怎麼辦。</p><blockquote>在這裡我必須釐清一個點，平方募資並沒有辦法解決「錢從哪裡來」這個問題。而是在解決「錢如何分配」的問題。比如說有一百萬，我要怎麼決定多少錢蓋公園、多少錢蓋火車站。</blockquote><p>以下是我整理出來的思考路徑，我想這樣可以更好的理解我們現在在解決什麼問題、以及我們如何解決。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Fk0-m-PggHgT3tqi7LA_Q.png" /></figure><h3>公共財難題二：1p1v，1d1v</h3><p>這其實是一個資金分配的問題。在做資金分配時往往會遇到一個難題，就是我應該落實絕對平等，也就是一人一票，還是有錢的人決定權更大。</p><h4>tradeoff</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*ykpBp-vGM8k0UPmW1UIlwg.png" /></figure><p>以上兩者都有他會造成的問題，要在這兩種之間做取捨，而 QV 就是折衷後的結果。得到越多的人會付出越多，但是每單位付出的金錢隨著他所獲得的效用而增加。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*brfG190L-GEAndJO4oeEUA.png" /><figcaption><a href="https://vitalik.ca/general/2019/12/07/quadratic.html">https://vitalik.ca/general/2019/12/07/quadratic.html</a></figcaption></figure><p>可以看看上圖，橫軸為願意付出的金錢，縱軸為獲得的票數（話語權）。</p><p>中間的 QV 可以使得資助少量金錢的人擁有一定的話語權，又不會使資助大量金錢的人擁有絕對的決定權。</p><h3>簡單整理一下</h3><p>QF 想要解決什麼問題</p><ol><li>個人提供公共財：效益不夠大、搭便車問題</li><li>一人一票決定建什麼公共財：無法反映個體偏好的差異</li><li>一元一票決定建什麼公共財：決定權掌握在有錢人手上</li></ol><p>**其中2, 3點能用 QV 的方式解決</p><p>為了解決第一點，一些現有的解決方法如下：</p><ol><li>收稅：由政府收稅建公共財</li></ol><p>2. 轉變成私有財：將我的文章轉變成付費解鎖</p><p>3. 用道德、文化規勸大家捐款：慈善團體募資</p><p>而以上的方法都有他的限制以及不效率的地方（這可以用數學證明），於是由 Vitalik 和其他兩位經濟學家以 QV 的基礎提出了另一種機制：能夠遏止搭便車，又能顯示個體偏好的方法，</p><p><strong>Liberal Radical Mechanism ( LR ) 自由激進機制。</strong></p><p>這個機制其實不是平方募資，而是他的一個基本版，不過我們需要先了解這個。</p><h3>*LR （Liberal Radical Mechanism）</h3><p>以下會需要基礎個體經濟學的知識，若沒有基礎的讀者可以嘗試讀看看，若看不懂也不要緊，可以看下一段結論的部分。</p><h4>Notation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*G5Dko8qlv1lF54vR2RpthA.png" /></figure><p>如果你覺得公民這個詞很難懂，可以把他想像成捐款者，只不過這個捐款者也同樣會因為公共財而受益。</p><p>由以上的表示方法可以得到：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*md0cYglmF2ztHafqbeg_5g.png" /></figure><p>每個公民獲得的效用等於所有公共財提供給他的效用減去他付出的成本，注意到這裡的效用函數我們已經將他轉換成貨幣量了，意思是<strong>他的單位是「元」而不是「單位」</strong>。簡單的單調轉換可以做到這件事，並且不影響偏好的比較，不過這不在我們討論的範疇。</p><p>假定沒有稅收。</p><h4>最佳解的 F.O.C</h4><p>我們想要最大化公共財 p 所提供的總效用，進而計算出對整體社會最好的解：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*9t-BAMNK3jUWnQqr-ttHEQ.png" /></figure><p>經過簡單的一階微分會得到 F.O.C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*vX8Wz1BWP1OA1BIZLX-NCA.png" /></figure><p>其中</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*AnHAXq05VDpNO0hl2xH_hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*P-Y-vjCGiGfJAj7GDX9I-A.png" /></figure><h4>LR mechanism</h4><p>Liberal Radical 機制假定：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*aKccTxf0Xt0SALEDuXUeiA.png" /></figure><p>也就是我們建立一個機制讓公共財 <em>p</em> 所獲得的總募資量等於各個投資者提供的資金的開根號總和的平方。我們晚點再來解釋這個式子的直觀意義方便跳過此段的讀者一起看。</p><p>現在我們先來看看這樣的假設可以導出什麼結果。</p><p>基於以上的假設，個體公民對於公共財 <em>p</em> 所獲得的總效用（我偷用 π 表示）：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*6IQvAQUqugQ2I2njxXslNw.png" /></figure><p>一樣，為了找出個體公民的最佳解，我們做一階微分 = 0 找 F.O.C</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*Ua4PEGuwNSQbQNKLurcXYw.png" /></figure><p>整理一下：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*XEJ18A4SIp1LdQZ-C-W4Tg.png" /></figure><p>這串就是對個體公民的F.O.C.，很直觀的來看這個式子：</p><ul><li>等式左邊：個人影響力佔總影響力（都是開根號後）的比例</li><li>等式右邊：在該單位對該公民的邊際效用</li></ul><p>這是一個很好的性質，也就是說剛好符合我們想要的，當個體在尋找最佳解時，能夠獲得越多邊際效用的人會願意付出得金錢佔比就越多。</p><p><strong>我們可以用一個人所捐款的量來回推公共財對他的邊際效用，</strong>並且用一個人獲得的效用來衡量他應該擁有多少話語權，所以反過來說，<strong>一個人想要擁有越多話語權，他就必須付出更多，而每單位所需要提供的資金隨著他的效用上升而上升。</strong>如此一來可以解決1p1v, 1d1v的問題。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Cq7AsBpnOdJkDbL3m1FXmQ.png" /></figure><p>你會發現等號左邊就等於 1 ，就正好跟公共財最佳解的等式一模一樣。</p><h3>LR 機制的結論</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/1*PZ-5MIyu6fJgUCqgMNXMAQ.png" /></figure><p>這個式子無論如何都希望讀者可以看懂，我會把這個式子用白話文來翻譯：</p><ul><li>等式左邊：一個公共財獲得的總募資量。</li><li>等式右邊：每個捐款者的捐款量開根號後加總起來再平方。</li></ul><p>我們想要讓公共財可以獲得的捐款量 = 每個個體提供的捐款的某個函數，而非直接是所有捐款的加總。</p><p>這是以上的數學模型假設，而這個假設可以讓我們導出非常好的結論：</p><ol><li>個體的選擇會剛好讓公共財的提供最大化社會利益</li><li>可以在投票權上做出權衡 （QV）</li></ol><p>很神奇吧！我也這麼覺得。</p><p>我們解決了這篇文章一開始提到的公共財提供問題。<strong>第一個問題：</strong>公共財由個人提供會有不足，因為個體的偏好沒有誘因讓他們為公共財提供更多的資金。而在 LR 模型假設下，個體的最佳解剛好等於公共利益的最佳解。</p><p><strong>第二個問題</strong>是投票權上的權衡，如同以上所提到的 QV 帶來的結論，我就不再贅述。</p><blockquote>我想岔出來提一個需要注意的點。上面數學模型的推導方式，是在資助者「完全瞭解」LR 機制的前提下進行，因為我們在計算資助者會想資助多少時，已經將開根號加總平方這件事列入他的效益函數裡，自然也就代表我們得出來的結論是基於他已知計算的方式為前提。</blockquote><p>而綜合以上想要建立出一個募資方式，將 LR 機制建構成實際可以使用並且有效率的募資方式，這裡我們要介紹另一個 LR 機制的改良版， CLR ，也就是平方募資。</p><h3>LR ⇒ CLR（QF）</h3><p>LR 的機制使得實際投入的資金無法與真實投給公共財的資金相等。</p><p>事實上 <strong>LR 會將資金放大。</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*q8Uz_zh2hKMEuATcSoAKUA.png" /></figure><p>回來看一次這個式子，這次我們舉個例：</p><p>假設A、B兩人各捐款100元，那麼實際上公共財專案會獲得的金額是多少呢？</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*uluZp20Y_dT0y8vTQdMZFA.png" /></figure><p>兩個人總共投入200，但卻要給專案400元，那麼多出來的錢要從哪裡來？</p><p>在LR的機制裡我們假設有一個源源不絕的金錢從某個地方流入，但是真實世界哪有那麼好康的事情，於是我們必須導入另一個機制來限制無上限的金錢需求。也就是</p><p><strong>CLR （Capital- constrained Liberal Radical mechanism）資金受限的自由激進機制，而這個機制才是我們今天要提到的 平方募資。</strong></p><p>CLR 機制的重點在於，資金的來源來自兩個地方</p><ul><li>資金池（一筆準備被分配的金錢）</li><li>投票募資的捐款</li></ul><p>以下是用數學式表達的 CLR 機制</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*_oLh3FUiEdmJXKxDXbJXFg.png" /></figure><p>資金池提供者通常為大機構，他們將錢投入池中，這些資金會在最後計算分配給參與募資的許多項目。分配比例由投票募資的結果決定。而投票募資者以金錢作為票對他們有興趣的項目進行資助。</p><p>這個 α 會隨著配對池中資金的多寡進行調整以確保足夠，所以他同樣由募資投票者數量與所提供的資金多寡決定。而剩下的部分就由投票者真實投入的資金做調配。</p><p>（一直沒有解釋 Φ 就是機制的 notation）</p><blockquote>我將之稱為募資投票者，意思是他雖然表面上進行簡單的募資捐獻，但他所提供的數量會在幕後作為一種投票的數值計算最後資金池中資金的分配方式。</blockquote><h3>平方募資的特性</h3><p>平方募資有個很重要的特性是：<strong>同樣數量的資金，若是由越多人共同提供放大效果越大。</strong></p><p>這麼講可能有點含糊，我舉個例子：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*wuk_T1AVr_D1NLeq78Gq0g.png" /></figure><p>假設同樣一筆資金100元，由兩種分配提供：</p><p>第一種、1個人出100元</p><p>第二種、4個人各出25元</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*CtBZJgxYmmWruBwa5i7HrQ.png" /></figure><p>再更極端一點，100個人各出1元，則最終則會輸出10000元，整整多了100倍。這就是平方募資厲害的地方，人數多寡遠遠比金錢多寡來得更為重要。換言之，就算你只能提供少少的金錢，你也能造成巨大的回饋，因為重要的是你這個人的參與，而不是你捐款的數量。</p><p>以下這個圖是我在其他文章看到的，連結會附在下方，這個圖很清楚的具象化這個概念。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*HhyRi1_-vFbFKAlMDZxb9w.png" /><figcaption><a href="https://vitalik.ca/general/2019/12/07/quadratic.html">https://vitalik.ca/general/2019/12/07/quadratic.html</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*oyDF26NjHgeDHueOa1HuSw.png" /></figure><p>數學表示多出的部分面積，也就是黃色面積：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*biuMsenWOwYsjkXbQOIIgA.png" /></figure><p>現在想想你把綠色的方塊切到最小，小到看起來會像是在大方塊中的對角線，那一條線的面積就會是投票者所提供的資金（小到不行），而卻還是可以建構出同樣面積的大正方形。其中大部分的地方都是額外多出的部分。</p><p>試想另一種方式，投票者只有一個，那為了達成這麼大的方塊，他就必須要提供一個邊長就等於大正方形的資助，事實上也就是他的資金完全沒有放大效果，全部由他來資助。</p><p>還是得要再一次提醒，那些因放大效果所變出來的錢並不是憑空出現，而是由某些大型的個體，如基金、財團等提供。<strong>平方募資只是將你手中的錢不僅僅當作是錢，還當作是選票來衡量你獲得的效用，進而決定哪一個公共項目應該獲得更多資金補助。它是考慮總體效用的一種資金分配方式。</strong></p><h4>平方募資平台</h4><p>本篇文章主要在介紹平方募資的背景知識以及其特性的推導。對於應用上雖然非常重要，不過礙於篇幅，再請有興趣的讀者自行選讀。現有的平方募資平台主要有<a href="https://gitcoin.co/">Gitcoin</a>、以及<a href="https://eth2clrfund.netlify.app/#/">clrfund</a></p><p>以下提供兩篇基本介紹給各位：</p><ul><li><a href="https://www.gemini.com/cryptopedia/gtc-crypto-gitcoin-bounties-web3-gtc-token"><strong>Gitcoin (GTC): A Marketplace for Open-Source Development</strong></a></li><li><a href="https://medium.com/taipei-ethereum-meetup/clrfund-%E7%B0%A1%E4%BB%8B-1d78d0aa5673"><strong>CLR簡介</strong></a></li></ul><h3>小結</h3><p>我們從最一開始的兩個問題出發：搭便車問題、投票權問題（1p1v, 1d1v），我們想要提供一個解決方法。於是在 LR 的機制底下，我們得出了良好的結論。然而， LR 在實務上難以實現，因為他所造成的資金放大效果，而資金無法憑空出現。於是我們找到基於 LR 所做出的改良 CLR，也就是 QF ，以資金池有限作為前提的募資機制。</p><p>我個人認為平方募資比較像一種方法，他藉由參考一個人願意出多少錢來回推他的效用佔多少，而藉由這樣回推的過程再去決定他應該佔有多少話語權。能夠讓金錢多寡不會佔最終決定的太大比例，而又重視多少人願意提供資金給該公共財，同時平衡了金錢跟效用。又因為機制的設計，使得金錢能力較少的人也能用少少的錢換得巨大的影響力，避免了搭便車問題。若平方募資的觀念得以普及，勢必可以提升社會整體效益。</p><p>— — — —</p><p>最後得要很抱歉的說，因為表達數學式子的關係，很多地方是用截圖的方式，造成版面有跑掉。跟以往一樣我將我 notion 的原稿附在<a href="https://chenyanlong.notion.site/Quadratic-Funding-464556a9d81a48378a05651d26952cac">這裡</a>，方便需要<em>katex </em>版本數學式子的人使用。</p><p>*圖片底下皆有標註來源，若無標註則為我本人製作。</p><h3>Reference.</h3><ul><li><a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3243656"><strong>Liberal Radicalism: A Flexible Design For Philanthropic Matching Funds</strong></a></li><li><a href="https://vitalik.ca/general/2019/12/07/quadratic.html"><strong>Quadratic Payments: A Primer</strong></a></li><li><a href="https://daaab.medium.com/%E6%B3%95%E5%AD%B8-%E7%B6%93%E6%BF%9F%E5%AD%B8%E8%88%87%E5%8D%80%E5%A1%8A%E9%8F%88%E7%9A%84%E6%9C%80%E6%BD%AE%E4%BA%A4%E6%9C%83-%E6%BF%80%E9%80%B2%E5%B8%82%E5%A0%B4-radical-markets-%E6%8F%90%E6%A1%88%E5%85%A5%E9%96%80-%E5%90%AB%E9%96%B1%E8%AE%80%E6%B8%85%E5%96%AE-989032d9c2c5"><strong>法學、經濟學與區塊鏈的最潮交會 — 激進市場（Radical Markets）提案入門 [含閱讀清單]</strong></a></li><li><a href="https://www.youtube.com/watch?v=LrdG-pZw2Fc&amp;ab_channel=WhiteboardCrypto"><strong>Quadratic Funding — Crypto Charity that SUPERCHARGES donations</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=465b5da3b3c9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swf-lab/quadratic-funding-%E5%B9%B3%E6%96%B9%E5%8B%9F%E8%B3%87-465b5da3b3c9">Quadratic Funding 平方募資</a> was originally published in <a href="https://medium.com/swf-lab">SWF Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polkadot -Object, Tokenomics & Protocols]]></title>
            <link>https://medium.com/swf-lab/polkadot-object-tokenomics-protocols-b58652637a9c?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b58652637a9c</guid>
            <category><![CDATA[polkadot]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crosschain]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 04:55:48 GMT</pubDate>
            <atom:updated>2022-11-14T17:12:27.253Z</atom:updated>
            <content:encoded><![CDATA[<p>a more comprehensive look at Polkadot. It is highly recommended to read <a href="http://Edit  Come from Yilan, Taiwan.  study in NTU ECON, do my own research on blockchain, learning smart contract."><strong><em>Polkadot briefly explained</em></strong></a> first.</p><p>Published on July 28, 2022 by Chen YanLong.</p><h3>table of contents.</h3><ul><li>Objects</li><li>Tokenomics</li><li>Protocols</li></ul><h3>Objects</h3><p>We introduced about main objects of Polkadot briefly in last article, today we’re gonna look deeper into those paraobjects.</p><h4>Parachains</h4><p>Parachains are chains that are attached to the relay chain, it can be a blockchain, a smart contract chain, privacy chain, and so on.</p><p>Parachains are maintained by collators, collators collect information which need to attach to this parachain, and they provide candidate blocks to the relay chain validators. Parachains are not required to have their own native token, neither are they restricted to have one.</p><p>Polkadot provides 100 <strong>parachain slot</strong>, there are three types of objects to be allocated:</p><ul><li><strong><em>Common good parachains</em></strong></li></ul><p>Parachain slots reserved for functionality that benefits the ecosystem as a whole. The governance system will decide whether to allocate or not.</p><ul><li><strong><em>Auction parachains</em></strong></li></ul><p>these parachains gain slot by participating in an auction with two period candle auction ( see <a href="https://wiki.polkadot.network/docs/learn-auction#polkadot-implementation">here</a> )</p><ul><li><strong><em>Parathreads</em></strong></li></ul><p>described below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*QSNPB3fIaajvVjzgIcVkgg.png" /></figure><h4>Parathreads</h4><p>Parathreads are parachains that temporarily participate in Polkadot’s security without needing to lease a dedicated parachain slot. In fact, parachain is like paying the rent of a slot, and parathreads is like paying for the production of blocks. You can see it as a <a href="https://medium.com/polkadot-network/parathreads-pay-as-you-go-parachains-7440d23dde06">pay-as-you-go parachain</a> .</p><p>Parathread is for those who does not need the whole use of a parachain but needs the participation of the shared security of Polkadot, they bid for the production of blocks ( it is kind of like paying gas fee to make your transactions included in Bitcoin ). Parathreads participate in the auction in <em>parathreads pool, </em>the one who wins gets his transactions onto the chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QgC_Lrpw0TDUEko46cTKZA.png" /></figure><h3>Bridges</h3><p>bridges are special blockchains that allow chains on Polkadot to communicate with <em>external blockchains</em> (like Ethereum or Bitcoin). There are three ways to build a bridge.</p><ul><li>via bridge pallet (Kusama, testnet for Polkadot)</li><li>via smart contract (Ethereum)</li><li>higher-order protocol (Bitcoin)</li></ul><h3>Tokenomics ( mathematically )</h3><p>a deep look at the native token DOT of Polkadot, inflation determination, reward to validators, and the usage of DOT included.</p><h4>Parameters</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*tqc10YZmGxlEhyHghmjOIQ.png" /></figure><ul><li>I am sorry that I have to do the paste thing since medium does not support mathematical expressions, if you want to see the original one, I’ll paste my notion site at the bottom.</li></ul><h4>Functions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gGvpoW1hqJ3VGUzbn8kU4Q.png" /></figure><ul><li><strong><em>x- axis</em></strong>: staking rate</li><li><strong><em>y- axis</em></strong>: inflation rate ( for blue line), interest rate ( for green line)</li><li><strong><em>Blue line</em></strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*tuSPpZedcWONt2KJMBPcTA.png" /></figure><ul><li><strong><em>Green line</em></strong><em>:</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*CORC6l-oCYbSHhS6B0Ku7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*2GMfaN2REap-ZEny_BfLtA.png" /></figure><h4>Payment mechanism</h4><p>Validators are rewarded by performing the following actions, they get points for doing these things, and the points determines how much their rewards are:</p><ul><li><em>20</em> points for each validity statement</li><li><em>20</em> points for each (non-uncle) block produced</li><li><em>2</em> points (to the block producer) for each reference to a previously unreferenced uncle</li><li><em>1</em> point to the producer of each referenced uncle</li></ul><p>the rewards will be calculated every era, and will be the proportion of points earned by individual validator to points earned by all validators times the target total payout. That is, mathematically,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*TaO4NeKxKGGPnc06ttH6sg.png" /></figure><p>note that the target total payout is determined by the calculation of <em>i(x)</em>, as mentioned above.</p><h4>Validator slot</h4><p>Each validator slot consists of 1 validator and multiple nominators. Validators and nominators gets reward in validator slot.</p><blockquote>Simple explanation, if there are 26 validators, there would be 26 validator slot. Every nominators who nominates (stakes) for that validator will be count in A’s validator slot, if 5 nominators stakes for validator A, then there will be 5 nominators in validator slot A.</blockquote><p>Each validator slot (A~Z) gets the reward as mentioned above (according to how many points the validator in that slot gets), and that reward will be distributed with two steps:</p><ul><li><strong><em>commission fee</em></strong></li></ul><p>。the commission fee is announced by the validator in advanced</p><p>。commission fee will first be distributed to the validator</p><ul><li><strong><em>remainder</em></strong></li></ul><p>。total reward minus the commission fee</p><p>。the remainder will be shared proportionally to their stake within the validator slot</p><p>。this part of reward will be shared to both staked-validators and staked-nominators</p><p><strong>Mechanism advantages:</strong></p><ul><li><strong><em>Incentive to nominate less popular validators</em></strong></li></ul><p>。less popular validators means a more distribution of reward</p><p>。lower entering barrier to become a validator</p><p>。more decentralized</p><ul><li><strong><em>market efficiency</em></strong></li></ul><p>。commission fee can be anounced at any price</p><p>。higher commission fee attracts less nominators, which could lead to a risk not being able to become a validator caused by low nomination.</p><p>。validators with high reputation can have the market power to charge more fee</p><h4>Treasury</h4><p>a fund which is raised to pay for developers, apply changes, and to keep the system running.</p><ul><li>+minting</li><li>+transaction fees, slashing ( part of )</li></ul><p>which, could leads to inflation</p><h3>Protocol</h3><h4>NPoS</h4><p>this cycle repeats everyday:</p><ol><li>nominator publishes a list of validators he trusts and stake DOTs.</li><li>system select the validators with massive DOTs staked.</li></ol><p><em>a.</em><strong><em> fair representation</em></strong></p><p>the nominators who stakes at least “average DOTs staked per nominators” is guaranteed to have at least one validators trusted to be elected. As an example, the first nominator bellow will have validator A elected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*yruxfGxiOKLC19QOYOVgAw.png" /></figure><p><em>b. </em><strong><em>security</em></strong></p><p>the level of security of an election = the minimum amount of backing of any elected validator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*lbpyQocB0cPpyeDW45dWSg.png" /></figure><p>c.<em> </em><strong><em>the system splits the nominators’ stake into validators’ backings of roughly equal size.(it is more secure)</em></strong></p><p>d. <strong><em>the election rule is too complicated to explain, see </em></strong><a href="https://research.web3.foundation/en/latest/polkadot/NPoS/3.%20Balancing.html"><strong><em>this</em></strong></a><strong><em> if you are interested in.</em></strong></p><h4>XCM(Cross-Consensus message format)</h4><p>XCM is a “<strong>format</strong>” of how cross-consensus transfer should be performed.</p><p>Note that this is a FORMAT, I am sorry, but it has to be explained here.</p><p>The reason why I mention it here, is because it involves protocols that are important to transferring messages between chains.</p><p><strong>1.VMP (Vertical Message passing)</strong></p><p>this protocol allows message transfering between parachains and the relay chain. there are two part of it:</p><ul><li>UMP(upward)</li><li>DMP(downward)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*GC8UM_ADLUMTd9PI5zSRfQ.png" /></figure><p>A message from parachain1 uses UMP to transfer to the relay chain, and then the relay chain uses the DMP to transfer it to parachain2. Then, it communicates.</p><p><strong>2.//XCMP</strong></p><p><em>Cross-chain message-passing protocol</em></p><blockquote><em>! XCMP is still under development. HRMP is now implemented as a substitute of XCMP, and it is useful, only that it needs more resource than XCMP does. The lowest different is that whether transactions are stored as a Hash or not.</em></blockquote><blockquote><em>** HRMP=Horizontal Relay-routed Message Passing*</em></blockquote><blockquote><em>** </em>I noticed that it said “XCMP (sometimes known as HRMP)” on <a href="https://github.com/paritytech/xcm-format">github of XCM format</a> , but it seems that it is a little bit different according to <a href="https://wiki.polkadot.network/docs/learn-crosschain">Polkadot’s website</a>.</blockquote><p>This protocol makes it possible for different blockchain ( parachains ) to communicate with each other, and it does NOT need to pass the relay chain. Once the parachains establish “channels” between them, they are able to transfer message directly. To open a channel, deposit need to be put down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*j5QGp7zrHHNaMAzIXvO0wA.png" /></figure><p>two types of channels according to directions of message flow:</p><ul><li><strong><em>Unidirectional XCMP Channel</em></strong></li></ul><p>。messages flow in one direction</p><p>。unique configuration</p><p>。more flexible</p><ul><li><strong><em>Bidirectional XCMP Channel</em></strong></li></ul><p>。messages flow in both directions</p><p>。same configuration for both directions</p><p>。more efficient</p><p>the message transfering process is briefly illustrated below, as the explanation would be too cumbersome, I’ll just skip it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RK0O62FZCYGTzinc9YTX6Q.png" /></figure><p>— — — — — — — — — — — —</p><p>Next part- <strong>Security(Cryptography), Networking and Others(Kusama)</strong>… on Polkadot, of course. Still working on it ( haven’t started actually ), cheers.</p><p>Any problem or mistake, please contact me, appreciate. And thanks for reading.</p><p>the original article I wrote on notion comes <a href="https://chenyanlong.notion.site/Polkadot-Object-Tokenomics-Protocols-e9d6648ea45c46a1a76f7cd32290f6b1">here</a>, welcome to have a look if you need <em>Katex</em> version of mathematical expression.</p><h3>Reference</h3><ul><li><a href="https://research.web3.foundation/en/latest/index.html">https://research.web3.foundation/en/latest/index.html</a></li><li><a href="https://polkadot.network/">https://polkadot.network/</a></li><li><a href="https://polkaworld.medium.com/whats-the-significance-of-xcmp-to-polkadot-ba9c4a283fd1">https://polkaworld.medium.com/whats-the-significance-of-xcmp-to-polkadot-ba9c4a283fd1</a></li><li><a href="https://medium.com/polkadot-network/parathreads-pay-as-you-go-parachains-7440d23dde06">https://medium.com/polkadot-network/parathreads-pay-as-you-go-parachains-7440d23dde06</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b58652637a9c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swf-lab/polkadot-object-tokenomics-protocols-b58652637a9c">Polkadot -Object, Tokenomics &amp; Protocols</a> was originally published in <a href="https://medium.com/swf-lab">SWF Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polkadot briefly explained]]></title>
            <link>https://medium.com/swf-lab/polkadot-briefly-explained-9cdea409bf04?source=rss-32f3623574bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9cdea409bf04</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crosschain]]></category>
            <category><![CDATA[polkadot]]></category>
            <dc:creator><![CDATA[Chen YanLong]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 04:53:07 GMT</pubDate>
            <atom:updated>2023-01-08T18:52:25.763Z</atom:updated>
            <content:encoded><![CDATA[<p>a brief explanation of Polkadot, published on July 28, 2022, by Chen YanLong.</p><h3>table of contents.</h3><ul><li>Introduction</li><li>Architecture</li><li>Advantage</li><li>Consensus</li><li>Tokenomics</li></ul><h3>Introduction</h3><p>Polkadot is a protocol which <strong>allows blockchains to connect to different blockchains</strong>, it allows any type of data, tokens to be sent between any type of blockchain. Polkadot is developed by Ethereum co creator Gavin Wood, and was launched on May 26, 2020.</p><p>Imagine you want to build a game chain, you need different functions, and you wouldn’t want to do it all by yourself. As an example, if your game need a recharge function, you might need some DeFi functions, or maybe you need NFTs to build the game. You’ll have to get all these functions, and these functions has already been set on other blockchains, you can get them from those blockchains.</p><p>So this is what Polkadot does, it <strong>combines different blockchains, they can cooperate, focus on whatever they are good at</strong>, <strong>and increase their performance.</strong> They can let the others do what they are good at. In brief, Polkadot is a crosschain protocol</p><p>So how exactly does it works, we’re gonna see it architecture first.</p><h3>Architecture</h3><p>The structure of Polkadot is different from the other public blockchains.</p><p>Polkadot is radial, it consists of a <strong>relay chain</strong> in the middle, and the surrounding <strong>parachains</strong> and <strong>bridges</strong>.</p><figure><img alt="architecture of Polkadot" src="https://cdn-images-1.medium.com/max/807/1*WJrO0BlD6PcMcUyFDMXJ9A.png" /></figure><p><strong>Four different chains on Polkadot:</strong></p><ul><li><strong>Relay chains</strong></li></ul><p>The heart of Polkadot, responsible for the network’s security, consensus and cross-chain interoperability.</p><ul><li><strong>Parachains</strong></li></ul><p>Sovereign blockchains that can have their own tokens and optimize their functionality for specific use cases. Parachains is connected to Relay chains by leasing a slot on it.</p><ul><li><strong>Parathreads</strong></li></ul><p>Parathreads are parachains that are temporarily participate in Polkadot security without needing to lease a dedicated parachain slot.</p><ul><li><strong>Bridges</strong></li></ul><p>Special blockchains that allow Polkadot shards to connect to and communicate with external networks like Ethereum and Bitcoin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjFF8s1MEGAFxApQpkceKg.png" /></figure><h3>Consensus</h3><p>Polkadot uses “<strong><em>Nominated POS</em></strong>”, this allow token holders to vote for validators to represent them. On the other hand, Polkadot uses hybrid consensus which consist of <strong>BABE</strong> and <strong>GRANDPA</strong> to take benefit on both probabilistic ( continuously producing new blocks ) and provable ( deterministic ) finality.</p><h4>1. BABE</h4><p><strong>B</strong>lind <strong>A</strong>ssignment for <strong>B</strong>lockchain <strong>E</strong>xtension. It is for block generation.</p><p>Validators in Polkadot will participate in a lottery in every slot that will tell them whether or not they are the block producer candidate for that slot. There may be two or more validators for the same slot, all will start producing new block, and the one who first reaches most of the networks wins.</p><h4>2. GRANDPA</h4><p><strong>G</strong>HOST-based <strong>R</strong>ecursive <strong>AN</strong>cestor <strong>D</strong>eriving <strong>P</strong>refix <strong>A</strong>greement. It is for proving finality.</p><p>GRANDPA is a finality gadget which can speed up the <strong>finalization process</strong>, and it works as long as 2/3 of nodes are honest.</p><h4>Consensus Roles</h4><p>there are three roles that maintains Polkadot</p><ul><li>Nominators: nominators stake their DOTs and select the validators of relay chain.</li><li>Collators: Collators maintain parachains by collecting parachain transactions from users and producing state transition proofs for validators.</li><li>Validators: validate proofs from collators and it changes every epoch(day)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*DJM2M1ZxNZmTbyKZj17L6Q.png" /><figcaption>interaction between collators and validators</figcaption></figure><h3>Advantages</h3><p>here are the four advantages of Polkadot:</p><ul><li>heterogeneous sharding</li><li>scalability, upgradeability</li><li>transparent governance</li><li>cross-chain composability</li></ul><h3><strong>Tokenomics</strong></h3><p>DOT is the native token of Polkadot, we’re going to discuss the inflation of DOT, its economic part.</p><h4><em>I</em>nflation :</h4><ul><li>aims to have 50% staked in NPoS, 30% in parachains deposits (who gets a parachain slot)</li><li>inflationary, approximately 10% annually</li><li>no maximum number</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*gGvpoW1hqJ3VGUzbn8kU4Q.png" /></figure><ul><li><strong>inflation (“+” means cause to inflation, “–” means deflation)</strong></li></ul><p>+ NPoS rewards</p><p>+ treasury (explained later)</p><p>– slashing ( punishment for bad validates )</p><p>– fees</p><ul><li><strong>the amount staked influence the inflation rate(explanation of the graph above)</strong></li></ul><p><strong>x-axis </strong>: Proportion of DOT staked</p><p><strong>y-axis </strong>: Inflation, annualized percentage</p><p><strong>Blue line </strong>: Inflation rewards to stakers</p><p><strong>Green line </strong>: Staker rate of return</p><p>Inflation should reach the maximal when staking rate reaches 0.5 ( the ideal staking rate) to control staking rate.</p><h4>functions of DOT:</h4><ul><li>governance</li><li>stake for the operation of the network( nominators, validators, etc.)</li><li>parachain slot acquisition</li></ul><p>Thanks for reading, a more comprehensive explanation to Polkadot is being worked, welcome to take a look at my other publications !</p><h3>Reference</h3><ul><li><a href="https://polkadot.network/">https://polkadot.network/</a></li><li><a href="https://www.notion.so/DAY-23-HTTPS-TLS-SSL-ea27cb9173384ce1bf8ca9d4def0e2a5">Polkadot lightpaper</a></li><li><a href="https://blockcast.it/2022/01/12/aax-the-slow-rise-of-polkadot/">https://blockcast.it/2022/01/12/aax-the-slow-rise-of-polkadot/</a></li><li><a href="https://www.coinbase.com/learn/crypto-basics/what-is-polkadot">https://www.coinbase.com/learn/crypto-basics/what-is-polkadot</a></li><li><a href="https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html">https://research.web3.foundation/en/latest/polkadot/overview/2-token-economics.html</a></li></ul><h3>Extend Reading</h3><ul><li><a href="https://research.web3.foundation/en/latest/polkadot/block-production/Babe.html">BABE</a></li><li><a href="https://github.com/w3f/consensus/blob/master/pdf/grandpa.pdf">GRANDPA</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cdea409bf04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swf-lab/polkadot-briefly-explained-9cdea409bf04">Polkadot briefly explained</a> was originally published in <a href="https://medium.com/swf-lab">SWF Lab</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>