event.rs (2249B)
1 use crate::{Error, Pubkey, Result}; 2 use serde_derive::{Deserialize, Serialize}; 3 use std::hash::{Hash, Hasher}; 4 5 /// Event is the struct used to represent a Nostr event 6 #[derive(Serialize, Deserialize, Debug, Clone)] 7 pub struct Event { 8 /// 32-bytes sha256 of the the serialized event data 9 pub id: EventId, 10 /// 32-bytes hex-encoded public key of the event creator 11 #[serde(rename = "pubkey")] 12 pub pubkey: Pubkey, 13 /// unix timestamp in seconds 14 pub created_at: u64, 15 /// integer 16 /// 0: NostrEvent 17 pub kind: u64, 18 /// Tags 19 pub tags: Vec<Vec<String>>, 20 /// arbitrary string 21 pub content: String, 22 /// 64-bytes signature of the sha256 hash of the serialized event data, which is the same as the "id" field 23 pub sig: String, 24 } 25 26 // Implement Hash trait 27 impl Hash for Event { 28 fn hash<H: Hasher>(&self, state: &mut H) { 29 self.id.0.hash(state); 30 } 31 } 32 33 impl PartialEq for Event { 34 fn eq(&self, other: &Self) -> bool { 35 self.id == other.id 36 } 37 } 38 39 impl Eq for Event {} 40 41 impl Event { 42 pub fn from_json(s: &str) -> Result<Self> { 43 serde_json::from_str(s).map_err(Into::into) 44 } 45 46 pub fn verify(&self) -> Result<Self> { 47 return Err(Error::InvalidSignature); 48 } 49 50 /// This is just for serde sanity checking 51 #[allow(dead_code)] 52 pub(crate) fn new_dummy( 53 id: &str, 54 pubkey: &str, 55 created_at: u64, 56 kind: u64, 57 tags: Vec<Vec<String>>, 58 content: &str, 59 sig: &str, 60 ) -> Result<Self> { 61 let event = Event { 62 id: id.to_string().into(), 63 pubkey: pubkey.to_string().into(), 64 created_at, 65 kind, 66 tags, 67 content: content.to_string(), 68 sig: sig.to_string(), 69 }; 70 71 event.verify() 72 } 73 } 74 75 impl std::str::FromStr for Event { 76 type Err = Error; 77 78 fn from_str(s: &str) -> Result<Self> { 79 Event::from_json(s) 80 } 81 } 82 83 #[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone, Hash)] 84 pub struct EventId(String); 85 86 impl From<String> for EventId { 87 fn from(s: String) -> Self { 88 EventId(s) 89 } 90 } 91 92 impl From<EventId> for String { 93 fn from(evid: EventId) -> Self { 94 evid.0 95 } 96 }