nostrdb

an unfairly fast embedded nostr database backed by lmdb
git clone git://jb55.com/nostrdb
Log | Files | Refs | Submodules | README | LICENSE

commit 3283fc4531f5b7ebac9a3b02c2b6c10c9a94470e
parent 46984bef852b9effbb1d48b8a0f8d6b1486b93ba
Author: William Casarin <jb55@jb55.com>
Date:   Tue, 30 Apr 2024 23:19:05 +0200

api: add ndb_note_json

add a way to write an ndb note as json to a buffer

Diffstat:
Msrc/nostrdb.c | 48++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/nostrdb.h | 3+++
2 files changed, 51 insertions(+), 0 deletions(-)

diff --git a/src/nostrdb.c b/src/nostrdb.c @@ -4726,6 +4726,54 @@ static int ndb_event_commitment(struct ndb_note *ev, unsigned char *buf, int buf return cur.p - cur.start; } +static int cursor_push_hex(struct cursor *c, unsigned char *bytes, int len) +{ + int i; + unsigned char chr; + if (c->p + (len * 2) >= c->end) + return 0; + + for (i = 0; i < len; i++) { + chr = bytes[i]; + + *(c->p++) = hexchar(chr >> 4); + *(c->p++) = hexchar(chr & 0xF); + } + + return 1; +} + +static int cursor_push_int_str(struct cursor *c, int num) +{ + char timebuf[16] = {0}; + snprintf(timebuf, sizeof(timebuf), "%d", num); + return cursor_push_str(c, timebuf); +} + +int ndb_note_json(struct ndb_note *note, char *buf, int buflen) +{ + struct cursor cur, *c = &cur; + + make_cursor((unsigned char *)buf, (unsigned char*)buf + buflen, &cur); + + return cursor_push_str(c, "{\"id\":\"") && + cursor_push_hex(c, ndb_note_id(note), 32) && + cursor_push_str(c, "\",\"pubkey\":\"") && + cursor_push_hex(c, ndb_note_pubkey(note), 32) && + cursor_push_str(c, "\",\"created_at\":") && + cursor_push_int_str(c, ndb_note_created_at(note)) && + cursor_push_str(c, ",\"kind\":") && + cursor_push_int_str(c, ndb_note_kind(note)) && + cursor_push_str(c, ",\"tags\":") && + cursor_push_json_tags(c, note) && + cursor_push_str(c, ",\"content\":") && + cursor_push_jsonstr(c, ndb_note_content(note)) && + cursor_push_str(c, ",\"sig\":\"") && + cursor_push_hex(c, ndb_note_sig(note), 64) && + cursor_push_c_str(c, "\"}"); + +} + int ndb_calculate_id(struct ndb_note *note, unsigned char *buf, int buflen) { int len; diff --git a/src/nostrdb.h b/src/nostrdb.h @@ -528,6 +528,9 @@ void _ndb_note_set_kind(struct ndb_note *note, uint32_t kind); struct ndb_tags *ndb_note_tags(struct ndb_note *note); int ndb_str_len(struct ndb_str *str); +/// write the note as json to a buffer +int ndb_note_json(struct ndb_note *, char *buf, int buflen); + // TAGS void ndb_tags_iterate_start(struct ndb_note *note, struct ndb_iterator *iter); uint16_t ndb_tags_count(struct ndb_tags *);