Skip to main content
21.6k
Two Booleans and 739 Lines: How py-libp2p Made TLS Work Across Languages

Two Booleans and 739 Lines: How py-libp2p Made TLS Work Across Languages

py-libp2p TLS security interoperability
by Yash Kumar Saini 10 min read

It took 739 lines of code to prove that py-libp2p's TLS encryption worked. Bidirectional chat, echo testing, ping latency measurement — three modes of secure communication, all running over TLS 1.3. Then it took exactly two lines to prove it worked with everyone else. The irony was perfect: Python's certificate generation was following the X.509 standard. Rust's rejection of those certificates was also following the X.509 standard. Both implementations were correct — just correct about different things. Python marked BasicConstraints and KeyUsage as critical extensions. Rust's TLS stack, encountering critical extensions it didn't recognize in the context of libp2p's self-signed certificates, did exactly what the spec demands: abort the connection. The result was a silent wall between two implementations of the same protocol. PR #1144 built the examples that proved TLS worked within Python. PR #1160 changed two booleans that made it work across languages. This is the story of both.

Background: How libp2p Does TLS

libp2p uses TLS 1.3 with a distinctive twist. Instead of relying on Certificate Authorities, each peer generates a self-signed X.509 certificate that embeds its libp2p public key in a custom extension (OID 1.3.6.1.4.1.53594.1.1). During the handshake, each side creates an ephemeral key pair for the TLS session, then wraps its long-term host key into the certificate extension along with a signature proving ownership. The receiving peer extracts the host key, derives the peer ID, and verifies it matches the expected identity.

This approach lets libp2p use key types like secp256k1 — common in crypto and P2P networks but not natively supported by standard TLS stacks — while still getting TLS 1.3's encryption and forward secrecy.

X.509 certificates carry extensions — additional metadata fields that can be marked as "critical" or "non-critical." Per RFC 5280, if an implementation encounters a critical extension it doesn't understand, it must reject the certificate. Non-critical extensions it doesn't understand can be safely ignored. This distinction is the fulcrum on which the interoperability story pivots.

py-libp2p had a working TLS implementation but lacked two things: examples showing developers how to use it, and proof that it worked with other libp2p implementations.

The Problem: No Examples and a Hidden Incompatibility

Two gaps existed, and they were related more closely than anyone initially realized.

The examples gap. Issue #555 had been open since the early days of py-libp2p, tracking interest in TLS (and eventually AutoTLS) support. The TLS security transport was eventually implemented, but no examples existed to show developers how to create a TLS-enabled host, set up encrypted communication, or test connectivity. The existing examples — ping, chat, identify, pub-sub — all used Noise or plaintext for security. A developer wanting to use TLS had to read the source code and piece together the setup themselves.

The interoperability gap. Hidden behind the lack of examples was a more fundamental problem. py-libp2p's certificate generation marked two standard X.509 extensions — BasicConstraints and KeyUsage — as critical=True. For Python-to-Python connections, this was invisible. Both sides used the same certificate library, understood the same extensions, and connected without issue.

But libp2p is a multi-language protocol. The test-plans repository runs interoperability tests across Go, Rust, JavaScript, Nim, and Python implementations. When Python tried to connect to Rust nodes, the handshake failed silently. Rust's TLS stack (rustls, built on webpki) encountered critical extensions it didn't recognize in libp2p's self-signed context and did exactly what RFC 5280 requires: reject the certificate.

TLS certificates generated by Python libp2p set the BasicConstraints and KeyUsage X.509 extensions as critical=True. Rust libp2p does not recognize these extensions, so it aborts the TLS handshake per spec. — Issue #1159

Tls handshake failure

Before PR #1160, Python's TLS certificates marked BasicConstraints and KeyUsage as critical. Rust's TLS stack rejected them per spec, aborting the handshake.

Investigation: From Working Demo to Broken Interop

The path to discovery followed a natural progression: build it, show it works, then test it against the world.

I created PR #1144 to fill the examples gap. Rather than minimal stubs, it delivered production-quality TLS chat examples with three communication modes: echo (send-and-receive), interactive chat (full-duplex bidirectional), and ping (latency measurement). These examples proved that py-libp2p's TLS implementation worked correctly for same-language connections.

The interoperability failure surfaced when py-libp2p entered the test-plans framework — libp2p's cross-language testing infrastructure that verifies different implementations can communicate. PR #798 in test-plans added Python TLS support. The initial test code included a telling workaround: a 40-line custom certificate template that manually constructed extensions with critical=False:

# Custom cert template with critical=False for interop compatibility
custom_template = (
    x509.CertificateBuilder()
    .serial_number(serial)
    .not_valid_before(not_before)
    .not_valid_after(not_after)
    .subject_name(subject_name)
    .issuer_name(issuer_name)
    .add_extension(
        x509.BasicConstraints(ca=False, path_length=None),
        critical=False,  # Must be False for Rust interop
    )
    .add_extension(
        x509.KeyUsage(
            digital_signature=True,
            # ... all other flags False
        ),
        critical=False,  # Must be False for Rust interop
    )
)

That workaround was the smoking gun. If the interop test needed to override the default certificate template just to make Rust connections work, the default template itself was the bug.

The Approach: Build It Right, Then Fix the Root

Two design decisions shaped these PRs.

For the examples: The choice was between minimal stubs that showed TLS setup and production-quality demos that exercised the full communication lifecycle. I chose production quality. Three modes meant three different interaction patterns: simple request-response (echo), concurrent bidirectional streams (chat), and protocol-level latency testing (ping). Each mode tested different aspects of the TLS implementation under real conditions.

For the interop fix: The choice was between patching each consumer that needed Rust compatibility (the workaround approach) and fixing the default certificate template at the source. Fixing the source was clearly better — it meant every TLSTransport instance would generate spec-compliant certificates by default, and consumers wouldn't need to know about the distinction.

The Solution: Examples and a Two-Boolean Fix

PR #1144 — TLS Examples

The examples introduced a complete TLS communication toolkit built on trio's nursery pattern for structured concurrency.

The server registers handlers for two protocols — the bidirectional chat protocol and the standard libp2p ping protocol:

host.set_stream_handler(PROTOCOL_ID, _bidirectional_chat_handler)
host.set_stream_handler(PING_PROTOCOL_ID, handle_ping)

The client's ping mode measures round-trip time over the encrypted connection:

async def ping_mode(host, server_maddr: str, count: int) -> None:
    stream = await host.new_stream(info.peer_id, [PING_PROTOCOL_ID])
    rtts = []
    for i in range(count):
        ping_bytes = secrets.token_bytes(PING_LENGTH)
        before = time.time()
        await stream.write(ping_bytes)
        pong_bytes = await stream.read(PING_LENGTH)
        rtt_ms = (time.time() - before) * 1000
        rtts.append(rtt_ms)
        if ping_bytes != pong_bytes:
            print(f"Ping #{i + 1}: ERROR - Invalid response")
        else:
            print(f"Ping #{i + 1}: {rtt_ms:.2f} ms")

The chat mode uses trio's nursery to run send and receive concurrently — true full-duplex communication:

async with trio.open_nursery() as nursery:
    nursery.start_soon(receive_messages)
    nursery.start_soon(send_messages)

The three example modes — echo (single message), chat (full-duplex nursery), and ping (RTT measurement) — all flow through the shared TLS transport layer to the server.

PR #1144's TLS client supports three modes — echo for basic testing, chat for full-duplex bidirectional messaging, and ping for latency measurement — all over TLS 1.3 encryption.

PR #1160 — The Two-Boolean Fix

The core change in certificate.py:

 # Add Basic Constraints extension - not a CA
 builder = builder.add_extension(
-    x509.BasicConstraints(ca=False, path_length=None), critical=True
+    x509.BasicConstraints(ca=False, path_length=None), critical=False
 )

 # Add Key Usage - digital signature only
 builder = builder.add_extension(
     x509.KeyUsage(
         digital_signature=True,
         # ... all other flags False
     ),
-    critical=True,
+    critical=False,
 )

Two booleans. Four characters of meaningful change. And with that, the 40-line workaround in the interop test was deleted:

Tls handshake success

After PR #1160, the same extensions are marked non-critical. Rust ignores them per spec, processes the libp2p extension, and the handshake succeeds.

Under the Hood: Why Two Booleans Matter

Why critical=True was wrong for libp2p certificates. In a traditional PKI, BasicConstraints and KeyUsage being critical makes sense — they control whether a certificate can sign other certificates and what operations it's authorized for. A relying party must understand these to make trust decisions. But libp2p certificates are self-signed and ephemeral. No CA hierarchy exists. The identity proof lives entirely in the custom libp2p extension. BasicConstraints(ca=False) is informational — it tells the other side "this isn't a CA certificate" — but in a system with no CAs, that information is redundant. Marking it non-critical lets implementations that don't track these extensions simply skip them.

The interop test cleanup. Before the fix, ping_test.py in the test-plans repository contained a 40-line custom certificate template that replicated the entire certificate generation logic just to set critical=False. After the fix, the entire block was replaced with:

# Use default certificate template (now has critical=False for Rust interop)
tls_transport = TLSTransport(
    libp2p_keypair=key_pair,
    early_data=None,
    muxers=None,
)

That's 40 lines of workaround code deleted, replaced by the default behavior doing the right thing.

Interop workaround cleanup

Before the fix, the interop test needed a 40-line custom certificate template as a workaround. After fixing the default template, the workaround was deleted entirely.

Before and After

CapabilityBeforeAfter
TLS examplesNone — developers read source code3 modes: echo, chat, ping
Rust interoperabilityBroken — handshake failureWorking — spec-compliant certificates
Interop test code40-line custom cert template workaroundDefault TLSTransport, no workaround
Certificate compliancecritical=True (technically valid but incompatible)critical=False (spec-aligned for libp2p context)
Regression protectionNoneDedicated test enforcing non-critical flags

These two PRs transformed py-libp2p's TLS story from "implemented but undocumented and incompatible" to "demonstrated, tested, and interoperable."

Testing and Validation

PR #1144 validated its examples through direct execution — the client and server run as standalone scripts that demonstrate TLS communication in real time. @acul71 added ping mode support and verified it worked during review.

PR #1160 added a dedicated regression test:

def test_certificate_extensions_are_noncritical():
    """Verify BasicConstraints and KeyUsage are non-critical for Rust interop."""
    keypair = create_secp256k1()
    tmpl = certmod.create_cert_template()
    cert_pem, _ = certmod.generate_certificate(keypair.private_key, tmpl)
    cert = x509.load_pem_x509_certificate(cert_pem.encode())

    for ext in cert.extensions:
        if isinstance(ext.value, x509.BasicConstraints):
            assert ext.critical is False, (
                "BasicConstraints must be non-critical for Rust interop"
            )
        elif isinstance(ext.value, x509.KeyUsage):
            assert ext.critical is False, (
                "KeyUsage must be non-critical for Rust interop"
            )

This test ensures the flags can never silently revert to critical=True — a change that would be invisible in Python-only testing but would break cross-language interop.

Security Impact

Changing critical=True to critical=False does not weaken security. In libp2p's TLS model, the meaningful security properties come from:

  1. TLS 1.3 encryption — unchanged, still provides confidentiality and forward secrecy
  2. The libp2p extension — carries the host key and signature, enabling peer ID verification; this extension remains properly handled by all implementations
  3. Certificate validity — NotBefore/NotAfter constraints are still enforced

BasicConstraints(ca=False) says "this is not a CA certificate." In a system with no CA hierarchy, this is purely informational. KeyUsage(digital_signature=True) says "this key is used for signatures." Both are true and useful metadata, but neither is security-critical in the self-signed, ephemeral certificate context that libp2p uses. Marking them non-critical means implementations that don't process them can skip them safely — exactly the behavior the libp2p TLS spec intends.

Lessons Learned

1. Examples are integration tests in disguise. Building real TLS examples forced the code through the full lifecycle: key generation, transport setup, connection establishment, stream management, and graceful teardown. This kind of end-to-end exercise catches problems that unit tests miss. If I had built TLS examples earlier, the interop issue might have surfaced sooner.

2. Spec-compliant can still be broken. Both Python and Rust were following the X.509 specification correctly. Python marked extensions as critical — which RFC 5280 allows. Rust rejected unknown critical extensions — which RFC 5280 requires. The bug wasn't in either implementation's spec compliance. It was in the mismatch between what one side expected and what the other required. Cross-implementation testing is the only way to find these gaps.

3. Small fixes, large blast radius. Two booleans changed four characters of code. The impact: working Python-to-Rust TLS connections, 40 lines of workaround code deleted from the interop tests, and a new regression test added. The ratio of impact to code changed is a reminder that bug severity and fix complexity are independent variables.

4. Fix the source, not the consumer. The initial approach was a workaround — building a custom certificate template in the interop test. The correct fix was changing the default template in certificate.py so every TLSTransport instance generates compatible certificates without consumers needing to know about the distinction.

What's Next

Issue #555's original request — AutoTLS support — remains the next milestone on py-libp2p's TLS roadmap. With working examples, spec-compliant certificates, and cross-language interop established, the foundation is solid. The test-plans framework now validates Python-to-Rust connections, and future transport additions (WebSocket over TLS, QUIC) can build on the same certificate infrastructure without worrying about extension compatibility.

Conclusion

The arc of these two PRs tells a compact story about software maturity. PR #1144 built 739 lines of TLS examples — a bidirectional chat with echo, chat, and ping modes — proving that py-libp2p's encryption worked. PR #1160 changed two booleans — critical=True to critical=False — proving it worked with everyone else. The first PR was about making the feature real. The second was about making it interoperable. Together, they took py-libp2p's TLS from "implemented but isolated" to "demonstrated, tested, and talking to Rust."

Acknowledgements

Resources

  1. PR #1144 — TLS Bidirectional Chat Examples
  2. PR #1160 — TLS Extensions Non-Critical Fix
  3. Issue #555 — AutoTLS Support
  4. Issue #1159 — Rust Interop Certificate Bug
  5. libp2p TLS Specification
  6. RFC 5280 — X.509 Certificate Profile
  7. libp2p test-plans Repository
  8. py-libp2p TLS Documentation

Related on libp2p.io: TLS, What are Secure Channels, Testing all the libp2ps.

If you would like to contribute, please connect with the libp2p maintainers.