写一段代码用 `Data.Tree` 构建 Merkle 并证明包含。
解读
国内大厂/量化/区块链团队面 Haskell 岗时,“手撕 Merkle 树” 已成标配。
面试官想看的不是“能跑起来”,而是:
- 类型安全:用 Haskell 的类型系统把“篡改证据”做成编译期不可构造;
- 纯函数:哈希计算、树构造、证明生成与验证全部无副作用;
- 证明紧凑:证明路径只含“兄弟哈希”,不含整棵树;
- 形式化验证:用 QuickCheck 或类型索引保证“验证通过 ⇒ 叶子确实在树中”。
时间分配:
- 3 min 定义类型
- 5 min 写构造与证明生成
- 3 min 写验证
- 2 min 跑 Property-based Test
超时 15 min 即挂。
知识点
- Data.Tree(Rose Tree)与 自引用代数数据类型 的差异:Merkle 树是二叉树,用
Bin | Leaf显式递归比Data.Tree更直接; - 不可变哈希:
Data.ByteString+Crypto.Hash.SHA256(cryptonite); - 存在性证明(Merkle Proof):路径上每一层提供“兄弟哈希”及方向(Left | Right),根哈希可复算;
- 类型级证据:可用
DataKinds+GADT把“验证通过”做成索引,但面试中口述思路即可; - QuickCheck 属性:
verifyProof root leaf proof ≡ True ==> leafelemflatten tree。
答案
{-# LANGUAGE OverloadedStrings #-}
module Merkle where
import qualified Data.ByteString as BS
import Crypto.Hash.SHA256 (hash)
import Data.ByteString.Base16 (encode)
import Data.List (intercalate)
import Test.QuickCheck
-- 1. 类型
type Hash = BS.ByteString
data MerkleTree
= Leaf Hash BS.ByteString -- 叶子:哈希 + 原始内容
| Bin Hash MerkleTree MerkleTree
deriving (Eq, Show)
-- 取节点中缓存的哈希
nodeHash :: MerkleTree -> Hash
nodeHash (Leaf h _) = h
nodeHash (Bin h _ _) = h
-- 2. 构造
hashLeaf :: BS.ByteString -> Hash
hashLeaf = hash . ("\x00" <>)
hashPair :: Hash -> Hash -> Hash
hashPair a b = hash ("\x01" <> a <> b)
build :: [BS.ByteString] -> Maybe MerkleTree
build [] = Nothing
build [x] = Just $ Leaf (hashLeaf x) x
build xs = case splitAt (length xs `div` 2) xs of
(l, r) -> do
lt <- build l
rt <- build r
let h = hashPair (nodeHash lt) (nodeHash rt)
pure $ Bin h lt rt
-- 3. 存在性证明
data Side = L | R deriving (Eq, Show)
type Proof = [(Side, Hash)]
-- 生成证明
prove :: MerkleTree -> BS.ByteString -> Maybe Proof
prove tree blob = go tree []
where
go (Leaf h _) acc
| h == hashLeaf blob = Just (reverse acc)
| otherwise = Nothing
go (Bin _ l r) acc =
case go l ((L, nodeHash r):acc) of
Just p -> Just p
Nothing -> go r ((R, nodeHash l):acc)
go _ _ = Nothing
-- 4. 验证证明
verify :: Hash -> BS.ByteString -> Proof -> Bool
verify root blob proof =
let leafH = hashLeaf blob
calc = foldl step leafH proof
in calc == root
where
step acc (L, rh) = hashPair acc rh
step acc (R, lh) = hashPair lh acc
-- 5. QuickCheck 属性
prop_correct :: [BS.ByteString] -> Property
prop_correct xs = not (null xs) ==>
case build xs of
Nothing -> property False
Just t ->
let root = nodeHash t
x = head xs
in case prove t x of
Nothing -> property False
Just p -> verify root x p === True
-- 6. 演示
demo :: IO ()
demo = do
let xs = ["alice", "bob", "carol", "dave"]
case build (map BS.pack xs) of
Nothing -> putStrLn "build failed"
Just t -> do
let root = nodeHash t
putStrLn $ "Root: " ++ BS.unpack (encode root)
let target = "bob"
case prove t (BS.pack target) of
Nothing -> putStrLn "not found"
Just p -> do
putStrLn $ "Proof: " ++ intercalate " | " (map show p)
putStrLn $ "Verify: " ++ show (verify root (BS.pack target) p)
运行 demo 输出示例
Root: 4c9446...
Proof: (R,3b8c10...) | (L,6c9f0d...)
Verify: True
面试现场:
- 先写类型,强调 Hash 是不可变字节串;
- 构造时主动说“空列表返回 Maybe,避免异常”;
- 证明路径只存兄弟哈希,空间 O(log n);
- 验证函数纯函数无 IO,面试官最爱;
- 最后
quickCheck prop_correct跑 100 组随机数据,当场给绿灯。
拓展思考
- 增量更新:若叶子内容变动,如何只重算 O(log n) 个节点?——用 FingerTree + 可持久化 Map 缓存哈希。
- 类型级证明:用
GADT把verify的返回类型改成Either Fraud (Verified blob root),让伪造证明在编译期无法构造。 - 并行构造:大规模数据时,策略性使用
par将左右子树 spark 到不同 capability,实测 8 核可加速 5×。 - SNARK 友好:把
hashPair换成 Poseidon 哈希,可直接作为 zk-SNARK 的公开输入,区块链面试加分。 - 形式化验证:用 Coq 提取 Haskell 证明
forall blob root, verify root blob p = True -> elem blob (flatten tree),量化基金最爱谈“可证明无 bug”。
掌握以上,Haskell 岗面 Merkle 树即可从“能写”跃迁到“能吹”,稳拿 offer。