Hic inserere motto

ben_vulpes base58 encoding in Common Lisp

January 24, 2021 — shinohai

As the anniversary of the fall of TMSR approaches the decay of the once-proud institution is evident in the rapidly decreasing number of websites of former Lords., formerly operated by ben_vulpes (WoT:ben_vulpes) is sadly one of these castles specifically because the guy wrote the defacto introduction to vtronics (archived) and some interesting posts on common lisp.

One forgotten item I found particularly useful was an implementation of base58 encoding in common lisp. Sadly I could find no archive of the original article but after a bit of digging I found a copy of the code contained within saved on an old hard drive. I'm quoting it below so I have a handy reference for future projects.

(defparameter +b58-alphabet+ "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")

(defun b58-encode (bytes)
  (let ((string (make-string-output-stream))
        (bignum (loop for i to (- (length bytes) 1) summing
               (* (elt bytes i)
                  (expt 256 i)))))

   (loop while (> bignum 0) do
        (multiple-value-bind (x r) (floor bignum (length +b58-alphabet+))
          (write-char (elt +b58-alphabet+ r) string)
          (setf bignum x)))

   (loop for b across (reverse bytes) do
        (if (= 0 b)
            (write-char (elt +b58-alphabet+ 0) string)

   (reverse (get-output-stream-string string))))

Tags: Bitcoin, Lisp, News