]> gitweb.factorcode.org Git - factor.git/blob - extra/hashcash/hashcash.factor
017cb4bcd0956edd21fe77dd543e6d4a43796b15
[factor.git] / extra / hashcash / hashcash.factor
1 ! Copyright (C) 2009 Diego Martinelli.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors byte-arrays calendar checksums
4 checksums.openssl classes.tuple formatting io.encodings.ascii
5 io.encodings.string kernel literals math math.functions
6 math.parser math.ranges present random sequences splitting ;
7 IN: hashcash
8
9 ! Hashcash implementation
10 ! Reference materials listed below:
11 !
12 ! http://hashcash.org
13 ! http://en.wikipedia.org/wiki/Hashcash
14 ! http://www.ibm.com/developerworks/linux/library/l-hashcash.html?ca=dgr-lnxw01HashCash
15 !
16 ! And the reference implementation (in python):
17 ! http://www.gnosis.cx/download/gnosis/util/hashcash.py
18
19 <PRIVATE
20
21 ! Return a string with today's date in the form YYMMDD
22 : get-date ( -- str )
23     now "%y%m%d" strftime ;
24
25 ! Random salt is formed by ascii characters
26 ! between 33 and 126
27 CONSTANT: available-chars $[
28     CHAR: : 33 126 [a..b] remove >byte-array
29 ]
30
31 PRIVATE>
32
33 ! Generate a 'length' long random salt
34 : salt ( length -- salted )
35     [ available-chars random ] "" replicate-as ;
36
37 TUPLE: hashcash version bits date resource ext salt suffix ;
38
39 : <hashcash> ( -- tuple )
40     hashcash new
41         1 >>version
42         20 >>bits
43         get-date >>date
44         8 salt >>salt ;
45
46 M: hashcash string>>
47     tuple-slots [ present ] map ":" join ;
48
49 <PRIVATE
50
51 : sha1-checksum ( str -- bytes )
52     ascii encode openssl-sha1 checksum-bytes ; inline
53
54 : set-suffix ( tuple guess -- tuple )
55     >hex >>suffix ;
56
57 : get-bits ( bytes -- str )
58     [ >bin 8 CHAR: 0 pad-head ] { } map-as concat ;
59
60 : checksummed-bits ( tuple -- relevant-bits )
61     dup string>> sha1-checksum
62     swap bits>> 8 / ceiling head get-bits ;
63
64 : all-char-zero? ( seq -- ? )
65     [ CHAR: 0 = ] all? ; inline
66
67 : valid-guess? ( checksum tuple -- ? )
68     bits>> head all-char-zero? ;
69
70 : (mint) ( tuple counter -- tuple )
71     2dup set-suffix checksummed-bits pick
72     valid-guess? [ drop ] [ 1 + (mint) ] if ;
73
74 PRIVATE>
75
76 : mint* ( tuple -- stamp )
77     0 (mint) string>> ;
78
79 : mint ( resource -- stamp )
80     <hashcash>
81         swap >>resource
82     mint* ;
83
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? ;