From 9bc75875577c429c5a74a9fc2130bd036a6b36c5 Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Sun, 15 Oct 2017 21:22:52 -0700 Subject: [PATCH] ircd::json: Add a preliminary suite of sign()/verify()/hash() for tuple. --- include/ircd/json/tuple.h | 92 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/include/ircd/json/tuple.h b/include/ircd/json/tuple.h index 68fd342ef..339c6d9e0 100644 --- a/include/ircd/json/tuple.h +++ b/include/ircd/json/tuple.h @@ -64,6 +64,7 @@ struct tuple using super_type = tuple; operator json::value() const; + operator crh::sha256::buf() const; static constexpr size_t size(); @@ -995,6 +996,97 @@ operator<<(std::ostream &s, const tuple &t) return s; } +template +tuple::operator +crh::sha256::buf() +const +{ + //TODO: XXX + const auto preimage + { + json::strung(*this) + }; + + return crh::sha256::buf + { + [&preimage](auto &buf) + { + sha256{buf, const_raw_buffer{preimage}}; + } + }; +} + +template +enable_if_tuple +sign(const tuple &t, + const ed25519::sk &sk) +{ + //TODO: XXX + const auto preimage + { + json::strung(t) + }; + + return ed25519::sig + { + [&sk, &preimage](auto &buf) + { + sk.sign(buf, const_raw_buffer{preimage}); + } + }; +} + +template +enable_if_tuple +verify(const tuple &t, + const ed25519::pk &pk, + const ed25519::sig &sig, + std::nothrow_t) +noexcept try +{ + //TODO: XXX + const auto preimage + { + json::strung(t) + }; + + return pk.verify(const_raw_buffer{preimage}, sig); +} +catch(const std::exception &e) +{ + log::error("Verification of json::tuple unexpected failure: %s", e.what()); + return false; +} + +template +enable_if_tuple +verify(const tuple &t, + const ed25519::pk &pk, + const ed25519::sig &sig) +{ + if(!verify(t, pk, sig, std::nothrow)) + throw ed25519::bad_sig{"Verification failed"}; +} + +template +enable_if_tuple +verify(const tuple &t, + const ed25519::pk &pk) +{ + const ed25519::sig sig + { + [&t](auto &buf) + { + b64decode(buf, at<"signatures"_>(t)); + } + }; + + auto copy(t); + at<"signatures"_>(copy) = string_view{}; + if(!verify(copy, pk, sig, std::nothrow)) + throw ed25519::bad_sig{"Verification failed"}; +} + template tuple::operator json::value()