1 ! Copyright (C) 2009 Diego Martinelli.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors byte-arrays calendar calendar.format checksums
4 checksums.openssl classes.tuple fry kernel make math math.functions
5 math.parser math.ranges present random sequences splitting strings ;
8 ! Hashcash implementation
9 ! Reference materials listed below:
12 ! http://en.wikipedia.org/wiki/Hashcash
13 ! http://www.ibm.com/developerworks/linux/library/l-hashcash.html?ca=dgr-lnxw01HashCash
15 ! And the reference implementation (in python):
16 ! http://www.gnosis.cx/download/gnosis/util/hashcash.py
20 ! Return a string with today's date in the form YYMMDD
22 now [ year>> 100 mod pad-00 ]
24 [ day>> pad-00 ] tri 3append ;
26 ! Random salt is formed by ascii characters
28 : available-chars ( -- seq )
29 33 126 [a,b] [ CHAR: : = not ] filter ;
33 ! Generate a 'length' long random salt
34 : salt ( length -- salted )
35 available-chars '[ _ random ] "" replicate-as ;
37 TUPLE: hashcash version bits date resource ext salt suffix ;
39 : <hashcash> ( -- tuple )
47 tuple-slots [ present ] map ":" join ;
51 : sha1-checksum ( str -- bytes )
52 openssl-sha1 checksum-bytes ; inline
54 : set-suffix ( tuple guess -- tuple )
57 : get-bits ( bytes -- str )
58 [ >bin 8 CHAR: 0 pad-head ] { } map-as concat ;
60 : checksummed-bits ( tuple -- relevant-bits )
61 dup string>> sha1-checksum
62 swap bits>> 8 / ceiling head get-bits ;
64 : all-char-zero? ( seq -- ? )
65 [ CHAR: 0 = ] all? ; inline
67 : valid-guess? ( checksum tuple -- ? )
68 bits>> head all-char-zero? ;
70 : (mint) ( tuple counter -- tuple )
71 2dup set-suffix checksummed-bits pick
72 valid-guess? [ drop ] [ 1 + (mint) ] if ;
76 : mint* ( tuple -- stamp )
79 : mint ( resource -- stamp )
84 ! One might wanna add check based on the date,
85 ! passing a 'good-until' duration param
86 : check-stamp ( stamp -- ? )
87 dup ":" split [ sha1-checksum get-bits ] dip
88 second string>number head all-char-zero? ;