(hashcash-extra-generate-parameters): New variable.
[gnus] / lisp / hashcash.el
1 ;;; hashcash.el --- Add hashcash payments to email
2
3 ;; Copyright (C) 2003, 2004, 2005 Free Software Foundation
4 ;; Copyright (C) 1997--2002 Paul E. Foley
5
6 ;; Maintainer: Paul Foley <mycroft@actrix.gen.nz>
7 ;; Keywords: mail, hashcash
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; The hashcash binary is at http://www.hashcash.org/.
29 ;;
30 ;; Call mail-add-payment to add a hashcash payment to a mail message
31 ;; in the current buffer.
32 ;;
33 ;; Call mail-add-payment-async after writing the addresses but before
34 ;; writing the mail to start calculating the hashcash payment
35 ;; asynchronously.
36 ;;
37 ;; The easiest way to do this automatically for all outgoing mail
38 ;; is to set `message-generate-hashcash' to t.  If you want more
39 ;; control, try the following hooks.
40 ;;
41 ;; To automatically add payments to all outgoing mail when sending:
42 ;;    (add-hook 'message-send-hook 'mail-add-payment)
43 ;;
44 ;; To start calculations automatically when addresses are prefilled:
45 ;;    (add-hook 'message-setup-hook 'mail-add-payment-async)
46 ;;
47 ;; To check whether calculations are done before sending:
48 ;;    (add-hook 'message-send-hook 'hashcash-wait-or-cancel)
49
50 ;;; Code:
51
52 (eval-and-compile
53  (autoload 'executable-find "executable"))
54
55 (defcustom hashcash-default-payment 20
56   "*The default number of bits to pay to unknown users.
57 If this is zero, no payment header will be generated.
58 See `hashcash-payment-alist'."
59   :type 'integer)
60
61 (defcustom hashcash-payment-alist '()
62   "*An association list mapping email addresses to payment amounts.
63 Elements may consist of (ADDR AMOUNT) or (ADDR STRING AMOUNT), where
64 ADDR is the email address of the intended recipient and AMOUNT is
65 the value of hashcash payment to be made to that user.  STRING, if
66 present, is the string to be hashed; if not present ADDR will be used."
67   :type '(repeat (choice (list :tag "Normal"
68                                (string :name "Address")
69                                (integer :name "Amount"))
70                          (list :tag "Replace hash input"
71                                (string :name "Address")
72                                (string :name "Hash input")
73                                (integer :name "Amount")))))
74
75 (defcustom hashcash-default-accept-payment 20
76   "*The default minimum number of bits to accept on incoming payments."
77   :type 'integer)
78
79 (defcustom hashcash-accept-resources `((,user-mail-address nil))
80   "*An association list mapping hashcash resources to payment amounts.
81 Resources named here are to be accepted in incoming payments.  If the
82 corresponding AMOUNT is NIL, the value of `hashcash-default-accept-payment'
83 is used instead.")
84
85 (defcustom hashcash-path (executable-find "hashcash")
86   "*The path to the hashcash binary.")
87
88 (defcustom hashcash-extra-generate-parameters nil
89   "*A list of parameter strings passed to `hashcash-path' when minting.
90 For example, you may want to set this to '(\"-Z2\") to reduce header length."
91   :type '(repeat string))
92
93 (defcustom hashcash-double-spend-database "hashcash.db"
94   "*The path to the double-spending database.")
95
96 (defcustom hashcash-in-news nil
97   "*Specifies whether or not hashcash payments should be made to newsgroups."
98   :type 'boolean)
99
100 (defvar hashcash-process-alist nil
101   "Alist of asynchronous hashcash processes and buffers.")
102
103 (require 'mail-utils)
104
105 (eval-and-compile
106  (if (fboundp 'point-at-bol)
107      (defalias 'hashcash-point-at-bol 'point-at-bol)
108    (defalias 'hashcash-point-at-bol 'line-beginning-position))
109
110  (if (fboundp 'point-at-eol)
111      (defalias 'hashcash-point-at-eol 'point-at-eol)
112    (defalias 'hashcash-point-at-eol 'line-end-position)))
113
114 (defun hashcash-strip-quoted-names (addr)
115   (setq addr (mail-strip-quoted-names addr))
116   (if (and addr (string-match "\\`\\([^+@]+\\)\\+[^@]*\\(@.+\\)" addr))
117       (concat (match-string 1 addr) (match-string 2 addr))
118     addr))
119
120 (defun hashcash-token-substring ()
121   (save-excursion
122     (let ((token ""))
123       (loop
124         (setq token
125           (concat token (buffer-substring (point) (hashcash-point-at-eol))))
126         (goto-char (hashcash-point-at-eol))
127         (forward-char 1)
128         (unless (looking-at "[ \t]") (return token))
129         (while (looking-at "[ \t]") (forward-char 1))))))
130
131 (defun hashcash-payment-required (addr)
132   "Return the hashcash payment value required for the given address."
133   (let ((val (assoc addr hashcash-payment-alist)))
134     (or (nth 2 val) (nth 1 val) hashcash-default-payment)))
135
136 (defun hashcash-payment-to (addr)
137   "Return the string with which hashcash payments should collide."
138   (let ((val (assoc addr hashcash-payment-alist)))
139     (or (nth 1 val) (nth 0 val) addr)))
140
141 (defun hashcash-generate-payment (str val)
142   "Generate a hashcash payment by finding a VAL-bit collison on STR."
143   (if (and (> val 0)
144            hashcash-path)
145       (save-excursion
146         (set-buffer (get-buffer-create " *hashcash*"))
147         (erase-buffer)
148         (apply 'call-process hashcash-path nil t nil
149                "-m" "-q" "-b" (number-to-string val) str
150                hashcash-extra-generate-parameters)
151         (goto-char (point-min))
152         (hashcash-token-substring))
153     (error "No `hashcash' binary found")))
154
155 (defun hashcash-generate-payment-async (str val callback)
156   "Generate a hashcash payment by finding a VAL-bit collison on STR.
157 Return immediately.  Call CALLBACK with process and result when ready."
158   (if (> val 0)
159       (let ((process (apply 'start-process "hashcash" nil
160                             hashcash-path "-m" "-q"
161                             "-b" (number-to-string val) str
162                             hashcash-extra-generate-parameters)))
163         (setq hashcash-process-alist (cons
164                                       (cons process (current-buffer))
165                                       hashcash-process-alist))
166         (set-process-filter process `(lambda (process output)
167                                        (funcall ,callback process output))))
168     (funcall callback nil)))
169
170 (defun hashcash-check-payment (token str val)
171   "Check the validity of a hashcash payment."
172   (if hashcash-path
173       (zerop (call-process hashcash-path nil nil nil "-c"
174                            "-d" "-f" hashcash-double-spend-database
175                            "-b" (number-to-string val)
176                            "-r" str
177                            token))
178     (progn
179       (message "No hashcash binary found")
180       (sleep-for 1)
181       nil)))
182
183 (defun hashcash-version (token)
184   "Find the format version of a hashcash token."
185   ;; Version 1.2 looks like n:yymmdd:rrrrr:xxxxxxxxxxxxxxxx
186   ;;   This carries its own version number embedded in the token,
187   ;;   so no further format number changes should be necessary
188   ;;   in the X-Payment header.
189   ;;
190   ;; Version 1.1 looks like yymmdd:rrrrr:xxxxxxxxxxxxxxxx
191   ;;   You need to upgrade your hashcash binary.
192   ;;
193   ;; Version 1.0 looked like nnnnnrrrrrxxxxxxxxxxxxxxxx
194   ;;   This is no longer supported.
195   (cond ((equal (aref token 1) ?:) 1.2)
196         ((equal (aref token 6) ?:) 1.1)
197         (t (error "Unknown hashcash format version"))))
198
199 (defun hashcash-already-paid-p (recipient)
200   "Check for hashcash token to RECIPIENT in current buffer."
201   (save-excursion
202     (save-restriction
203       (message-narrow-to-headers-or-head)
204       (let ((token (message-fetch-field "x-hashcash")))
205         (and (stringp token)
206              (string-match (regexp-quote recipient) token))))))
207
208 ;;;###autoload
209 (defun hashcash-insert-payment (arg)
210   "Insert X-Payment and X-Hashcash headers with a payment for ARG"
211   (interactive "sPay to: ")
212   (unless (hashcash-already-paid-p arg)
213     (let ((pay (hashcash-generate-payment (hashcash-payment-to arg)
214                                           (hashcash-payment-required arg))))
215       (when pay
216         ;;      (insert-before-markers "X-Payment: hashcash "
217         ;;                           (number-to-string (hashcash-version pay)) " "
218         ;;                           pay "\n")
219         (insert-before-markers "X-Hashcash: " pay "\n")))))
220
221 ;;;###autoload
222 (defun hashcash-insert-payment-async (arg)
223   "Insert X-Payment and X-Hashcash headers with a payment for ARG
224 Only start calculation.  Results are inserted when ready."
225   (interactive "sPay to: ")
226   (unless (hashcash-already-paid-p arg)
227     (hashcash-generate-payment-async (hashcash-payment-to arg)
228                                      (hashcash-payment-required arg)
229                                      `(lambda (process payment)
230                                         (hashcash-insert-payment-async-2 ,(current-buffer) process payment)))))
231
232 (defun hashcash-insert-payment-async-2 (buffer process pay)
233   (with-current-buffer buffer
234     (save-excursion
235       (save-restriction
236         (setq hashcash-process-alist (delq
237                                       (assq process hashcash-process-alist)
238                                       hashcash-process-alist))
239         (goto-char (point-min))
240         (search-forward mail-header-separator)
241         (beginning-of-line)
242         (when pay
243 ;;      (insert-before-markers "X-Payment: hashcash "
244 ;;                           (number-to-string (hashcash-version pay)) " "
245 ;;                           pay "\n")
246           (insert-before-markers "X-Hashcash: " pay))))))
247
248 (defun hashcash-cancel-async (&optional buffer)
249   "Delete any hashcash processes associated with BUFFER.
250 BUFFER defaults to the current buffer."
251   (interactive)
252   (unless buffer (setq buffer (current-buffer)))
253   (let (entry)
254     (while (setq entry (rassq buffer hashcash-process-alist))
255       (delete-process (car entry))
256       (setq hashcash-process-alist
257             (delq entry hashcash-process-alist)))))
258
259 (defun hashcash-wait-async (&optional buffer)
260   "Wait for asynchronous hashcash processes in BUFFER to finish.
261 BUFFER defaults to the current buffer."
262   (interactive)
263   (unless buffer (setq buffer (current-buffer)))
264   (let (entry)
265     (while (setq entry (rassq buffer hashcash-process-alist))
266       (accept-process-output (car entry)))))
267
268 (defun hashcash-processes-running-p (buffer)
269   "Return non-nil if hashcash processes in BUFFER are still running."
270   (rassq buffer hashcash-process-alist))
271
272 (defun hashcash-wait-or-cancel ()
273   "Ask user whether to wait for hashcash processes to finish."
274   (interactive)
275   (when (hashcash-processes-running-p (current-buffer))
276     (if (y-or-n-p 
277           "Hashcash process(es) still running; wait for them to finish? ")
278         (hashcash-wait-async)
279       (hashcash-cancel-async))))
280
281 ;;;###autoload
282 (defun hashcash-verify-payment (token &optional resource amount)
283   "Verify a hashcash payment"
284   (let* ((split (split-string token ":"))
285          (key (if (< (hashcash-version token) 1.2)
286                   (nth 1 split)
287                   (case (string-to-number (nth 0 split))
288                     (0 (nth 2 split))
289                     (1 (nth 3 split))))))
290     (cond ((null resource)
291            (let ((elt (assoc key hashcash-accept-resources)))
292              (and elt (hashcash-check-payment token (car elt)
293                         (or (cadr elt) hashcash-default-accept-payment)))))
294           ((equal token key)
295            (hashcash-check-payment token resource
296                                 (or amount hashcash-default-accept-payment)))
297           (t nil))))
298
299 ;;;###autoload
300 (defun mail-add-payment (&optional arg async)
301   "Add X-Payment: and X-Hashcash: headers with a hashcash payment
302 for each recipient address.  Prefix arg sets default payment temporarily.
303 Set ASYNC to t to start asynchronous calculation.  (See
304 `mail-add-payment-async')."
305   (interactive "P")
306   (let ((hashcash-default-payment (if arg (prefix-numeric-value arg)
307                                     hashcash-default-payment))
308         (addrlist nil))
309     (save-excursion
310       (save-restriction
311         (goto-char (point-min))
312         (search-forward mail-header-separator)
313         (beginning-of-line)
314         (narrow-to-region (point-min) (point))
315         (let ((to (hashcash-strip-quoted-names (mail-fetch-field "To" nil t)))
316               (cc (hashcash-strip-quoted-names (mail-fetch-field "Cc" nil t)))
317               (ng (hashcash-strip-quoted-names (mail-fetch-field "Newsgroups"
318                                                                  nil t))))
319           (when to
320             (setq addrlist (split-string to ",[ \t\n]*")))
321           (when cc
322             (setq addrlist (nconc addrlist (split-string cc ",[ \t\n]*"))))
323           (when (and hashcash-in-news ng)
324             (setq addrlist (nconc addrlist (split-string ng ",[ \t\n]*")))))
325         (when addrlist
326           (mapcar (if async
327                       #'hashcash-insert-payment-async
328                     #'hashcash-insert-payment)
329                   addrlist))))) ; mapc
330   t)
331
332 ;;;###autoload
333 (defun mail-add-payment-async (&optional arg)
334   "Add X-Payment: and X-Hashcash: headers with a hashcash payment
335 for each recipient address.  Prefix arg sets default payment temporarily.
336 Calculation is asynchronous."
337   (interactive "P")
338   (mail-add-payment arg t))
339
340 ;;;###autoload
341 (defun mail-check-payment (&optional arg)
342   "Look for a valid X-Payment: or X-Hashcash: header.
343 Prefix arg sets default accept amount temporarily."
344   (interactive "P")
345   (let ((hashcash-default-accept-payment (if arg (prefix-numeric-value arg)
346                                            hashcash-default-accept-payment))
347         (version (hashcash-version (hashcash-generate-payment "x" 1))))
348     (save-excursion
349       (goto-char (point-min))
350       (search-forward "\n\n")
351       (beginning-of-line)
352       (let ((end (point))
353             (ok nil))
354         (goto-char (point-min))
355         (while (and (not ok) (search-forward "X-Payment: hashcash " end t))
356           (let ((value (split-string (hashcash-token-substring) " ")))
357             (when (equal (car value) (number-to-string version))
358               (setq ok (hashcash-verify-payment (cadr value))))))
359         (goto-char (point-min))
360         (while (and (not ok) (search-forward "X-Hashcash: " end t))
361           (setq ok (hashcash-verify-payment (hashcash-token-substring))))
362         (when ok
363           (message "Payment valid"))
364         ok))))
365
366 (provide 'hashcash)
367
368 ;;; arch-tag: 0e7fe983-a124-4392-9788-0dbcbd2c4d62