📜 [專欄新文章] Merkle Tree in JavaScript
✍️ Johnson
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
這篇文章會說明 Merkle Tree 的運作原理,以及解釋 Merkle Proofs 的用意,並以 JavaScript / TypeScript 簡單實作出來。
本文為 Tornado Cash 研究系列的 Part 1,本系列以 tornado-core 為教材,學習開發 ZKP 的應用,另兩篇為:
Part 2:ZKP 與智能合約的開發入門
Part 3:Tornado Cash 實例解析
Special thanks to C.C. Liang for review and enlightenment.
本文中實作的 Merkle Tree 是以 TypeScript 重寫的版本,原始版本為 tornado-core 以 JavaScript 實作而成,基本上大同小異。
Merkle Tree 的原理
在理解 Merkle Tree 之前,最基本的先備知識是 hash function,利用 hash 我們可以對資料進行雜湊,而雜湊後的值是不可逆的,假設我們要對 x 值做雜湊,就以 H(x) 來表示,更多內容可參考:
一次搞懂密碼學中的三兄弟 — Encode、Encrypt 跟 Hash
SHA256 Online
而所謂的 Merkle Tree 就是利用特定的 hash function,將一大批資料兩兩進行雜湊,最後產生一個最頂層的雜湊值 root。
當有一筆資料假設是const leaves = [A, B, C, D],我們就用function Hash(left, right),開始製作這顆樹,產生H(H(A) + H(B))與H(H(C) + H(D)),再將這兩個值再做一次 Hash 變成 H(H(H(A) + H(B)) + H(H(C) + H(D))),就會得到這批資料的唯一值,也就是 root。
本文中使用的命名如下:
root:Merkle Tree 最頂端的值,特色是只要底下的資料一有變動,root 值就會改變。
leaf:指單一個資料,如 H(A)。
levels:指樹的高度 (height),以上述 4 個資料的假設,製作出來的 levels 是 2,levels 通常會作為遞迴的次數。
leaves:指 Merkle Tree 上的所有資料,如上述例子中的 H(A), H(B), H(C), H(D)。leaves 的數量會決定樹的 levels,公式是 leaves.length == 2**levels,這段建議先想清楚!
node:指的是非 leaves 也非 root 的節點,或稱作 branch,如上述例子中的H(H(A) + H(B)) 和 H(H(C) + H(D))。
index:指某個 leaf 所在的位置,leaf = leaves[index],index 如果是偶數,leaf 一定在左邊,如果是奇數 leaf 一定在右邊。
Merkle Proofs
Merkle Proofs 的重點就是要證明資料有沒有在樹上。
如何證明?就是提供要證明的 leaf 以及其相對應的路徑 (path) ,經過計算後一旦能夠產生所需要的 root,就能證明這個 leaf 在這顆樹上。
因此這類要判斷資料有無在樹上的證明,類似的說法有:proving inclusion, proving existence, or proving membership。
這個 proof 的特點在於,我們只提供 leaf 和 path 就可以算出 root,而不需要提供所有的資料 (leaves) 去重新計算整顆 Merkle Tree。這讓我們在驗證資料有沒有在樹上時,不需要花費大量的計算時間,更棒的是,這讓我們只需要儲存 root 就好,而不需要儲存所有的資料。
在區塊鏈上,儲存資料的成本通常很高,也因此 Merkle Tree 的設計往往成為擴容上的重點。
我們知道 n 層的 Merkle Tree 可以存放 2**n 個葉子,以 Tornado Cash 的設計來說,他們設定 Merkle Tree 有 20 層,也就是一顆樹上會有 2**20 = 1048576 個葉子,而我們用一個 root 就代表了這 1048576 筆資料。
接續上段的例子,這顆 20 層的 Merkle Tree 所產生的 Proof ,其路徑 (path) 要從最底下的葉子 hash 幾次才能到達頂端的 root 呢?答案就是跟一棵樹的 levels 一樣,我們要驗證 Proof 所要遞迴的次數就會是 20 次。
在實作之前,我們先來看 MerkleTree 在 client 端是怎麼調用的,這有助於我們理解 Merkle Proofs 在做什麼。
基本上一個 proof 的場景會有兩個人:prover 與 verifier。
在給定一筆 leaves 的樹,必定產生一特定 root。prover 標示他的 leaf 在樹上的 index 等於 2,也就是 leaves[2] == 30,以此來產生一個 proof,這個 proof 的內容大致上會是這個樣子:
對 verifier 來說,他要驗證這個 proof,就是用裡面的 leaf 去一個一個與 pathElements 的值做 hash,上述就是 H('30', 40) 後得出 node,再 hash 一次 H('19786...', node) 於是就能得出這棵樹的 root。
重點來了,這麼做有什麼意義?它的巧思在於對 verifier 來說,他只需要儲存一個 root,由 prover 提交證明給他,經過計算後產生的 root 如果跟 verifier 儲存的 root 一樣,那就證明了 prover 所提供的資料確實存在於這個樹上。
而 verifier 若不透過 proof ,要驗證某個 leaf 是否存在於樹上,也可以把 leaves = [10, 20 ,leaf ,40]整筆資料拿去做 MerkleTree 的演算法跑一趟也能產生特定的 root。
但由 prover 先行計算後所提交的 proof,讓 verifier 不必儲存整批資料,也省去了大量的計算時間,即可做出某資料有無在 Merkle Tree 上的判斷。
Sparse Merkle Tree
上述能夠證明資料有無在樹上的 Merkle Proofs 是屬於標準的 Merkle Tree 的功能。但接下來我們要實作的是稍微不一樣的樹,叫做 Sparse Merkle Tree。
Sparse Merkle Tree 的特色在於除了 proving inclusion 之外,還可以 proving non-inclusion。也就是能夠證明某筆資料不在某個 index,例如 H(A) 不在 index 2 ,這是一般 Merkle Tree 沒辦法做到的。
而要做到 non-membership 的功能其實也不難,就是我們要在沒有資料的葉子裡補上 zero value,或是說 null 值。更多內容請參考:What’s a Sparse Merkle Tree。
實作細節
本節將完整的程式碼分成三個片段來解釋。
首先,這裡使用的 Hash Function 是 MiMC,主要是為了之後在 ZKP 專案上的效率考量,你可以替換成其他較常見的 hash function 例如 node.js 內建 crypto 的 sha256:
crypto.createHash("sha256").update(data.toString()).digest("hex");
這裡定義簡單的 Merkle Tree 介面有 root, proof, and insert。
首先我們必須先給定這顆樹的 levels,也就是樹的高度先決定好,樹所能容納的資料量也因此固定為 2**levels 筆資料,至於要不要有 defaultLeaves 則看創建 Merkle Tree 的 client 自行決定,如果有 defaultLeaves 的話,constructor 就會跑下方一大段計算,對 default 資料開始作 hash 去建立 Merkle Tree。
如果沒有 defaultLeaves,我們的樹也不會是空白的,因為這是顆 Sparse Merkle Tree,這裡使用 zeroValue 作為沒有填上資料的值,zeros 陣列會儲存不同 level 所應該使用的 zero value。假設我們已經填上第 0 筆與第 1 筆資料,要填上第 2 筆資料時,第 2 筆資料就要跟 zeros[0] 做 hash,第 2 筆放左邊, zero value 放右邊。
我們將所有的點不論是 leaf, node, root 都用標籤 (index) 標示,並以 key-value 的形式儲存在 storage 裡面。例如第 0 筆資料會是 0–0,第 1 筆會是 0–1,這兩個 hash 後的節點 (node) 會是 1–0。假設 levels 是 2,1–0 節點就要跟 1–1 節點做 hash,即可產出 root (2–0)。
後半部份的重點在於 proof,先把 proof 和 traverse 看懂,基本上就算是打通任督二脈了,之後有興趣再看 insert 和 update。
sibling 是指要和 current 一起 hashLeftRight 的值…也就是相鄰在兩旁的 leaf (or node)。
到這裡程式碼的部分就結束了。
最後,讓我們回到一開始 client 調用 merkleTree 的例子:
以及 proof 的內容:
前面略過了 proof 裡頭的 pathIndices,pathIndices 告訴你的是當前的 leaf (or node) 是要放在左邊,還是放在右邊,大概是這個樣子:
if (indices == 0) hash(A, B);if (indices == 1) hash(B, A);
有興趣的讀者可以實作 verify function 看看就會知道了!
原始碼
TypeScript from gist
JavaScript from tornado-core
參考
Merkle Proofs Explained
What’s a Sparse Merkle Tree?
延伸:Verkle Tree
Merkle Tree in JavaScript was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
同時也有24部Youtube影片,追蹤數超過27萬的網紅Pixel Gamer,也在其Youtube影片中提到,PIXELMON NOOB TEAM TẬP 47: POKEMON HUYỀN THOẠI KHÓ BẮT NHẤT - MELTAN VÀ THẦN TỔNG HỢP TYPE: NULL Lịch stream: 8h - 14h hàng ngày trên NimoTV : https:/...
if null 在 Milton Goh Blog and Sermon Notes Facebook 的最佳解答
His Banner Over me is Love!
“He brought me to the banquet hall. His banner over me is love.” (Song of Solomon 2:4 WEB)
In a Jewish wedding, the wedding couple get married under a canopy called a “Chuppah” which consists of a big sheet (like a banner) stretched out over four standing poles.
This scene is a picture of two people in love sealing their marriage by a covenant.
Imagine Jesus standing with you under the canopy, affirming His love for you. He sealed the New Covenant of Grace for you by shedding His own precious blood.
Perhaps that is why I was led to color the carpet as red because we are standing upon the foundation established by His blood.
““You shall make a veil of blue, and purple, and scarlet, and fine twined linen, with cherubim. The work of the skillful workman shall it be made.” (Exodus 26:31 WEB)
Without realizing it until the picture was done, the colors I used reflect the four colors of the veil in the Tabernacle, and the golden wings of the cherubim on the Ark of the Covenant. The Chuppah is like a tabernacle—you are preserved from the corruption of the world and kept from harm in God’s dwelling place.
“For the woman that has a husband is bound by law to the husband while he lives, but if the husband dies, she is discharged from the law of the husband.” (Romans 7:2 WEB)
A covenant between two is dissolved when one of the two parties dies.
You already died once when you first placed your faith in Jesus. You shared in His death at the cross, His burial, and His resurrection. This means that the covenant between you and God can never become null and void!
When you know that you are united with Jesus by an everlasting covenant, you will not be afraid of falling out of His favor or of any enemies.
His banner over you is love. Just look up and see His love spreading out over you, enveloping you, keeping you safe and protected under the shelter of God!
Keep studying God’s word and growing in your understanding of His ways. Our Patreon community is currently on a Bible study series called “My Faith Declarations” which looks at the Spirit-inspired utterances of the authors of the Psalms. They wrote about the trials and tribulations they experienced, so the book of Psalms is very relatable.
By turning their faith declarations into our own, we can learn how to overcome similar circumstances in life through faith in the Lord! Become a “God Every Morning” tier or above patron on Patreon to receive this reward, daily devotionals by email, and also all my eBooks. Thanks for being a blessing to this ministry: http://Patreon.com/miltongohblog
if null 在 Facebook 的最讚貼文
A VERY BLESSED CHRISTMAS FROM US TO YOU! ❤ First time celebrating Christmas as husband and wife! 🤵👰♀️
•
It's been a challenging year for most if not all of us but we remember that there is HOPE even in darkest time, and that hope is in Jesus! ✝️ Without His birth, our hope would be completely null and void! So, we praise God for today and this year even though it was tough! 🌟 Have a beautiful one! 😊
if null 在 Pixel Gamer Youtube 的最讚貼文
PIXELMON NOOB TEAM TẬP 47: POKEMON HUYỀN THOẠI KHÓ BẮT NHẤT - MELTAN VÀ THẦN TỔNG HỢP TYPE: NULL
Lịch stream: 8h - 14h hàng ngày trên NimoTV : https://www.nimo.tv/live/324824101
Liên hệ quảng cáo: [email protected]
✪ Link FanPage Face Book: http://bit.ly/2IeuBGK
✪ Link Group Face Book: http://bit.ly/2xbZDNj
✪ Link Donate ủng hộ Pixel: https://playerduo.com/pixelgamer
✪ Kênh Pixel Stream: http://bit.ly/3cgN0R4
✪ Kênh T Gaming : https://goo.gl/sG6owZ
✪ Kênh Zeno Gaming: https://bitly.com.vn/3NowZ
✪ Kênh Vanh MC: https://sum.vn/FNJQ8
✪Kênh Vlogs T Gaming : https://bitly.vn/184u
✪ Hãy giúp Mình đạt được 500k đăng ký!
Click vào nút đăng ký nhé
✪ FaceBook Pixel Gamer: https://bitly.vn/72w0
✪ Page Facebook : https://goo.gl/TwCm2i
✪ Group FB : https://goo.gl/ldtCfL
#PixelGamer #Pokemon #Pixelmon #CuuGamer , #BinhLuanGame #Minecraft #Noob #TGaming
★ SUBSCRIBE, LIKE VÀ CHIA SẺ VIDEO ĐỂ GIÚP T CÓ THÊM ĐỘNG LỰC LÀM VIDEO NỮA NHÉ!
**Music copyright of youtube music free.
....If You See Me Use Music With Copyright Content Be In Touch With Me. I will remove it from Chanel. Thank you
**Music provided by NoCopyrightSounds.
Link :https://www.youtube.com/user/NoCopyri

if null 在 ONE_ Youtube 的精選貼文
メンズメイク経験豊富な私が
ばれずに盛れるBBクリームをAmazonで10品購入→使用感上位4品をレビューしました。
是非参考にしてください♪
・オシャレ感・自然さ◎
ORBIS Mr. ベースカラー
https://amzn.to/3eeYEfI
・使いやすさバランス良し
リップスボーイ メンズ フェイスジェル
https://amzn.to/2zSy39s
・カバー力最強と感じた
NULL BBクリーム
https://amzn.to/3dqqq81
・保湿しながら美肌効果
NUDO BBクリーム モイストベースクリーム
https://amzn.to/3ejJMgb
Twitter:
https://twitter.com/one_genera1
note:
https://note.mu/showbiz
If you want to donate subtitles, click the link below. Thank you.
http://www.youtube.com/timedtext_video?ref=share&v=U0PlVOg4vws
00:00 OPENING
01:59 ORBIS Mr.
03:13 リップスボーイ、フェイスジェル
04:06 NULL BBクリーム
05:39 NUDO BBクリーム
07:13 まとめ、総評
08:38 猫
#メンズメイク
#メンズ BBクリーム

if null 在 Lollalane Youtube 的最讚貼文
Here is another video for this week. It is all about my most favorite as well as most frequently used stationery for the first quarter of 2020.
Enjoy watching :)
--------------------------------------------------------------------------------------------------------------
1. Monokoto Washi Tapes
https://monokotostore.net/
https://journal-pages.com/collections/monokoto-store
2. Laban Flame Fountain Pen
https://www.laban.com/product/flame-fountain-pen/
3. SOM x La Dolce Vita Stamps Set
https://www.sumthingsofmine.com/collections/som-studio/products/best-wishes-rubber-stamp-set
4. Pion Washi Tape
https://journal-pages.com/collections/pion/products/pion-label-girls-washi-tape
5. P. Palatte Stickers
https://journal-pages.com/collections/p-palette
6. Soupy Tang Camping Stamps Set
https://journal-pages.com/products/soupy-the-great-outdoors-rubber-stamp?_pos=1&_sid=5e07bc142&_ss=r
7. Amnesiac Stamps Set
https://www.sumthingsofmine.com/collections/amnesiac/products/amnesiac-original-rubber-stamp-set-re-or-null
8. LCN Stamps Paper Pad
https://journal-pages.com/collections/lcn-design-studio%E5%90%89/products/lcn-postage-stamp-paper-pad
------------------------------------------------------------------------------------
Please comment down below if you have any question or feedback, would love to hear from you all.
Don't forget to subscribe and show me some love if you want to see more updates from me!
-------------------------------------------------------
You may also reach me at
Instagram: Lollalane
Email: lollalanejournal@gmail.com
