Skip to content

FIX: Ensure valid json#39

Merged
motorina0 merged 3 commits intolnbits:mainfrom
PatMulligan:ensure-valid-event-json
Sep 15, 2025
Merged

FIX: Ensure valid json#39
motorina0 merged 3 commits intolnbits:mainfrom
PatMulligan:ensure-valid-event-json

Conversation

@PatMulligan
Copy link
Copy Markdown
Contributor

Fix: construct EVENT message with json.dumps instead of string interpolation

Why

The old implementation built JSON-like strings by interpolation. This works for simple inputs, but as soon as values contain quotes, backslashes, or Unicode characters, the result is not valid JSON and will be rejected by relays.

Change

- event_to_forward = f"""["EVENT", "{s_original}", {event_json}]"""
+ event_to_forward = json.dumps(["EVENT", s_original, json.loads(event_json)])

Example of the problem

Inputs

import json

s_original = 'sub"one'
event_json = '{"content": "hello \\"nostr\\"", "tags": []}'

Old code

event_to_forward = f"""["EVENT", "{s_original}", {event_json}]"""
print(event_to_forward)
# ["EVENT", "sub"one", {"content": "hello \"nostr\"", "tags": []}]
json.loads(event_to_forward)
# raises json.decoder.JSONDecodeError

The string looks like JSON but cannot be parsed.

New code

event_to_forward = json.dumps(["EVENT", s_original, json.loads(event_json)])
print(event_to_forward)
# ["EVENT", "sub\"one", {"content": "hello \"nostr\"", "tags": []}]
json.loads(event_to_forward)  # ✅ works

Benefits

  • Always produces valid JSON.
  • Correctly escapes special characters in subscription IDs and event data.
  • Removes risk of malformed payloads and relay rejections.
  • Easier to maintain and extend (all inputs handled as objects, not string fragments).

Ensures outbound Nostr messages are valid JSON and safely escaped by
constructing the payload as Python objects and serializing with
json.dumps
@PatMulligan PatMulligan force-pushed the ensure-valid-event-json branch from 176aa98 to eb05d39 Compare September 10, 2025 12:49
@motorina0 motorina0 merged commit e66f997 into lnbits:main Sep 15, 2025
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants