ndb: implement eventref building from ndb notes

This commit is contained in:
William Casarin committed 2023-07-24 10:55:34 -07:00
1 parent c8e236b6d5
commit 1e9e4a7f3a
8 files changed
+209 -31

No files matched your search

+67
View File
@@ -73,3 +73,70 @@ func parse_note_content_ndb(note: NdbNote) -> Blocks {
return Blocks(words: words, blocks: out)
}
func interpret_event_refs_ndb(blocks: [Block], tags: TagsSequence) -> [EventRef] {
if tags.count == 0 {
return []
}
/// build a set of indices for each event mention
let mention_indices = build_mention_indices(blocks, type: .event)
/// simpler case with no mentions
if mention_indices.count == 0 {
let ev_refs = References(tags: tags).ids()
return interp_event_refs_without_mentions_ndb(ev_refs)
}
return interp_event_refs_with_mentions_ndb(tags: tags, mention_indices: mention_indices)
}
func interp_event_refs_without_mentions_ndb(_ ev_tags: LazyFilterSequence<References>) -> [EventRef] {
var count = 0
var evrefs: [EventRef] = []
var first: Bool = true
var first_ref: Reference? = nil
for ref in ev_tags {
if first {
first_ref = ref
evrefs.append(.thread_id(ref.to_referenced_id()))
first = false
} else {
evrefs.append(.reply(ref.to_referenced_id()))
}
count += 1
}
if let first_ref, count == 1 {
let r = first_ref.to_referenced_id()
return [.reply_to_root(r)]
}
return evrefs
}
func interp_event_refs_with_mentions_ndb(tags: TagsSequence, mention_indices: Set<Int>) -> [EventRef] {
var mentions: [EventRef] = []
var ev_refs: [ReferencedId] = []
var i: Int = 0
for tag in tags {
if tag.count >= 2, let t = tag[0], t.matches_char("e"),
let ref = tag_to_refid_ndb(tag)
{
if mention_indices.contains(i) {
let mention = Mention(index: i, type: .event, ref: ref)
mentions.append(.mention(mention))
} else {
ev_refs.append(ref)
}
}
i += 1
}
var replies = interp_event_refs_without_mentions(ev_refs)
replies.append(contentsOf: mentions)
return replies
}
+1 -1
View File
@@ -7,7 +7,7 @@
import Foundation
enum EventRef {
enum EventRef: Equatable {
case mention(Mention)
case thread_id(ReferencedId)
case reply(ReferencedId)
+1 -1
View File
@@ -158,7 +158,7 @@ func render_blocks(blocks: [Block]) -> String {
}
}
struct Blocks {
struct Blocks: Equatable {
let words: Int
let blocks: [Block]
}
+20 -6
View File
@@ -10,6 +10,9 @@ import Foundation
struct Reference {
let key: AsciiCharacter
let id: NdbTagElem
var ref_id: NdbTagElem {
id
}
func to_referenced_id() -> ReferencedId {
ReferencedId(ref_id: id.string(), relay_id: nil, key: key.string)
@@ -17,11 +20,11 @@ struct Reference {
}
struct References: Sequence, IteratorProtocol {
let note: NdbNote
var tags: TagsIterator
let tags: TagsSequence
var tags_iter: TagsIterator
mutating func next() -> Reference? {
while let tag = tags.next() {
while let tag = tags_iter.next() {
guard let key = tag[0], key.count == 1,
let id = tag[1], id.is_id
else { continue }
@@ -35,9 +38,20 @@ struct References: Sequence, IteratorProtocol {
return nil
}
init(note: NdbNote) {
self.note = note
self.tags = note.tags().makeIterator()
func ids() -> LazyFilterSequence<References> {
References(tags: tags).lazy
.filter() { ref in ref.key == "e" }
}
func pubkeys() -> LazyFilterSequence<References> {
References(tags: tags).lazy
.filter() { ref in ref.key == "p" }
}
init(tags: TagsSequence) {
self.tags = tags
self.tags_iter = tags.makeIterator()
}
}
+4
View File
@@ -160,6 +160,10 @@ Curated playlists from WASTOIDS friends
[Follow us on Nostr!](https://primal.net/wastoids)
"""
// a random event I found to test event refs
let test_reply_json = """
{"kind":1,"id":"9c845174ff41dfafe5a1a435ce0da8e00d253951956d760b2d1fa3f45295f146","content":"nostr:npub1wxl6njlcgygduct7jkgzrvyvd9fylj4pqvll6p32h59wyetm5fxqjchcan and nostr:npub1vp8fdcyejd4pqjyrjk9sgz68vuhq7pyvnzk8j0ehlljvwgp8n6eqsrnpsw have come up with 2 different solutions that are a few extra steps but are fantastic.","created_at":1690211612,"tags":[["e","7e31960ca1c9e03664dcbde1b208f2c340af3dc5acfe0479c0bad761f561b6c2"],["p","3efdaebb1d8923ebd99c9e7ace3b4194ab45512e2be79c1b7d68d9243e0d2681"],["p","32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245"],["p","4d8e327543efbe13ef4f49e43922a40258ac60ededcee062a568f18845a09a04"],["p","71bfa9cbf84110de617e959021b08c69524fcaa1033ffd062abd0ae2657ba24c"],["p","604e96e099936a104883958b040b47672e0f048c98ac793f37ffe4c720279eb2"]],"pubkey":"8c71091d5b7dea833eae73bb07e28f12cc456dc791aa7f213ad175fb5a1d6fe6","sig":"b8a81536c10e2633340206cd9a822f2725827d158f6af9e5888af361d927c83dc6c8ea7598fbe7d6fdbe3086a5f595a92b97a690a6e5e2bfd5c9d216c3a97271"}
"""
let test_contact_list_json = """
{"content":"{\\\"wss://nos.lol\\\":{\\\"write\\\":true,\\\"read\\\":true},\\\"wss://relay.damus.io\\\":{\\\"write\\\":true,\\\"read\\\":true},\\\"ws://monad.jb55.com:8080\\\":{\\\"write\\\":true,\\\"read\\\":true},\\\"wss://nostr.wine\\\":{\\\"write\\\":true,\\\"read\\\":true},\\\"wss://welcome.nostr.wine\\\":{\\\"write\\\":true,\\\"read\\\":true},\\\"wss://eden.nostr.land\\\":{\\\"write\\\":true,\\\"read\\\":true},\\\"wss://relay.mostr.pub\\\":{\\\"write\\\":true,\\\"read\\\":true},\\\"wss://nostr-pub.wellorder.net\\\":{\\\"write\\\":true,\\\"read\\\":true}}","created_at":1689904312,"id":"20d0ff27d6fcb13de8366328c5b1a7af26bcac07f2e558fbebd5e9242e608c09","kind":3,"pubkey":"32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245","sig":"f388e9b45d2872e9320e2d092f52d3d9ccee7e83ef3376b48a705c22099d27736fcc750800e0b6cd4a2a6b7a44c4b0b435c7242392c7ceeb809da40c1fa1ee6c","tags":[["p","6cad545430904b84a8101c5783b65043f19ae29d2da1076b8fc3e64892736f03","wss://nostr-pub.wellorder.net"],["p","2ef93f01cd2493e04235a6b87b10d3c4a74e2a7eb7c3caf168268f6af73314b5","wss://nostr-pub.wellorder.net"],["p","9ec7a778167afb1d30c4833de9322da0c08ba71a69e1911d5578d3144bb56437","wss://nostr.bitcoiner.social"],["p","b2d670de53b27691c0c3400225b65c35a26d06093bcc41f48ffc71e0907f9d4a","wss://nostr-relay.untethr.me"],["p","3bf0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d","wss://nostr-relay.freeberty.net"],["p","8c0da4862130283ff9e67d889df264177a508974e2feb96de139804ea66d6168","wss://nostr-pub.wellorder.net"],["p","21763c71793764a2661eb10ede32a8f2312c9f8db08bc539c888bafa38dcf368"],["p","4570d7a0b49b5524797120810116a2a5c18281423b173a557056f08f15c5382d","wss://nostr-pub.wellorder.net"],["p","04c915daefee38317fa734444acee390a8269fe5810b2241e5e6dd343dfbecc9","wss://nostr-relay.freeberty.net"],["p","d3646691ba5b1d796c1e1b3430df00fe1189ec9c232877adde18c8f656af18f0"],["p","34af16f1787b261331a67fa519e9edb11f0a851c0b10a15901720b0fe0a06d1d"],["p","b7c66ce6f7bbe034e96be54c2ffc0adf631a889abc0834ba1431171b67c489aa"],["p","8355095016fddbe31fcf1453b26f613553e9758cf2263e190eac8fd96a3d3de9"],["p","3efdaebb1d8923ebd99c9e7ace3b4194ab45512e2be79c1b7d68d9243e0d2681"],["p","35d26e4690cbe1a898af61cc3515661eb5fa763b57bd0b42e45099c8b32fd50f"],["p","0810b5bc4cddc3e7624a1f6acbdccdc95c6e9409c144ce83365ee04a3a63314e"],["p","51fc7209201b1414f721c3d2d2b3430699b1e6317716c5182cc1d7945072e358"],["p","e6a92d8b6c20426f78bba8510ccdc73df5122814a3bac1d553adebac67a92b27"],["p","619d0c0483a311a16767b0a7999ce9f28e58e79eff66f0edafae9ca2d9054f08"],["p","d7b76d02c758a62a505e03bd5f5049aaee4e7e36283d273c7f6798912692df2b"],["p","d4d4fdde8ab4924b1e452e896709a3bd236da4c0576274b52af5992d4d34762c"],["p","3878d95db7b854c3a0d3b2d6b7bf9bf28b36162be64326f5521ba71cf3b45a69"],["p","ac9ec020170155f0feb347f0d777ee5fc38dd1f36353093046323646cff5169f"],["p","d91191e30e00444b942c0e82cad470b32af171764c2275bee0bd99377efd4075"],["p","146bda4ec6932830503ee4f8e8b626bd7b3a5784232b8240ba15c8cbff9a07cd"],["p","ea75802dd1c86933c1e20c582541bb283d44c88e3445ed90d4375fc3d973f3a0"],["p","41108126409bf99cb77ff16fd53f4da2e53010b0dca04b0a53ebdf46eade37aa"],["p","9682c33f9024dadb1bffdf762c3156e26b4aa340de8d06c91ca537fcc0fdb3a9"],["p","a8f14f05c64f9e62bdada89c21a52f09aa5d7948b47ccf52da1be16b0de9efac"],["p","80482e60178c2ce996da6d67577f56a2b2c47ccb1c84c81f2b7960637cb71b78"],["p","b10c0000079a83cf26815dc7538818d8d56a2983e374e30a4143e50060978457"],["p","547fcc5c7e655fe7c83da5a812e6332f0a4779c87bf540d8e75a4edbbf36fe4a"],["p","dd81a8bacbab0b5c3007d1672fb8301383b4e9583d431835985057223eb298a5"],["p","bb1cf5250435ff475cd8b32acb23e3ee7bbe8fc38f6951704b4798513947672c"],["p","1fa91680ebfc68069ec13423fc8b9b0a746e9265584e16cf7d80be7ad721de6e"],["p","52b4a076bcbbbdc3a1aefa3735816cf74993b1b8db202b01c883c58be7fad8bd"],["p","d8139f130cc1dec5d92e3a4dc49fb11f064bf5b32c65d96da107ba2389547dc7"],["p","9ac12013d20fae4f8829ba4e5ba6343e410288d3a0752d6143386d2c1af1f57e"],["p","46fcbe3065eaf1ae7811465924e48923363ff3f526bd6f73d7c184b16bd8ce4d"],["p","4b0572ab1f9a575415326b599f1179c20134bc23040d207156e71800b4ed33fe"],["p","2fa4b9ba71b6dab17c4723745bb7850dfdafcb6ae1a8642f76f9c64fa5f43436"],["p","3235036bd0957dfb27ccda02d452d7c763be40c91a1ac082ba6983b25238388c"],["p","954aaf69c2e7c9fb3f9998f61944ab8ab08ce3c8679ecd985e4486a6eb696217"],["p","d7f0e3917c466f1e2233e9624fbd6d4bd1392dbcfcaf3574f457569d496cb731"],["p","08b80da85ba68ac031885ea555ab42bb42231fde9b690bbd0f48c128dfbf8009"],["p","104749bc9151a0e54b9845ee50fc4b559439dd1ada006e36a6c49ad3ea16a55c"],["p","c47daa0cd21a70797fe9404f8fe0c3f679c2b46148788d1295e6424232064f1d"],["p","d987084c48390a290f5d2a34603ae64f55137d9b4affced8c0eae030eb222a25"],["p","e1ff3bfdd4e40315959b08b4fcc8245eaa514637e1d4ec2ae166b743341be1af"],["p","cf9413eb6bbe55c8a3c10119ec0635e134fa266f2c50f825d7225da9b92ecc4e"],["p","bae77874946ec111f94be59aef282de092dc4baf213f8ecb8c9e15cb7ed7304e"],["p","c7eda660a6bc8270530e82b4a7712acdea2e31dc0a56f8dc955ac009efd97c86"],["p","2590201e2919a8aa6568c88900192aa54ef00e6c0974a5Line truncated
+46 -23
View File
@@ -39,6 +39,14 @@ class NdbNote {
let count: Int
let note: UnsafeMutablePointer<ndb_note>
// cached stuff (TODO: remove these)
private var _event_refs: [EventRef]? = nil
var decrypted_content: String? = nil
private var _blocks: Blocks? = nil
private lazy var inner_event: NdbNote? = {
return NdbNote.owned_from_json_cstr(json: content_raw, json_len: content_len)
}()
init(note: UnsafeMutablePointer<ndb_note>, owned_size: Int?) {
self.note = note
self.owned = owned_size != nil
@@ -86,12 +94,20 @@ class NdbNote {
}
static func owned_from_json(json: String, bufsize: Int = 2 << 18) -> NdbNote? {
return json.withCString { cstr in
return NdbNote.owned_from_json_cstr(
json: cstr, json_len: UInt32(json.utf8.count), bufsize: bufsize)
}
}
static func owned_from_json_cstr(json: UnsafePointer<CChar>, json_len: UInt32, bufsize: Int = 2 << 18) -> NdbNote? {
let data = malloc(bufsize)
guard var json_cstr = json.cString(using: .utf8) else { return nil }
//guard var json_cstr = json.cString(using: .utf8) else { return nil }
//json_cs
var note: UnsafeMutablePointer<ndb_note>?
let len = ndb_note_from_json(&json_cstr, Int32(json_cstr.count), &note, data, Int32(bufsize))
let len = ndb_note_from_json(json, Int32(json_len), &note, data, Int32(bufsize))
if len == 0 {
free(data)
@@ -100,8 +116,8 @@ class NdbNote {
// Create new Data with just the valid bytes
guard let note_data = realloc(data, Int(len)) else { return nil }
let new_note = note_data.assumingMemoryBound(to: ndb_note.self)
return NdbNote(note: new_note, owned_size: Int(len))
}
}
@@ -152,26 +168,39 @@ extension NdbNote {
// TODO: References iterator
public var referenced_ids: LazyFilterSequence<References> {
References(note: self).lazy
.filter() { ref in ref.key == "e" }
References(tags: self.tags()).ids()
}
public var referenced_pubkeys: LazyFilterSequence<References> {
References(note: self).lazy
.filter() { ref in ref.key == "p" }
References(tags: self.tags()).pubkeys()
}
/*
func event_refs(_ privkey: String?) -> [EventRef] {
if let rs = _event_refs {
return rs
}
let refs = interpret_event_refs(blocks: self.blocks(privkey).blocks, tags: self.tags)
let refs = interpret_event_refs_ndb(blocks: self.blocks(privkey).blocks, tags: self.tags())
self._event_refs = refs
return refs
}
func get_content(_ privkey: String?) -> String {
if known_kind == .dm {
return decrypted(privkey: privkey) ?? "*failed to decrypt content*"
}
return content
}
func blocks(_ privkey: String?) -> Blocks {
if let bs = _blocks { return bs }
let blocks = get_blocks(content: self.get_content(privkey))
self._blocks = blocks
return blocks
}
// NDBTODO: switch this to operating on bytes not strings
func decrypted(privkey: String?) -> String? {
if let decrypted_content = decrypted_content {
return decrypted_content
@@ -185,38 +214,32 @@ extension NdbNote {
return nil
}
var pubkey = self.pubkey
// NDBTODO: don't hex encode
var pubkey = hex_encode(self.pubkey)
// This is our DM, we need to use the pubkey of the person we're talking to instead
if our_pubkey == pubkey {
guard let refkey = self.referenced_pubkeys.first else {
return nil
}
pubkey = refkey.ref_id
pubkey = refkey.ref_id.string()
}
// NDBTODO: pass data to pubkey
let dec = decrypt_dm(key, pubkey: pubkey, content: self.content, encoding: .base64)
self.decrypted_content = dec
return dec
}
func get_content(_ privkey: String?) -> String {
if known_kind == .dm {
return decrypted(privkey: privkey) ?? "*failed to decrypt content*"
}
return content
}
/*
var description: String {
return "NostrEvent { id: \(id) pubkey \(pubkey) kind \(kind) tags \(tags) content '\(content)' }"
}
var known_kind: NostrKind? {
return NostrKind.init(rawValue: kind)
}
private enum CodingKeys: String, CodingKey {
case id, sig, tags, pubkey, created_at, kind, content
}
+4
View File
@@ -56,6 +56,10 @@ struct TagsSequence: Sequence {
return nil
}
func references() -> References {
return References(tags: self)
}
func makeIterator() -> TagsIterator {
return .init(note: note)
}
+66
View File
@@ -74,6 +74,72 @@ final class NdbTests: XCTestCase {
}
}
func test_perf_old_decoding() {
self.measure {
let event = decode_nostr_event_json(test_contact_list_json)
XCTAssertNotNil(event)
}
}
func test_perf_old_iter() {
self.measure {
let event = decode_nostr_event_json(test_contact_list_json)
XCTAssertNotNil(event)
}
}
func longer_iter(_ n: Int = 1000) -> XCTMeasureOptions {
let opts = XCTMeasureOptions()
opts.iterationCount = n
return opts
}
func test_perf_interp_evrefs_old() {
guard let event = decode_nostr_event_json(test_reply_json) else {
return
}
self.measure(options: longer_iter()) {
let blocks = event.blocks(nil).blocks
let xs = interpret_event_refs(blocks: blocks, tags: event.tags)
XCTAssertEqual(xs.count, 1)
}
}
func test_perf_interp_evrefs_ndb() {
guard let note = NdbNote.owned_from_json(json: test_reply_json) else {
return
}
self.measure(options: longer_iter()) {
let blocks = note.blocks(nil).blocks
let xs = interpret_event_refs_ndb(blocks: blocks, tags: note.tags())
XCTAssertEqual(xs.count, 1)
}
}
func test_decoded_events_are_equal() {
let event = decode_nostr_event_json(test_reply_json)
let note = NdbNote.owned_from_json(json: test_reply_json)
XCTAssertNotNil(note)
XCTAssertNotNil(event)
guard let note else { return }
guard let event else { return }
XCTAssertEqual(note.content_len, UInt32(event.content.utf8.count))
XCTAssertEqual(hex_encode(note.pubkey), event.pubkey)
XCTAssertEqual(hex_encode(note.id), event.id)
let ev_blocks = event.blocks(nil)
let note_blocks = note.blocks(nil)
XCTAssertEqual(ev_blocks, note_blocks)
let event_refs = interpret_event_refs(blocks: ev_blocks.blocks, tags: event.tags)
let note_refs = interpret_event_refs_ndb(blocks: note_blocks.blocks, tags: note.tags())
XCTAssertEqual(event_refs, note_refs)
}
func test_iteration_perf() throws {
guard let note = NdbNote.owned_from_json(json: test_contact_list_json) else {
XCTAssert(false)