hk-merkle-tree-keccak160-v1.clar 1.1 KB

123456789101112131415161718192021222324252627
  1. ;; Title: hiro-merkle-tree-keccak160
  2. ;; Version: v1
  3. (define-read-only (keccak160 (bytes (buff 1024)))
  4. (unwrap-panic (as-max-len? (unwrap-panic (slice? (keccak256 bytes) u0 u20)) u20)))
  5. (define-read-only (buff-20-to-uint (bytes (buff 20)))
  6. (buff-to-uint-be (unwrap-panic (as-max-len? (unwrap-panic (slice? bytes u0 u15)) u16))))
  7. (define-read-only (hash-leaf (bytes (buff 255)))
  8. (keccak160 (concat 0x00 bytes)))
  9. (define-read-only (hash-nodes (node-1 (buff 20)) (node-2 (buff 20)))
  10. (let ((uint-1 (buff-20-to-uint node-1))
  11. (uint-2 (buff-20-to-uint node-2))
  12. (sequence (if (< uint-2 uint-1)
  13. (concat (concat 0x01 node-2) node-1)
  14. (concat (concat 0x01 node-1) node-2))))
  15. (keccak160 sequence)))
  16. (define-read-only (check-proof (root-hash (buff 20)) (leaf (buff 255)) (path (list 255 (buff 20))))
  17. (let ((hashed-leaf (hash-leaf leaf))
  18. (computed-root-hash (fold hash-path path hashed-leaf)))
  19. (is-eq root-hash computed-root-hash)))
  20. (define-private (hash-path (entry (buff 20)) (acc (buff 20)))
  21. (hash-nodes entry acc))