summaryrefslogtreecommitdiff
path: root/the-ideal-stocking-stuffer/tiss.scm
blob: 5162b4091b0d9990850938266cc2ced2afa4c1ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
(define-module (tiss)
  #:use-module (ice-9 string-fun)
  #:use-module (hashing md5)
  #:use-module (rnrs bytevectors)
  #:use-module (ice-9 exceptions)
  #:export (tiss
            get-hash
            starts-with?))


(define (tiss prefix output-prefix suffix)
  "Given KEY puzzle key and the desired
OUTPUT-PREFIX, and the current suffix,
incrementally tries hash inputs until
the desired output is achieved.

Throws an exception after 150000 iterations."
  ;; (display (format #f "suffix is now: ~s\n" suffix))
  (when (> suffix 1000000000)
    (raise-exception
     (make-exception-with-message
      (format #f "Exceeded maximum attempts for key ~s!" prefix))))
  (let ((output (get-hash prefix (number->string suffix))))
    (if (starts-with? output output-prefix)
        suffix
        (tiss prefix output-prefix (1+ suffix)))))

(define (get-hash prefix suffix)
  "Computes the MD5 hash of prefix
combined with suffix."
  (md5->string
   (md5 (string->utf8
         (string-append prefix suffix)))))

(define (starts-with? str prefix)
  "Returns #t if STR starts with PREFIX."
  (let ((prefix-length (string-length prefix)))
    (and (>= (string-length str) prefix-length)
         (equal? (substring str 0 prefix-length) prefix))))