Skip to content

A peer-to-peer stack for code collaboration

1.9 KB
Raw Blame
{:module 'prelude/key-management
 :doc "Providing functions for creating and reading key pairs for signing send
 commands. Per default, key pairs are stored in `$HOME/.config/radicle/my-keys.rad`
 this can be adjusted by setting `$XDG_CONFIG_HOME`."
 :exports '[read-keys! get-keys! create-keys! set-fake-keys! use-fake-keys!]}

(import prelude/io :as 'io)
(import prelude/io-utils :as 'io)
(import prelude/strings :as 'string)
(import prelude/lens :unqualified)
(import prelude/error-messages :as 'error)

(def key-pair-mode (ref {:use-fake-key #f}))

(def set-fake-keys!
  "Bypass reading the keys from `my-keys.rad`, using instead the provided keys.
  This is intended for testing."
  (fn [keys]
    (set-ref key-pair-mode (@ :use-fake-key) #t)
    (set-ref key-pair-mode (@ :fake-key) keys)))

(def use-fake-keys!
  "Bypass reading the keys from `my-keys.rad`, using newly-generated ones.
  This is intended for testing."
  (fn [] (set-fake-keys! (gen-key-pair! (default-ecc-curve)))))

(def key-path
  (fn []
    (string-append (io/base-path!) "/my-keys.rad")))

(def read-keys!
  "Reads the keys stored in `my-keys.rad` or returns `:nothing` if the file
  doesn't exist."
  (fn []
    (if (lookup :use-fake-key (read-ref key-pair-mode))
      (lookup :fake-key (read-ref key-pair-mode))
      (catch 'any
        (io/read-file-value! (key-path))
        (fn [x] :nothing)))))

(def get-keys!
  "Like `read-keys` but prints an error message and exits the process if no key
  file was found."
  (fn []
    (match (read-keys!)
      :nothing (do (put-str! (error/missing-key-file))
                   (exit! 1))
      'keys    keys)))

(def create-keys!
  "Creates a new key pair and stores it in `my-keys.rad`. Returns the
  full absolute path of the created file."
  (fn []
    (io/shell! (string-append "mkdir -p " (io/base-path!)) "")
    (def kp (gen-key-pair! (default-ecc-curve)))
    (io/write-file! (key-path) (show kp))
    (key-path)))