Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. module MerkleTree where
  2.  
  3. import Hash (hash256)
  4. import Control.Monad.State
  5. import Control.Monad.Identity
  6.  
  7. type Tx = String
  8. type Hash = String
  9. data Node = Empty |
  10. Leaf {hash :: Hash, tx :: Tx} |
  11. Branch {hash :: Hash, left :: Node, right :: Node}
  12. deriving (Show, Eq)
  13. type TreeState = StateT [Node]
  14.  
  15. merkleTree :: [Tx] -> Node
  16. merkleTree tx = evalState buildTree ls
  17. where ls = map toLeaf tx
  18.  
  19. buildTree :: TreeState Identity Node
  20. buildTree = do
  21. s <- get
  22. if length s == 1
  23. then return $ head s
  24. else do
  25. ns <- newLayer
  26. put ns
  27. buildTree
  28.  
  29. newLayer :: TreeState Identity [Node]
  30. newLayer = do
  31. s <- get
  32. if null s
  33. then return []
  34. else do
  35. n <- newNode
  36. ns <- newLayer
  37. return $ n:ns
  38.  
  39. newNode :: TreeState Identity Node
  40. newNode = state f
  41. where f [t] = let h = hash256 $ hash t ++ hash t
  42. in (Branch h t Empty,[])
  43. f (l:r:ts) = let h = hash256 $ hash l ++ hash r
  44. in (Branch h l r,ts)
  45.  
  46.  
  47.  
  48. -- ใƒ†ใ‚นใƒˆ็”จ
  49. toLeaf tx = Leaf (hash256 tx) tx
  50. sample = ["a" ,"b", "c", "d", "e","f","g"]
  51. leaves = map toLeaf sample
  52. tree = merkleTree sample
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement