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