Skip to content

Conversation

@codeflash-ai
Copy link

@codeflash-ai codeflash-ai bot commented Nov 13, 2025

📄 14% (0.14x) speedup for NWCServerPlugin.serialize_connection_uri in electrum/plugins/nwc/nwcserver.py

⏱️ Runtime : 387 microseconds 340 microseconds (best of 249 runs)

📝 Explanation and details

The optimized code achieves a 13% speedup through three key optimizations that reduce redundant operations and improve string processing efficiency:

Key Optimizations:

  1. Cached attribute lookups: The optimized version reads self.config.NWC_RELAY and self.config.NOSTR_RELAYS once at the beginning of serialize_connection_uri() and stores them in local variables. This eliminates repeated attribute access within the loop, which the line profiler shows was consuming significant time (48.9% vs 48.4% for the initial query_params creation).

  2. Bounded string splitting: Instead of splitting the entire NOSTR_RELAYS string with .split(","), the optimized version uses .split(",", 5) to limit splits to only 6 parts maximum. This prevents unnecessary processing of very long relay lists since only the first 5 relays are used anyway. The test results show dramatic improvements for large relay lists - up to 108% faster for 1000 relays.

  3. Inline string construction: The final URI is constructed directly with f"{base_uri}?{'&'.join(query_params)}" instead of creating an intermediate query_string variable, eliminating one string allocation and assignment.

Performance Impact by Test Case:

  • Small relay lists: 1-5% improvements from reduced attribute lookups
  • Large relay lists (100-1000 relays): 19-108% improvements from bounded splitting
  • Duplicate relay filtering: Up to 38% faster when many relays are identical to NWC_RELAY

The optimizations are particularly effective for scenarios with many relays (common in production Nostr applications) while maintaining identical behavior and output format. The bounded splitting optimization prevents performance degradation as relay lists grow, making the function scale much better with large configurations.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 74 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Generated Regression Tests and Runtime
import urllib.parse

# imports
import pytest  # used for our unit tests
from electrum.plugins.nwc.nwcserver import NWCServerPlugin


# function to test
class DummyConfig:
    """A minimal config object to simulate SimpleConfig for testing."""
    def __init__(self, nwc_relay=None, nostr_relays=None):
        self.NWC_RELAY = nwc_relay
        self.NOSTR_RELAYS = nostr_relays
from electrum.plugins.nwc.nwcserver import NWCServerPlugin

# unit tests

# ----------- Basic Test Cases -----------

def test_basic_single_relay():
    """Test with a single relay in NOSTR_RELAYS, which is also NWC_RELAY."""
    config = DummyConfig(nwc_relay="wss://relay.example.com", nostr_relays="wss://relay.example.com")
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("abcdef123456", "pubkey123"); uri = codeflash_output # 7.84μs -> 7.52μs (4.27% faster)
    expected = "nostr+walletconnect://pubkey123?relay=wss%3A%2F%2Frelay.example.com&secret=abcdef123456"

def test_basic_multiple_relays():
    """Test with multiple relays, NWC_RELAY is first, others follow in order."""
    config = DummyConfig(
        nwc_relay="wss://relay1.example.com",
        nostr_relays="wss://relay1.example.com,wss://relay2.example.com,wss://relay3.example.com"
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("deadbeef", "pubkey456"); uri = codeflash_output # 11.5μs -> 11.7μs (1.79% slower)
    expected = (
        "nostr+walletconnect://pubkey456?"
        "relay=wss%3A%2F%2Frelay1.example.com"
        "&relay=wss%3A%2F%2Frelay2.example.com"
        "&relay=wss%3A%2F%2Frelay3.example.com"
        "&secret=deadbeef"
    )

def test_basic_relay_url_encoding():
    """Test that relay URLs are properly percent-encoded."""
    config = DummyConfig(
        nwc_relay="wss://relay space.com",
        nostr_relays="wss://relay space.com,wss://relay2.com"
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 9.74μs -> 9.67μs (0.724% faster)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay%20space.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&secret=secret"
    )

# ----------- Edge Test Cases -----------

def test_empty_secret_and_pubkey():
    """Test with empty secret and pubkey."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="wss://relay.com")
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("", ""); uri = codeflash_output # 6.97μs -> 7.04μs (1.04% slower)
    expected = "nostr+walletconnect://?relay=wss%3A%2F%2Frelay.com&secret="

def test_empty_nostr_relays():
    """Test with empty NOSTR_RELAYS string."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="")
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("s", "pk"); uri = codeflash_output # 7.42μs -> 7.63μs (2.74% slower)
    # Only NWC_RELAY is present
    expected = "nostr+walletconnect://pk?relay=wss%3A%2F%2Frelay.com&secret=s"

def test_nwc_relay_not_in_nostr_relays():
    """NWC_RELAY is not present in NOSTR_RELAYS, should still come first."""
    config = DummyConfig(
        nwc_relay="wss://special.com",
        nostr_relays="wss://relay1.com,wss://relay2.com"
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 11.1μs -> 11.2μs (0.874% slower)
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Fspecial.com"
        "&relay=wss%3A%2F%2Frelay1.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&secret=sec"
    )

def test_duplicate_relays():
    """Test with duplicate relay URLs in NOSTR_RELAYS."""
    config = DummyConfig(
        nwc_relay="wss://relay.com",
        nostr_relays="wss://relay.com,wss://relay.com,wss://relay2.com"
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 9.74μs -> 9.29μs (4.93% faster)
    # Only one relay.com should be first, the second should be skipped
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Frelay.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&secret=sec"
    )

def test_maximum_five_relays():
    """Test that only up to 5 relays are included."""
    relays = ",".join([f"wss://relay{i}.com" for i in range(1, 10)])
    config = DummyConfig(
        nwc_relay="wss://relay1.com",
        nostr_relays=relays
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 13.4μs -> 12.8μs (3.98% faster)
    # Only first 5 relays (including NWC_RELAY) should be present
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Frelay1.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&relay=wss%3A%2F%2Frelay3.com"
        "&relay=wss%3A%2F%2Frelay4.com"
        "&relay=wss%3A%2F%2Frelay5.com"
        "&secret=sec"
    )

def test_nwc_relay_with_special_chars():
    """Test NWC_RELAY with special characters needing percent-encoding."""
    config = DummyConfig(
        nwc_relay="wss://relay.com/?foo=bar&baz=qux",
        nostr_relays="wss://relay.com/?foo=bar&baz=qux"
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 8.15μs -> 7.87μs (3.62% faster)
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Frelay.com%2F%3Ffoo%3Dbar%26baz%3Dqux"
        "&secret=sec"
    )

def test_secret_with_special_chars():
    """Test secret containing special characters."""
    config = DummyConfig(
        nwc_relay="wss://relay.com",
        nostr_relays="wss://relay.com"
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    secret = "abc/def?ghi&jkl=123"
    codeflash_output = plugin.serialize_connection_uri(secret, "pk"); uri = codeflash_output # 7.36μs -> 7.18μs (2.44% faster)
    # Secret is not encoded, should appear as-is
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Frelay.com"
        "&secret=abc/def?ghi&jkl=123"
    )

def test_pubkey_with_special_chars():
    """Test pubkey containing special characters."""
    config = DummyConfig(
        nwc_relay="wss://relay.com",
        nostr_relays="wss://relay.com"
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    pubkey = "pk:with:special/chars"
    codeflash_output = plugin.serialize_connection_uri("sec", pubkey); uri = codeflash_output # 7.26μs -> 7.29μs (0.343% slower)
    expected = (
        "nostr+walletconnect://pk:with:special/chars?"
        "relay=wss%3A%2F%2Frelay.com"
        "&secret=sec"
    )

# ----------- Large Scale Test Cases -----------

def test_large_number_of_relays():
    """Test with a large number of relays to ensure only first 5 are used and performance is acceptable."""
    relays = ",".join([f"wss://relay{i}.com" for i in range(1, 1001)])
    config = DummyConfig(
        nwc_relay="wss://relay1.com",
        nostr_relays=relays
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("bigsecret", "bigpubkey"); uri = codeflash_output # 30.4μs -> 14.6μs (108% faster)
    # Only first 5 relays (including NWC_RELAY) should be present
    expected = (
        "nostr+walletconnect://bigpubkey?"
        "relay=wss%3A%2F%2Frelay1.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&relay=wss%3A%2F%2Frelay3.com"
        "&relay=wss%3A%2F%2Frelay4.com"
        "&relay=wss%3A%2F%2Frelay5.com"
        "&secret=bigsecret"
    )

def test_large_secret_and_pubkey():
    """Test with very large secret and pubkey strings."""
    config = DummyConfig(
        nwc_relay="wss://relay.com",
        nostr_relays="wss://relay.com"
    )
    large_secret = "a" * 512  # 512 chars
    large_pubkey = "b" * 256  # 256 chars
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri(large_secret, large_pubkey); uri = codeflash_output # 7.52μs -> 7.24μs (3.88% faster)
    expected = (
        f"nostr+walletconnect://{large_pubkey}?"
        "relay=wss%3A%2F%2Frelay.com"
        f"&secret={large_secret}"
    )

def test_large_unique_relays():
    """Test with 1000 unique relay URLs, only first 5 should be used."""
    relays = ",".join([f"wss://relay{i}.example.com" for i in range(1, 1001)])
    config = DummyConfig(
        nwc_relay="wss://relay1.example.com",
        nostr_relays=relays
    )
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 33.1μs -> 16.1μs (105% faster)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay1.example.com"
        "&relay=wss%3A%2F%2Frelay2.example.com"
        "&relay=wss%3A%2F%2Frelay3.example.com"
        "&relay=wss%3A%2F%2Frelay4.example.com"
        "&relay=wss%3A%2F%2Frelay5.example.com"
        "&secret=secret"
    )

# ----------- Additional Edge Cases -----------

def test_nwc_relay_is_empty_string():
    """Test with NWC_RELAY as an empty string."""
    config = DummyConfig(nwc_relay="", nostr_relays="wss://relay.com")
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 6.96μs -> 7.11μs (2.21% slower)
    expected = (
        "nostr+walletconnect://pk?"
        "relay="
        "&relay=wss%3A%2F%2Frelay.com"
        "&secret=sec"
    )

def test_nostr_relays_with_empty_entries():
    """Test with empty entries in NOSTR_RELAYS."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="wss://relay.com,,wss://relay2.com")
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 9.81μs -> 9.76μs (0.512% faster)
    # Empty relay should be skipped, only relay2.com included after relay.com
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Frelay.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&secret=sec"
    )

def test_nostr_relays_with_trailing_comma():
    """Test with NOSTR_RELAYS having a trailing comma."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="wss://relay.com,")
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 7.63μs -> 7.64μs (0.079% slower)
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Frelay.com"
        "&secret=sec"
    )

def test_nostr_relays_with_leading_comma():
    """Test with NOSTR_RELAYS having a leading comma."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays=",wss://relay.com")
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 7.86μs -> 7.83μs (0.332% faster)
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Frelay.com"
        "&secret=sec"
    )

def test_nostr_relays_all_empty():
    """Test with NOSTR_RELAYS as all empty entries."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays=",,,")
    plugin = NWCServerPlugin(None, config, "nwc")
    codeflash_output = plugin.serialize_connection_uri("sec", "pk"); uri = codeflash_output # 8.45μs -> 8.47μs (0.260% slower)
    expected = (
        "nostr+walletconnect://pk?"
        "relay=wss%3A%2F%2Frelay.com"
        "&secret=sec"
    )
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
import urllib.parse

# imports
import pytest
from electrum.plugins.nwc.nwcserver import NWCServerPlugin


# function to test
class DummyConfig:
    """A minimal config class to simulate the required attributes."""
    def __init__(self, nwc_relay=None, nostr_relays=None):
        self.NWC_RELAY = nwc_relay
        self.NOSTR_RELAYS = nostr_relays
from electrum.plugins.nwc.nwcserver import NWCServerPlugin

# unit tests

# ---------------- Basic Test Cases ----------------

def test_basic_single_relay():
    """Basic: Single relay, normal pubkey and secret."""
    config = DummyConfig(nwc_relay="wss://relay.example.com", nostr_relays="wss://relay.example.com")
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("abcdef123456", "0123456789abcdef"); uri = codeflash_output # 7.73μs -> 7.44μs (3.88% faster)
    expected = (
        "nostr+walletconnect://0123456789abcdef?"
        "relay=wss%3A%2F%2Frelay.example.com&secret=abcdef123456"
    )

def test_basic_multiple_relays():
    """Basic: Multiple relays, NWC_RELAY appears first, others follow."""
    config = DummyConfig(
        nwc_relay="wss://relay1.example.com",
        nostr_relays="wss://relay1.example.com,wss://relay2.example.com,wss://relay3.example.com"
    )
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("deadbeef", "pubkeyhex"); uri = codeflash_output # 11.6μs -> 11.6μs (0.466% faster)
    expected = (
        "nostr+walletconnect://pubkeyhex?"
        "relay=wss%3A%2F%2Frelay1.example.com"
        "&relay=wss%3A%2F%2Frelay2.example.com"
        "&relay=wss%3A%2F%2Frelay3.example.com"
        "&secret=deadbeef"
    )

def test_basic_secret_and_pubkey_special_chars():
    """Basic: Secret and pubkey with special characters (should not be encoded)."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="wss://relay.com")
    plugin = NWCServerPlugin(None, config, "test")
    secret = "abc$%def"
    pubkey = "pub:key@123"
    codeflash_output = plugin.serialize_connection_uri(secret, pubkey); uri = codeflash_output # 6.85μs -> 7.18μs (4.50% slower)
    expected = (
        "nostr+walletconnect://pub:key@123?"
        "relay=wss%3A%2F%2Frelay.com&secret=abc$%def"
    )

# ---------------- Edge Test Cases ----------------

def test_edge_empty_secret():
    """Edge: Empty secret string."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="wss://relay.com")
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("", "pubkey"); uri = codeflash_output # 7.14μs -> 6.91μs (3.37% faster)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay.com&secret="
    )

def test_edge_empty_pubkey():
    """Edge: Empty pubkey string."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="wss://relay.com")
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", ""); uri = codeflash_output # 7.34μs -> 7.23μs (1.54% faster)
    expected = (
        "nostr+walletconnect://?"
        "relay=wss%3A%2F%2Frelay.com&secret=secret"
    )

def test_edge_empty_relays():
    """Edge: Empty relay list (NWC_RELAY is empty, NOSTR_RELAYS is empty)."""
    config = DummyConfig(nwc_relay="", nostr_relays="")
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 2.96μs -> 3.19μs (6.97% slower)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=&secret=secret"
    )

def test_edge_nwc_relay_not_in_nostr_relays():
    """Edge: NWC_RELAY not present in NOSTR_RELAYS."""
    config = DummyConfig(
        nwc_relay="wss://special.com",
        nostr_relays="wss://relay1.com,wss://relay2.com"
    )
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 11.3μs -> 11.2μs (0.937% faster)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Fspecial.com"
        "&relay=wss%3A%2F%2Frelay1.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&secret=secret"
    )

def test_edge_duplicate_relays():
    """Edge: Duplicate relays in NOSTR_RELAYS, NWC_RELAY is one of them."""
    config = DummyConfig(
        nwc_relay="wss://relay.com",
        nostr_relays="wss://relay.com,wss://relay.com,wss://relay.com"
    )
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 7.22μs -> 7.45μs (2.97% slower)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay.com&secret=secret"
    )

def test_edge_special_characters_in_relay():
    """Edge: Relays with special characters should be URL-encoded."""
    config = DummyConfig(
        nwc_relay="wss://relay.com/path?foo=bar",
        nostr_relays="wss://relay.com/path?foo=bar,wss://other.com/#frag"
    )
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 10.2μs -> 10.5μs (2.47% slower)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay.com%2Fpath%3Ffoo%3Dbar"
        "&relay=wss%3A%2F%2Fother.com%2F%23frag"
        "&secret=secret"
    )

def test_edge_nostr_relays_more_than_five():
    """Edge: NOSTR_RELAYS has more than 5 relays, only first 5 used."""
    relays = ",".join([f"wss://relay{i}.com" for i in range(1, 8)])
    config = DummyConfig(nwc_relay="wss://relay1.com", nostr_relays=relays)
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 13.1μs -> 12.9μs (1.50% faster)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay1.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&relay=wss%3A%2F%2Frelay3.com"
        "&relay=wss%3A%2F%2Frelay4.com"
        "&relay=wss%3A%2F%2Frelay5.com"
        "&secret=secret"
    )

def test_edge_nwc_relay_is_none():
    """Edge: NWC_RELAY is None (should be treated as string 'None')."""
    config = DummyConfig(nwc_relay=None, nostr_relays="wss://relay.com")
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 7.13μs -> 6.97μs (2.19% faster)
    # urllib.parse.quote(None) raises TypeError, but the code as written will pass None to f-string, which becomes 'None'
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=None&secret=secret"
    )

def test_edge_nostr_relays_is_none():
    """Edge: NOSTR_RELAYS is None (should raise AttributeError on split)."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays=None)
    plugin = NWCServerPlugin(None, config, "test")
    with pytest.raises(AttributeError):
        plugin.serialize_connection_uri("secret", "pubkey") # 6.77μs -> 1.79μs (279% faster)

def test_edge_nostr_relays_is_empty_string():
    """Edge: NOSTR_RELAYS is empty string, should only include NWC_RELAY."""
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="")
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 7.68μs -> 8.07μs (4.82% slower)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay.com&secret=secret"
    )

# ---------------- Large Scale Test Cases ----------------

def test_large_scale_many_relays():
    """Large Scale: 100 relays, only first 5 used, NWC_RELAY is first."""
    relays = ",".join([f"wss://relay{i}.com" for i in range(1, 101)])
    config = DummyConfig(nwc_relay="wss://relay1.com", nostr_relays=relays)
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 15.9μs -> 13.4μs (19.2% faster)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay1.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&relay=wss%3A%2F%2Frelay3.com"
        "&relay=wss%3A%2F%2Frelay4.com"
        "&relay=wss%3A%2F%2Frelay5.com"
        "&secret=secret"
    )

def test_large_scale_long_secret_and_pubkey():
    """Large Scale: Very long secret and pubkey strings."""
    long_secret = "a" * 512
    long_pubkey = "b" * 256
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays="wss://relay.com")
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri(long_secret, long_pubkey); uri = codeflash_output # 7.61μs -> 7.57μs (0.475% faster)
    expected = (
        f"nostr+walletconnect://{long_pubkey}?"
        f"relay=wss%3A%2F%2Frelay.com&secret={long_secret}"
    )

def test_large_scale_all_relays_are_nwc_relay():
    """Large Scale: All relays are identical to NWC_RELAY, only one relay appears."""
    relays = ",".join(["wss://relay.com"] * 100)
    config = DummyConfig(nwc_relay="wss://relay.com", nostr_relays=relays)
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 10.9μs -> 7.93μs (38.0% faster)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay.com&secret=secret"
    )

def test_large_scale_different_nwc_relay():
    """Large Scale: NWC_RELAY is not in NOSTR_RELAYS, 100 relays, only first 5 used."""
    relays = ",".join([f"wss://relay{i}.com" for i in range(1, 101)])
    config = DummyConfig(nwc_relay="wss://special.com", nostr_relays=relays)
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 17.6μs -> 15.1μs (17.0% faster)
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Fspecial.com"
        "&relay=wss%3A%2F%2Frelay1.com"
        "&relay=wss%3A%2F%2Frelay2.com"
        "&relay=wss%3A%2F%2Frelay3.com"
        "&relay=wss%3A%2F%2Frelay4.com"
        "&relay=wss%3A%2F%2Frelay5.com"
        "&secret=secret"
    )

def test_large_scale_special_chars_in_many_relays():
    """Large Scale: 10 relays with special characters, check encoding."""
    relays = ",".join([
        "wss://relay.com/path?foo=bar",
        "wss://other.com/#frag",
        "wss://ex.com:1234",
        "wss://ex.com?x=1&y=2",
        "wss://ex.com/space here",
        "wss://ex.com/üñîçødë",
        "wss://ex.com/%25percent",
        "wss://ex.com/;semicolon",
        "wss://ex.com/@at",
        "wss://ex.com/!bang"
    ])
    config = DummyConfig(nwc_relay="wss://relay.com/path?foo=bar", nostr_relays=relays)
    plugin = NWCServerPlugin(None, config, "test")
    codeflash_output = plugin.serialize_connection_uri("secret", "pubkey"); uri = codeflash_output # 15.4μs -> 15.7μs (2.17% slower)
    # Only first 5 relays, with NWC_RELAY first, rest in order, skip duplicates
    expected = (
        "nostr+walletconnect://pubkey?"
        "relay=wss%3A%2F%2Frelay.com%2Fpath%3Ffoo%3Dbar"
        "&relay=wss%3A%2F%2Fother.com%2F%23frag"
        "&relay=wss%3A%2F%2Fex.com%3A1234"
        "&relay=wss%3A%2F%2Fex.com%3Fx%3D1%26y%3D2"
        "&relay=wss%3A%2F%2Fex.com%2Fspace%20here"
        "&secret=secret"
    )
# codeflash_output is used to check that the output of the original code is the same as that of the optimized code.
from electrum.plugins.nwc.nwcserver import NWCServerPlugin

To edit these changes git checkout codeflash/optimize-NWCServerPlugin.serialize_connection_uri-mhx6nm99 and push.

Codeflash Static Badge

The optimized code achieves a **13% speedup** through three key optimizations that reduce redundant operations and improve string processing efficiency:

**Key Optimizations:**

1. **Cached attribute lookups**: The optimized version reads `self.config.NWC_RELAY` and `self.config.NOSTR_RELAYS` once at the beginning of `serialize_connection_uri()` and stores them in local variables. This eliminates repeated attribute access within the loop, which the line profiler shows was consuming significant time (48.9% vs 48.4% for the initial query_params creation).

2. **Bounded string splitting**: Instead of splitting the entire `NOSTR_RELAYS` string with `.split(",")`, the optimized version uses `.split(",", 5)` to limit splits to only 6 parts maximum. This prevents unnecessary processing of very long relay lists since only the first 5 relays are used anyway. The test results show dramatic improvements for large relay lists - up to **108% faster** for 1000 relays.

3. **Inline string construction**: The final URI is constructed directly with `f"{base_uri}?{'&'.join(query_params)}"` instead of creating an intermediate `query_string` variable, eliminating one string allocation and assignment.

**Performance Impact by Test Case:**
- **Small relay lists**: 1-5% improvements from reduced attribute lookups
- **Large relay lists (100-1000 relays)**: 19-108% improvements from bounded splitting
- **Duplicate relay filtering**: Up to 38% faster when many relays are identical to NWC_RELAY

The optimizations are particularly effective for scenarios with many relays (common in production Nostr applications) while maintaining identical behavior and output format. The bounded splitting optimization prevents performance degradation as relay lists grow, making the function scale much better with large configurations.
@codeflash-ai codeflash-ai bot requested a review from mashraf-222 November 13, 2025 08:44
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Nov 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant