nostrdb/block: add bolt11 invoice encoding/decoding

Signed-off-by: William Casarin <jb55@jb55.com>
This commit is contained in:
William Casarin
2023-12-23 14:46:00 -08:00
committed by Daniel D’Aquino
parent acaf327a07
commit 373cd71f69
4 changed files with 91 additions and 1 deletions

View File

@@ -4,6 +4,7 @@
#include "short_types.h"
#include "hash_u5.h"
#include "list.h"
#include "amount.h"
#include "node_id.h"
//#include <secp256k1_recovery.h>

69
nostrdb/src/invoice.c Normal file
View File

@@ -0,0 +1,69 @@
#include "cursor.h"
#include "invoice.h"
#include "bolt11/bolt11.h"
#include "bolt11/amount.h"
int ndb_encode_invoice(struct cursor *cur, struct bolt11 *invoice) {
if (!invoice->description && !invoice->description_hash)
return 0;
if (!cursor_push_byte(cur, 1))
return 0;
// TODO: make cursor_cursor_push_varint uint64_t
if (!cursor_push_varint(cur, invoice->msat->millisatoshis))
return 0;
if (!cursor_push_varint(cur, invoice->timestamp))
return 0;
if (!cursor_push_varint(cur, invoice->expiry))
return 0;
if (invoice->description) {
if (!cursor_push_byte(cur, 1))
return 0;
if (!cursor_push_c_str(cur, invoice->description))
return 0;
} else {
if (!cursor_push_byte(cur, 2))
return 0;
if (!cursor_push(cur, invoice->description_hash->u.u8, 32))
return 0;
}
return 1;
}
int ndb_decode_invoice(struct cursor *cur, struct ndb_invoice *invoice)
{
unsigned char desc_type;
if (!cursor_pull_byte(cur, &invoice->version))
return 0;
if (!cursor_pull_varint(cur, &invoice->amount))
return 0;
if (!cursor_pull_varint(cur, &invoice->timestamp))
return 0;
if (!cursor_pull_varint(cur, &invoice->expiry))
return 0;
if (!cursor_pull_byte(cur, &desc_type))
return 0;
if (desc_type == 1) {
if (!cursor_pull_c_str(cur, (const char**)&invoice->description))
return 0;
} else if (desc_type == 2) {
invoice->description_hash = cur->p;
if (!cursor_skip(cur, 32))
return 0;
} else {
return 0;
}
return 1;
}

20
nostrdb/src/invoice.h Normal file
View File

@@ -0,0 +1,20 @@
#ifndef NDB_INVOICE_H
#define NDB_INVOICE_H
struct bolt11;
struct ndb_invoice {
unsigned char version;
uint64_t amount;
uint64_t timestamp;
uint64_t expiry;
char *description;
unsigned char *description_hash;
};
// ENCODING
int ndb_encode_invoice(struct cursor *cur, struct bolt11 *invoice);
int ndb_decode_invoice(struct cursor *cur, struct ndb_invoice *invoice);
#endif /* NDB_INVOICE_H */