A peer-to-peer stack for code collaboration
{:module 'prelude/validation
:doc "Functions for creating or combining *validators*, which are functions
which return the input unchanged or throw with an error message. These can be
used for checking data before accepting it onto a chain."
:exports
'[= member and or type pred integral optional-key contains contains-all
contains-only key optional-keys keys every uuid signed timestamp
string-of-max-length always-valid]}
(import prelude/dict :unqualified)
(import prelude/dict :as 'dict)
(import prelude/set :as 'set)
(def always-valid
"A validator that is always valid."
(fn [x] x))
(def =
"Given `x`, returns a validator that checks for equality with `x`."
(fn [x]
(fn [y]
(if (eq? x y)
x
(throw 'validation-failure {:info "Was not equal to expected value."
:expected x
:actual y})))))
(def member
"Given a structure, returns a validator which checks for membership in the structure."
(fn [xs]
(fn [x]
(if (member? x xs)
x
(throw 'validation-failure {:info "Element was not a member of container."
:container xs
:element x})))))
(def and
"Given a sequence of validators `vs`, returns a new validator which, given a
value, checks if it conforms to all the validators in `vs`."
(fn [vs]
(fn [x]
(map (fn [v] (v x)) vs)
x)))
(def-rec or
"Given a vector of validators `vs`, returns a new validator which, given a
value, checks if it conforms to at least one of the `vs`."
(fn [vs]
(fn [x]
(if (eq? vs [])
(throw 'validation-failure "validation/or: didn't satisfy any of the validators")
(catch
'validation-failure
((nth 0 vs) x)
(fn [y] ((or (drop 1 vs)) x)))))))
(def type
"Checks that a value has a type. Expects a keyword describing the type, as
returned by the `type` function."
(fn [t]
(fn [x]
(if (eq? (type x) t)
x
(throw 'validation-failure {:info "Value was not of the correct type."
:value x
:expected-type t})))))
(def pred
"Given a description and a predicate, returns a validator that checks if the
predicate is true."
(fn [name p]
(fn [x]
(if (p x)
x
(throw 'validation-failure {:info "Did not satisfy predicate."
:name name})))))
(def integral
"Validator for whole numbers."
(fn [n]
(if (integral? n)
n
(throw 'validation-failure {:info "Number was not an integer."
:number n}))))
(:test "integral"
[ (integral 0) ==> 0 ]
[ (catch 'validation-failure
(integral 1/3)
(fn [e] (lookup :number e))) ==> 1/3 ])
(def optional-key
"Given a key `k` and a validator `v`, returns a validator which checks that the
value associated to `k` in a dict conforms to `v`. If the key is absent, the
validator passes."
(fn [k v]
(fn [d]
(if (member? k d)
(do (v (lookup k d))
d)
d))))
(:test "optional-key"
[ ((optional-key :a (= 0)) {}) ==> {} ]
[ ((optional-key :a (= 0)) {:a 0}) ==> {:a 0} ]
[ (catch 'validation-failure
((optional-key :a (= 0)) {:a 1})
(fn [_] :ok))
==> :ok ])
(def contains
"Given a value, returns a validator which checks for membership of that value."
(fn [k]
(fn [x]
(if (member? k x)
x
(throw 'validation-failure {:info "Did not contain key."
:element k
:container x})))))
(:test "contains"
[ ((contains 42) {42 #t}) ==> {42 #t}]
[ (catch 'validation-failure
((contains 42) {})
(fn [e] (lookup :element e))) ==> 42])
(def key
"Combines existence and validity of a key in a dict."
(fn [k v]
(and [(contains k) (optional-key k v)])))
(:test "key"
[ ((key :a (= 0)) {:a 0}) ==> {:a 0} ]
[ (catch 'validation-failure
((key :a (= 0)) {})
(fn [e] (lookup :element e))) ==> :a ]
[ (catch 'validation-failure
((key :a (= 0)) {:a 1})
(fn [e] (lookup :expected e))) ==> 0])
(def optional-keys
"Given a dict associating keys to validators, returns a validator which checks
that the values associated to those keys in a dict conform to the
corresponding validators."
(fn [ks]
(fn [d]
(if (dict? d)
((and
(map (fn [kv] (optional-key (nth 0 kv) (nth 1 kv)))
(seq ks)))
d)
(throw 'validation-failure (string-append "Not a dict: " (show d)))))))
(:test "optional-keys"
[ ((optional-keys {0 (= 0) 1 (= 1)}) {0 0 1 1}) ==> {0 0 1 1}]
[ (catch 'validation-failure
((optional-keys {0 (= 0) 1 (= 1)}) {0 0 1 2})
(fn [e] (lookup :expected e))) ==> 1])
(def contains-all
"Given a vector of keys, returns a validator which checks that a structure
contains all of them."
(fn [ks]
(and (map contains ks))))
(:test "contains-all"
[ ((contains-all [0 1]) {0 0 1 1}) ==> {0 0 1 1}]
[ (catch 'validation-failure
((contains-all [0 1]) {0 0 2 2})
(fn [e] (lookup :element e))) ==> 1 ])
(def contains-only
"Validator which checks that a dict only contains a subset of a vector of keys."
(fn [ks]
(fn [d]
(if (set/subset? (set/key-set d) (set/from-seq ks))
d
(throw 'validation-failure {:info "Dict contained illegal keys."
:dict d
:allowed-keys ks})))))
(:test "contains-only"
[ ((contains-only [0 1]) {0 0}) ==> {0 0}]
[ (catch 'validation-failure
((contains-only [0 1]) {0 0 2 2})
(fn [e] (lookup :allowed-keys e))) ==> [0 1]])
(def keys
"Given a dict `d`, returns a validator which checks that a dict contains all the
keys that `d` does, and that the associated values a valid according to the
associated validators."
(fn [d]
(and [(contains-all (dict/keys d)) (optional-keys d)])))
(:test "keys"
[ ((keys {0 (= 0) 1 (= 1)}) {0 0 1 1}) ==> {0 0 1 1}]
[ (catch 'validation-failure
((keys {0 (= 0) 1 (= 1)}) {0 0})
(fn [e] (lookup :element e))) ==> 1]
[ (catch 'validation-failure
((keys {0 (= 0) 1 (= 1)}) {0 0 1 2})
(fn [e] (lookup :expected e))) ==> 1])
(def every
"Given a validator, creates a new validator which checks that all the items in
a sequence conform to it."
(fn [v]
(fn [xs]
(map v xs))))
(:test "every"
[ ((every (= 0)) [0 0 0]) ==> [0 0 0]]
[ ((every (= 0)) []) ==> []]
[ (catch 'validation-failure
((every (= 0)) [0 1])
(fn [e] (lookup :actual e))) ==> 1])
(def uuid
"Validates UUIDs."
(and
[(type :string)
(pred "valid UUID" uuid?)]))
(:test "uuid"
[ (uuid "3c038e2f-0f0c-4d49-8f10-6a44e75fbf40") ==> "3c038e2f-0f0c-4d49-8f10-6a44e75fbf40"]
[ (catch 'validation-failure
(uuid "nope")
(fn [_] :not-uuid)) ==> :not-uuid ])
(def signed
"Checks that a value is a dict with `:signature` and `:author` keys, and that
the signature is valid for the rest of the dict for that author. The rest of
the dict is turned into a string according to `show`."
(and
[(keys
{:author (pred "valid public key" public-key?)})
(pred
"Valid signature"
(fn [d]
(verify-signature
(lookup :author d)
(lookup :signature d)
(show (delete-many [:author :signature] d)))))]))
(:test "signed"
[:setup
(do (def keys (gen-key-pair! (default-ecc-curve)))
(def sk (lookup :private-key keys))
(def pk (lookup :public-key keys))
(def payload
{:nonce (uuid!)
:some "data"})
(def payload_ (insert :some "datadata" payload))
(def sig (gen-signature! sk (show payload)))
(def seal {:author (lookup :public-key keys)
:signature sig})
(def full (<> payload seal))
(def full_ (<> payload_ seal))
(def ok
(catch 'validation-failure (do (signed full) :ok) (fn [_] :not-ok)))
)
]
[ ok ==> :ok ]
)
(def timestamp
"A validator which checks if a string is an ISO 8601 formatted Coordinated
Universal Time (UTC) timestamp."
(and [(type :string)
(pred "valid timestamp" timestamp?)]))
(:test "timestamp"
[ (timestamp "2018-12-12T14:10:21Z") ==> "2018-12-12T14:10:21Z"]
[ (catch 'validation-failure
(timestamp "12-12-2018T14:10:21Z")
(fn [_] :ok)) ==> :ok ])
(def string-of-max-length
"A validator which checks that it's argument is a string and less than the
specified length."
(fn [max-len]
(and
[(type :string)
(pred (string-append "< " (show max-len) " chars in length")
(fn [s] (< (length s) max-len)))])))