Skip to content

Commit

Permalink
code cleanup and improved error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
riccardobl committed Jul 8, 2024
1 parent 57ed63d commit 79ca3c1
Show file tree
Hide file tree
Showing 15 changed files with 176 additions and 240 deletions.
50 changes: 27 additions & 23 deletions examples/ESP32TestNWC/ESP32TestNWC.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -55,29 +55,33 @@ void loop() {
}

void testNWC() {
transport = nostr::esp32::ESP32Platform::getTransport();
nwc = new nostr::NWC(transport, NWC_URL);
try{
transport = nostr::esp32::ESP32Platform::getTransport();
nwc = new nostr::NWC(transport, NWC_URL);

nwc->getBalance([&](nostr::GetBalanceResponse resp) { Serial.println("[!] Balance: " + String(resp.balance) + " msatoshis"); },
[](String err, String errMsg) { Serial.println("[!] Error: " + err + " " + errMsg); });
nwc->getInfo(
[&](nostr::GetInfoResponse resp) {
Serial.println("[!] Alias: " + resp.alias);
Serial.println("[!] Color: " + resp.color);
Serial.println("[!] Pubkey: " + resp.pubkey);
Serial.println("[!] Network: " + resp.network);
Serial.println("[!] Block height: " + String(resp.blockHeight));
Serial.println("[!] Block hash: " + resp.blockHash);
Serial.println("[!] Methods: ");
for (auto method : resp.methods) {
Serial.println(" " + method);
}
},
[](String err, String errMsg) { Serial.println("[!] Error: " + err + " " + errMsg); });
nwc->getBalance([&](nostr::GetBalanceResponse resp) { Serial.println("[!] Balance: " + String(resp.balance) + " msatoshis"); },
[](String err, String errMsg) { Serial.println("[!] Error: " + err + " " + errMsg); });
nwc->getInfo(
[&](nostr::GetInfoResponse resp) {
Serial.println("[!] Alias: " + resp.alias);
Serial.println("[!] Color: " + resp.color);
Serial.println("[!] Pubkey: " + resp.pubkey);
Serial.println("[!] Network: " + resp.network);
Serial.println("[!] Block height: " + String(resp.blockHeight));
Serial.println("[!] Block hash: " + resp.blockHash);
Serial.println("[!] Methods: ");
for (auto method : resp.methods) {
Serial.println(" " + method);
}
},
[](String err, String errMsg) { Serial.println("[!] Error: " + err + " " + errMsg); });

NostrString invoice = transport->getInvoiceFromLNAddr(PAYOUT_ADDRESS, PAYOUT_AMOUNT_MSAT, "Arduino NWC test");
Serial.println("[!] Paying " + String(PAYOUT_AMOUNT_MSAT) + " msats to " + PAYOUT_ADDRESS + " invoice: " + invoice);
nwc->payInvoice(
invoice, PAYOUT_AMOUNT_MSAT, [&](nostr::PayInvoiceResponse resp) { Serial.println("[!] Payment successful"); },
[](String err, String errMsg) { Serial.println("[!] Error: " + err + " " + errMsg); });
NostrString invoice = transport->getInvoiceFromLNAddr(PAYOUT_ADDRESS, PAYOUT_AMOUNT_MSAT, "Arduino NWC test");
Serial.println("[!] Paying " + String(PAYOUT_AMOUNT_MSAT) + " msats to " + PAYOUT_ADDRESS + " invoice: " + invoice);
nwc->payInvoice(
invoice, PAYOUT_AMOUNT_MSAT, [&](nostr::PayInvoiceResponse resp) { Serial.println("[!] Payment successful"); },
[](String err, String errMsg) { Serial.println("[!] Error: " + err + " " + errMsg); });
} catch (std::exception &e) {
Serial.println("[!] Exception: " + String(e.what()));
}
}
142 changes: 73 additions & 69 deletions examples/ESP32TestNip01/ESP32TestNip01.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,74 +61,78 @@ void loop() {
nostr::Transport *transport;

void testNIP01() {
String relay = RELAY;
String privKey = PRIVKEY;
transport = nostr::esp32::ESP32Platform::getTransport();

// We need a NostrPool instance that will handle all the communication
nostr::NostrPool *pool = new nostr::NostrPool(transport);
pools.push_back(pool); // NB. we are adding it to this vector since we need to call
// pool->loop() in the main loop to make it work properly

// Lets subscribe to the relay
String subId = pool->subscribeMany(
{relay},
{
{// we set the filters here (see
// https://github.com/nostr-protocol/nips/blob/master/01.md#from-client-to-relay-sending-events-and-creating-subscriptions)
{"kinds", {"1"}},
// {"since",{"1234567890"}},
// {"until",{"1234567890"}},
// {"limit",{"10"}},
{"#t", {"arduinoTest"}}} //,
// You can add another filter here
},
[&](const String &subId, nostr::SignedNostrEvent *event) {
// Received events callback, we can access the event content with
// event->getContent() Here you should handle the event, for this
// test we will just serialize it and print to console
JsonDocument doc;
JsonArray arr = doc["data"].to<JsonArray>();
event->toSendableEvent(arr);
String json;
serializeJson(arr, json);

Serial.println("Event received: " + json);
},
[&](const String &subId, const String &reason) {
// This is the callback that will be called when the subscription is
// closed
Serial.println("Subscription closed: " + reason);
},
[&](const String &subId) {
// This is the callback that will be called when the subscription is
// EOSE
Serial.println("Subscription EOSE: " + subId);
});

// NB. you might want to save the subId somewhere since you are going to
// need it to close the subscription like so: pool.closeSubscription(subId);

// The pool will start to listen for events immediately after the next
// loop()

// Lets try to send an event
// First we create an unsigned event
nostr::UnsignedNostrEvent ev(1, "Hello, World!", nostr::Utils::unixTimeSeconds());
// we can add some tags
ev.getTags()->addTag("t", {"arduinoTest"});
// then we sign it with our private key and we will get a SignedNostrEvent
// as result
nostr::SignedNostrEvent signEv = ev.sign(privKey);
// We can verify the event signature (this is not necessary here, but it
// might be when dealing with received events)
if (!signEv.verify()) {
Serial.println("Event signature is invalid");
return;
} else {
Serial.println("Event signature is valid");
try{
String relay = RELAY;
String privKey = PRIVKEY;
transport = nostr::esp32::ESP32Platform::getTransport();

// We need a NostrPool instance that will handle all the communication
nostr::NostrPool *pool = new nostr::NostrPool(transport);
pools.push_back(pool); // NB. we are adding it to this vector since we need to call
// pool->loop() in the main loop to make it work properly

// Lets subscribe to the relay
String subId = pool->subscribeMany(
{relay},
{
{// we set the filters here (see
// https://github.com/nostr-protocol/nips/blob/master/01.md#from-client-to-relay-sending-events-and-creating-subscriptions)
{"kinds", {"1"}},
// {"since",{"1234567890"}},
// {"until",{"1234567890"}},
// {"limit",{"10"}},
{"#t", {"arduinoTest"}}} //,
// You can add another filter here
},
[&](const String &subId, nostr::SignedNostrEvent *event) {
// Received events callback, we can access the event content with
// event->getContent() Here you should handle the event, for this
// test we will just serialize it and print to console
JsonDocument doc;
JsonArray arr = doc["data"].to<JsonArray>();
event->toSendableEvent(arr);
String json;
serializeJson(arr, json);

Serial.println("Event received: " + json);
},
[&](const String &subId, const String &reason) {
// This is the callback that will be called when the subscription is
// closed
Serial.println("Subscription closed: " + reason);
},
[&](const String &subId) {
// This is the callback that will be called when the subscription is
// EOSE
Serial.println("Subscription EOSE: " + subId);
});

// NB. you might want to save the subId somewhere since you are going to
// need it to close the subscription like so: pool.closeSubscription(subId);

// The pool will start to listen for events immediately after the next
// loop()

// Lets try to send an event
// First we create an unsigned event
nostr::UnsignedNostrEvent ev(1, "Hello, World!", nostr::Utils::unixTimeSeconds());
// we can add some tags
ev.getTags()->addTag("t", {"arduinoTest"});
// then we sign it with our private key and we will get a SignedNostrEvent
// as result
nostr::SignedNostrEvent signEv = ev.sign(privKey);
// We can verify the event signature (this is not necessary here, but it
// might be when dealing with received events)
if (!signEv.verify()) {
Serial.println("Event signature is invalid");
return;
} else {
Serial.println("Event signature is valid");
}
// Now we can send the event
pool->publish({relay}, &signEv);
// The event will be sent in the next loop() call
} catch (const std::exception &e) {
Serial.println("Error: " + String(e.what()));
}
// Now we can send the event
pool->publish({relay}, &signEv);
// The event will be sent in the next loop() call
}
26 changes: 6 additions & 20 deletions src/Nip04.cpp
Original file line number Diff line number Diff line change
@@ -1,34 +1,30 @@
#include "Nip04.h"
using namespace nostr;

NostrString Nip04::decrypt(NostrString &privateKeyHex, NostrString &senderPubKeyHex, NostrString content) {

int ivParamIndex = NostrString_indexOf(content, "?iv=");
if (ivParamIndex == -1) throw std::invalid_argument("Encrypted string does not contain ?iv= parameter.");

NostrString encryptedMessage = NostrString_substring(content, 0, ivParamIndex);

NostrString encryptedMessageHex = NostrString_base64ToHex(encryptedMessage);
int encryptedMessageSize = NostrString_length(encryptedMessageHex) / 2;
byte encryptedMessageBin[encryptedMessageSize];
NostrString_hexToBytes(encryptedMessageHex, encryptedMessageBin, encryptedMessageSize);
// fromHex(encryptedMessageHex, encryptedMessageBin,
// encryptedMessageSize);


NostrString iv = NostrString_substring(content, ivParamIndex + 4);
// String iv = content.substring(content.indexOf("?iv=") + 4);
// String ivHex = base64ToHex(iv);
NostrString ivHex = NostrString_base64ToHex(iv);
int ivSize = 16;
byte ivBin[ivSize];
NostrString_hexToBytes(ivHex, ivBin, ivSize);
// fromHex(ivHex, ivBin, ivSize);

int byteSize = 32;
byte privateKeyBytes[byteSize];
// fromHex(privateKeyHex, privateKeyBytes, byteSize);
NostrString_hexToBytes(privateKeyHex, privateKeyBytes, byteSize);
PrivateKey privateKey(privateKeyBytes);

byte senderPublicKeyBin[64];
// fromHex("02" + String(senderPubKeyHex), senderPublicKeyBin, 64);
NostrString_hexToBytes("02" + senderPubKeyHex, senderPublicKeyBin, 64);
PublicKey senderPublicKey(senderPublicKeyBin);

Expand All @@ -41,48 +37,38 @@ NostrString Nip04::decrypt(NostrString &privateKeyHex, NostrString &senderPubKey

return message;
}

NostrString Nip04::encrypt(NostrString &privateKeyHex, NostrString &recipientPubKeyHex, NostrString content) {
// Get shared point
// Create the private key object
int byteSize = 32;
byte privateKeyBytes[byteSize];
// fromHex(privateKeyHex, privateKeyBytes, byteSize);
NostrString_hexToBytes(privateKeyHex, privateKeyBytes, byteSize);
PrivateKey privateKey(privateKeyBytes);

byte publicKeyBin[64];
// fromHex("02" + NostrString(recipientPubKeyHex), publicKeyBin, 64);
NostrString_hexToBytes("02" + NostrString(recipientPubKeyHex), publicKeyBin, 64);
PublicKey otherDhPublicKey(publicKeyBin);

byte sharedPointX[32];
privateKey.ecdh(otherDhPublicKey, sharedPointX, false);
NostrString sharedPointXHex = NostrString_bytesToHex(sharedPointX, 32);

// Create the initialization vector
uint8_t iv[16];
for (int i = 0; i < sizeof(iv); i++) {
iv[i] = (uint8_t)Utils::randomInt(0, 255);
}

NostrString ivHex = toHex(iv, sizeof(iv));

String ivBase64 = hexToBase64(ivHex);

NostrString encryptedMessageHex = encryptData(sharedPointX, iv, content);

// divide the length of the hex string 2 to get the size of the byte
// array, since each byte consists of 2 hexadecimal characters.
int encryptedMessageSize = NostrString_length(encryptedMessageHex) / 2;
uint8_t encryptedMessage[encryptedMessageSize];
// fromHex(encryptedMessageHex, encryptedMessage,
// encryptedMessageSize);
NostrString_hexToBytes(encryptedMessageHex, encryptedMessage, encryptedMessageSize);

String encryptedMessageBase64 = hexToBase64(encryptedMessageHex);

encryptedMessageBase64 += "?iv=" + ivBase64;

return encryptedMessageBase64;
}

Expand Down Expand Up @@ -125,5 +111,5 @@ NostrString Nip04::decryptData(byte key[32], byte iv[16], NostrString messageHex
AES_init_ctx_iv(&ctx, key, iv);
AES_CBC_decrypt_buffer(&ctx, messageBin, sizeof(messageBin));

return NostrString((char *)messageBin).substring(0, byteSize);
return NostrString_substring(NostrString((char *)messageBin),0, byteSize);
}
4 changes: 2 additions & 2 deletions src/Nip04.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,5 @@ class Nip04 {

NostrString decryptData(byte key[32], byte iv[16], NostrString messageHex);
};
} // namespace nostr
#endif // NIP47_H
}
#endif
Loading

0 comments on commit 79ca3c1

Please sign in to comment.