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