Skip to content

Instantly share code, notes, and snippets.

@eu90h
Created September 2, 2015 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eu90h/6f38366f47e8c2d1f477 to your computer and use it in GitHub Desktop.
Save eu90h/6f38366f47e8c2d1f477 to your computer and use it in GitHub Desktop.
Merkle tree implementation in Racket
#lang racket
(require openssl/sha1)
(struct node (value left right) #:transparent)
(define (hash s)
(sha1 (open-input-string s)))
(define (build-foundation l [hash hash])
(let loop ([l l])
(if (null? l)
null
(if (= 1 (length l))
(list (node (hash (first l)) null null))
(let ([vals (take l 2)])
(cons (node (hash (string-append (first vals) (second vals)))
(node (hash (first vals)) null null)
(node (hash (second vals)) null null))
(loop (drop l 2))))))))
(define (build-next-node a b)
(node (hash (string-append (node-value a) (node-value b)))
a
b))
(define (merkle-tree l [hash hash])
(define (aux l)
(if (= 1 (length l))
l
(aux (let loop ([l l])
(if (null? l)
null
(if (= 1 (length l))
(list (node (hash (node-value (first l))) null null))
(let ([vals (take l 2)])
(cons (build-next-node (first vals) (second vals)) (loop (drop l 2))))))))))
(first (aux (build-foundation l hash))))
(module+ test
(define test-1 (build-list 10000 (lambda (i) (number->string i))))
(merkle-tree test-1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment