From 703b2efe6ee363fb882bd2eff3181155e10a1aab Mon Sep 17 00:00:00 2001 From: Greg Heartsfield Date: Sun, 15 Jan 2023 09:18:53 -0600 Subject: [PATCH] refactor: replaceable check in event --- src/bin/bulkloader.rs | 2 +- src/db.rs | 4 +++- src/event.rs | 18 ++++++++++++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/bin/bulkloader.rs b/src/bin/bulkloader.rs index 854ca52..cb9d3cd 100644 --- a/src/bin/bulkloader.rs +++ b/src/bin/bulkloader.rs @@ -160,7 +160,7 @@ fn write_event(tx: &Transaction, e: Event) -> Result { )?; } } - if e.kind == 0 || e.kind == 3 || e.kind == 41 || (e.kind >= 10000 && e.kind < 20000) { + if e.is_replaceable() { //let query = "SELECT id FROM event WHERE kind=? AND author=? ORDER BY created_at DESC LIMIT 1;"; //let count: usize = tx.query_row(query, params![e.kind, pubkey_blob], |row| row.get(0))?; //info!("found {} rows that /would/ be preserved", count); diff --git a/src/db.rs b/src/db.rs index 592ec81..6231701 100644 --- a/src/db.rs +++ b/src/db.rs @@ -374,6 +374,8 @@ pub fn write_event(conn: &mut PooledConnection, e: &Event) -> Result { let pubkey_blob: Option> = hex::decode(&e.pubkey).ok(); let delegator_blob: Option> = e.delegated_by.as_ref().and_then(|d| hex::decode(d).ok()); let event_str = serde_json::to_string(&e).ok(); + // check for replaceable events that would hide this one. + // ignore if the event hash is a duplicate. let mut ins_count = tx.execute( "INSERT OR IGNORE INTO event (event_hash, created_at, kind, author, delegated_by, content, first_seen, hidden) VALUES (?1, ?2, ?3, ?4, ?5, ?6, strftime('%s','now'), FALSE);", @@ -417,7 +419,7 @@ pub fn write_event(conn: &mut PooledConnection, e: &Event) -> Result { // if this event is replaceable update, hide every other replaceable // event with the same kind from the same author that was issued // earlier than this. - if e.kind == 0 || e.kind == 3 || e.kind == 41 || (e.kind >= 10000 && e.kind < 20000) { + if e.is_replaceable() { let author = hex::decode(&e.pubkey).ok(); // this is a backwards check - hide any events that were older. let update_count = tx.execute( diff --git a/src/event.rs b/src/event.rs index daf99f1..d476bee 100644 --- a/src/event.rs +++ b/src/event.rs @@ -120,6 +120,11 @@ impl Event { self.kind == 0 } + /// Should this event be replaced with newer timestamps from same author? + pub fn is_replaceable(&self) -> bool { + self.kind == 0 || self.kind == 3 || self.kind == 41 || (self.kind >= 10000 && self.kind < 20000) + } + /// Pull a NIP-05 Name out of the event, if one exists pub fn get_nip05_addr(&self) -> Option { if self.is_kind_metadata() { @@ -499,4 +504,17 @@ mod tests { let expected = Some(expected_json.to_owned()); assert_eq!(c, expected); } + + #[test] + fn replaceable_event() { + let mut event = Event::simple_event(); + event.kind=0; + assert!(event.is_replaceable()); + event.kind=3; + assert!(event.is_replaceable()); + event.kind=12000; + assert!(event.is_replaceable()); + + } + }