From a59ade344b54d658ba780b3f9e8979376371d653 Mon Sep 17 00:00:00 2001 From: Michael Jurkoic Date: Tue, 12 Mar 2024 09:51:04 -0500 Subject: Generate a valid ID while serializing an event --- src/event.cpp | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/event.cpp b/src/event.cpp index 6a179fa..a95657e 100644 --- a/src/event.cpp +++ b/src/event.cpp @@ -1,12 +1,19 @@ #include +#include +#include #include #include +#include #include "nostr.hpp" using nlohmann::json; +using std::hex; using std::invalid_argument; +using std::setw; +using std::setfill; using std::string; +using std::stringstream; using std::time; namespace nostr @@ -23,7 +30,6 @@ string Event::serialize() } json j = { - {"id", this->id}, {"pubkey", this->pubkey}, {"created_at", this->createdAt}, {"kind", this->kind}, @@ -31,6 +37,11 @@ string Event::serialize() {"content", this->content}, {"sig", this->sig} }; + + j["id"] = this->generateId(j.dump()); + + // TODO: Reach out to a signer to sign the event, then set the signature. + return j.dump(); }; @@ -48,12 +59,6 @@ void Event::deserialize(string jsonString) void Event::validate() { - bool hasId = this->id.length() > 0; - if (!hasId) - { - throw std::invalid_argument("Event::validate: The event id is required."); - } - bool hasPubkey = this->pubkey.length() > 0; if (!hasPubkey) { @@ -78,4 +83,21 @@ void Event::validate() throw std::invalid_argument("Event::validate: The event must be signed."); } }; + +string Event::generateId(string serializedData) const +{ + unsigned char hash[SHA256_DIGEST_LENGTH]; + SHA256_CTX sha256; + SHA256_Init(&sha256); + SHA256_Update(&sha256, serializedData.c_str(), serializedData.length()); + SHA256_Final(hash, &sha256); + + stringstream ss; + for (int i = 0; i < SHA256_DIGEST_LENGTH; i++) + { + ss << hex << setw(2) << setfill('0') << (int)hash[i]; + } + + return ss.str(); +}; } // namespace nostr -- cgit