Skip to content

Instantly share code, notes, and snippets.

Created April 30, 2013 01:01
Show Gist options
  • Save anonymous/5485986 to your computer and use it in GitHub Desktop.
Save anonymous/5485986 to your computer and use it in GitHub Desktop.
dobry-den's tnt.miner v0.1.0
(ns tnt.miner
(:require [clojure.string :refer [join]])
(:import [java.security MessageDigest]
[org.apache.commons.codec.binary Hex])
(:gen-class))
(set! *warn-on-reflection* true)
;(set! *unchecked-math* true)
;; Util ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def processor-count
(.availableProcessors (Runtime/getRuntime)))
(defn thread-name []
(.getName (Thread/currentThread)))
(defn thread-println [& msgs]
(println "[" (thread-name) "]" (join (interpose " " msgs))))
(def ascii (concat (range 10)
(map char (concat (range 65 91) (range 97 123)))))
;; Crypto ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn sha512 ^String [^String s ^MessageDigest d]
(let [unhashed-bytes (.getBytes s)
hashed-bytes (.digest d unhashed-bytes)]
(.reset d)
(Hex/encodeHexString hashed-bytes)))
;; Config ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def difficulty 7)
(def prefix (join (repeat difficulty "0"))) ; 0000000
(def upper-bound 1000000000)
;; Core ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def solution (agent nil))
(defn gen-seed []
(join (take 5 (shuffle ascii))))
(defn announce-solution! [guess]
(thread-println "Found solution:" guess)
(spit "tnt-miner-solutions.txt"
(str guess \newline)
:append true)
(send solution (fn [_] guess)))
(defn fast-concat
"Faster than `str`."
[^String s l]
(.concat s (Long/toString l)))
(defn work [seed digester]
(thread-println "Started working on" seed)
(loop [n 0]
(when (< n upper-bound)
(let [guess (fast-concat seed n)]
(if (.startsWith (sha512 guess digester) prefix)
(announce-solution! guess)
(recur (inc n)))))))
(defn -main [& args]
(def bench? (= "bench" (first args)))
(println "Launching" processor-count "threads...")
(dotimes [_ processor-count]
(let [digester (MessageDigest/getInstance "SHA-512")
action (if bench?
#(work "kNTny" digester)
#(while true (work (gen-seed) digester)))]
(.start (Thread. action))))
(shutdown-agents))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment