From 51d617e70f90a972185917ea0096c1ecef2bfa8b Mon Sep 17 00:00:00 2001 From: Bitflash-sh Date: Fri, 24 Jul 2026 11:18:11 -0300 Subject: Bitflash: fair-launch release Satoshi's bitcoin-0.1.0 reborn with RandomX CPU proof of work, anonymous .btf addressing over Nostr with CGNAT rendezvous, automatic peer discovery, a headless Linux node, and Windows GUI wallet. Fair launch, no premine, 21M cap. --- src/test_btfaddr.cpp | 142 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 src/test_btfaddr.cpp (limited to 'src/test_btfaddr.cpp') diff --git a/src/test_btfaddr.cpp b/src/test_btfaddr.cpp new file mode 100644 index 0000000..b40dcc1 --- /dev/null +++ b/src/test_btfaddr.cpp @@ -0,0 +1,142 @@ +// Standalone tests for btfaddr (ported from Itzal hidden.rs tests). +// Build (UCRT64): +// g++ -std=gnu++14 -DSECP256K1_STATIC -I../deps/include test_btfaddr.cpp btfaddr.cpp \ +// -L../deps/lib -lsecp256k1 -lssl -lcrypto -o test_btfaddr.exe + +#include "btfaddr.h" +#include +#define SECP256K1_STATIC +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +static int g_fail = 0; +#define CHECK(cond, name) do { \ + if (cond) { printf(" ok %s\n", name); } \ + else { printf(" FAIL %s\n", name); g_fail++; } } while(0) + +static std::string ToUpper(const std::string& s) +{ + std::string r = s; + for (char& c : r) c = (char)toupper((unsigned char)c); + return r; +} + +int main() +{ + secp256k1_context* ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY); + unsigned char seed[32]; RAND_bytes(seed, 32); secp256k1_context_randomize(ctx, seed); + + printf("base32_roundtrips\n"); + { + std::vector> cases; + std::string txt = "hello btf shadow 0123456789"; + cases.push_back(std::vector(txt.begin(), txt.end())); + cases.push_back(std::vector(34, 0x00)); + cases.push_back(std::vector(34, 0xff)); + for (auto& data : cases) + { + std::string enc = btf::Base32Encode(data.data(), data.size()); + std::vector dec; + bool ok = btf::Base32Decode(enc, dec); + // decode may include trailing partial byte handling; compare the meaningful prefix + CHECK(ok && dec.size() >= data.size() && + memcmp(dec.data(), data.data(), data.size()) == 0, "roundtrip"); + } + } + + printf("address_roundtrips_and_is_lowercase_hostname\n"); + { + unsigned char pk[32]; memset(pk, 7, 32); + std::string a = btf::Address(pk); + CHECK(a.size() > 4 && a.compare(a.size()-4, 4, ".btf") == 0, "ends with .btf"); + CHECK(btf::IsBtf(a), "IsBtf true"); + std::string label = a.substr(0, a.size()-4); + bool lc = true; + for (unsigned char c : label) + if (!((c >= 'a' && c <= 'z') || (c >= '2' && c <= '7'))) lc = false; + CHECK(lc, "label is lowercase base32 hostname"); + unsigned char out[32]; + CHECK(btf::ParseAddress(a, out) && memcmp(out, pk, 32) == 0, "parse round-trips"); + CHECK(btf::ParseAddress(ToUpper(a), out) && memcmp(out, pk, 32) == 0, "parse case-insensitive"); + } + + printf("rejects_tampered_address\n"); + { + unsigned char pk[32]; memset(pk, 9, 32); + std::string a = btf::Address(pk); + std::string t = a; + t[0] = (t[0] == 'a') ? 'b' : 'a'; + unsigned char out[32]; + CHECK(!(btf::ParseAddress(t, out) && memcmp(out, pk, 32) == 0), "tampered address rejected"); + } + + printf("rejects_non_btf\n"); + { + unsigned char out[32]; + CHECK(!btf::IsBtf("example.com"), "example.com not btf"); + CHECK(!btf::ParseAddress("example.com", out), "parse example.com fails"); + CHECK(!btf::ParseAddress("not-base-32-!!!.btf", out), "parse invalid base32 fails"); + } + + const std::string ENC_HEX = "aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"; + + // helper: fresh keypair -> (seckey, xonly pubkey) + auto newKey = [&](unsigned char sk[32], unsigned char pk[32]) { + do { RAND_bytes(sk, 32); } while (!secp256k1_ec_seckey_verify(ctx, sk)); + secp256k1_keypair kp; secp256k1_keypair_create(ctx, &kp, sk); + secp256k1_xonly_pubkey xp; secp256k1_keypair_xonly_pub(ctx, &xp, NULL, &kp); + secp256k1_xonly_pubkey_serialize(ctx, pk, &xp); + }; + + printf("descriptor_signs_and_self_certifies\n"); + { + unsigned char sk[32], pk[32]; newKey(sk, pk); + std::string d = btf::SignDescriptor(ctx, sk, ENC_HEX, "meeting-node-abc", 1000); + CHECK(!d.empty(), "sign produced descriptor"); + btf::Descriptor got; + CHECK(btf::VerifyDescriptor(ctx, d, pk, got), "own key verifies"); + CHECK(got.meeting_node == "meeting-node-abc" && got.enc == ENC_HEX && got.created == 1000, "fields match"); + unsigned char sk2[32], pk2[32]; newKey(sk2, pk2); + btf::Descriptor bad; + CHECK(!btf::VerifyDescriptor(ctx, d, pk2, bad), "different key rejected"); + } + + printf("descriptor_rejects_tampering\n"); + { + unsigned char sk[32], pk[32]; newKey(sk, pk); + std::string d = btf::SignDescriptor(ctx, sk, ENC_HEX, "node-1", 5); + json j = json::parse(d); j["meeting_node"] = "evil-node"; + btf::Descriptor o; + CHECK(!btf::VerifyDescriptor(ctx, j.dump(), pk, o), "tampered meeting_node rejected"); + json j2 = json::parse(d); j2["enc"] = "00000000000000000000000000000000000000000000000000000000deadbeef"; + CHECK(!btf::VerifyDescriptor(ctx, j2.dump(), pk, o), "tampered enc rejected"); + } + + printf("full_resolve_chain_from_address\n"); + { + unsigned char sk[32], pk[32]; newKey(sk, pk); + std::string addr = btf::Address(pk); + unsigned char resolved[32]; + CHECK(btf::ParseAddress(addr, resolved), "address parses"); + std::string d = btf::SignDescriptor(ctx, sk, ENC_HEX, "meeting", 1); + btf::Descriptor o; + CHECK(btf::VerifyDescriptor(ctx, d, resolved, o), "descriptor verifies under resolved key"); + } + + // Show a sample address so we can eyeball the format + { + unsigned char sk[32], pk[32]; newKey(sk, pk); + printf("\nsample .btf address:\n %s\n", btf::Address(pk).c_str()); + } + + printf("\n%s (%d failures)\n", g_fail == 0 ? "ALL TESTS PASSED" : "TESTS FAILED", g_fail); + secp256k1_context_destroy(ctx); + return g_fail == 0 ? 0 : 1; +} -- cgit v1.2.3 From d2b86473a267c960a1f0c012a983176e5d962187 Mon Sep 17 00:00:00 2001 From: Nsable-sh Date: Thu, 13 Aug 2026 11:11:59 -0300 Subject: net: add signed direct onion peer endpoints --- README.md | 26 ++++++++----- docs/rendezvous.md | 70 +++++++++++++++++++++++++++++------ docs/tor.md | 39 ++++++++++++++++++-- src/btfaddr.cpp | 102 +++++++++++++++++++++++++++++++++++++++++++++++---- src/btfaddr.h | 8 +++- src/main_gui.cpp | 15 +++++++- src/net.cpp | 102 +++++++++++++++++++++++++++++++++++++++++---------- src/net.h | 3 +- src/nostr.cpp | 76 +++++++++++++++++++++++++++++++------- src/nostr.h | 12 +++++- src/readme.txt | 8 ++-- src/selftest.cpp | 9 +++++ src/sockcount.h | 1 + src/test_btfaddr.cpp | 22 +++++++++++ 14 files changed, 420 insertions(+), 73 deletions(-) (limited to 'src/test_btfaddr.cpp') diff --git a/README.md b/README.md index e671302..181b6e8 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Bitflash keeps Satoshi's original consensus rules and replaces two things: **RandomX proof of work.** Memory-hard algorithm used by Monero. A laptop competes equally with a server. ASICs and GPUs have no advantage. -**Anonymous addressing.** Every node has a `.btf` address derived from its public key, similar to a Tor `.onion`. Nodes reach each other through encrypted rendezvous tunnels, so no port forwarding is needed and a node behind CGNAT works normally. +**Anonymous addressing.** Every node has a `.btf` address derived from its public key, similar to a Tor `.onion`. Nodes reach each other through encrypted rendezvous tunnels by default, and can advertise a signed direct `.onion` endpoint for Tor peers. No premine. No ICO. 50 BTF per block, halving on schedule, 21M cap, ~2 minute blocks. @@ -30,14 +30,15 @@ No premine. No ICO. 50 BTF per block, halving on schedule, 21M cap, ~2 minute bl Worth being precise, because the difference matters if you are relying on it. -**A peer you reach over `.btf` does not learn your IP.** All outbound connections go through a rendezvous tunnel; there is no IP-based peer dialling left in the node. The relay forwards encrypted bytes and cannot read or alter them. +**A peer you reach over `.btf` does not learn your IP.** Outbound peer discovery uses rendezvous tunnels by default. If both sides use Tor and the peer advertises a signed `.onion` endpoint, the node connects directly to that hidden service instead. In both cases the peer does not see your clearnet IP. -**The rendezvous relay does see your IP.** It has to — it is the thing your TCP connection terminates on. Relays are run by volunteers, so treat that as a party who knows you are on the network. +**The rendezvous relay sees your IP unless you use Tor.** It has to — it is the thing your TCP connection terminates on. With `-tor`, the relay sees Tor instead. With a signed direct `.onion` peer endpoint, the relay is not on that connection path at all. **The node still listens on 8433.** Nothing dials by IP any more, but the listener is still there, so anyone who already knows your address and can reach that port may connect directly. If that matters to you, firewall it. This is unlinkability between peers, not anonymity against a network observer. -For Tor routing, start the node with `-tor`; see [Tor mode](docs/tor.md). +For Tor routing and direct onion peer endpoints, start the node with `-tor`; +see [Tor mode](docs/tor.md). For a plain SOCKS5 proxy without Tor-specific defaults, use `-socks=HOST:PORT`. @@ -336,8 +337,9 @@ Other options worth knowing: ```bash -datadir=PATH # wallet and chain data elsewhere -port=N # P2P listen port, default 8433 --socks=HOST:PORT # SOCKS5 for outbound Nostr and .btf rendezvous dials +-socks=HOST:PORT # SOCKS5 for outbound Nostr, .btf relay, and onion peer dials -tor[=HOST:PORT] # Tor mode; default local Tor SOCKS5 proxy is 127.0.0.1:9050 +-onionservice=HOST.onion:PORT # advertise this node's Tor hidden service -debug # verbose log; without it debug.log is nearly silent -help # full list ``` @@ -346,15 +348,19 @@ Other options worth knowing: needed — the data directory takes an exclusive lock, so a second node pointed at the same one will refuse to start. -`-socks=127.0.0.1:9050` routes outbound Nostr discovery and `.btf` rendezvous -dials through a local SOCKS5 proxy such as Tor. When it is set, the node skips +`-socks=127.0.0.1:9050` routes outbound Nostr discovery, `.btf` rendezvous +dials, and direct `.onion` peer dials through a local SOCKS5 proxy such as Tor. +When it is set, the node skips plain HTTP external-IP probes instead of leaking a direct request outside the proxy. IPv6 proxy endpoints use brackets, for example `-socks=[::1]:9050`. `-tor` is a privacy shorthand for the usual local Tor SOCKS5 listener at -`127.0.0.1:9050`. It routes outbound Nostr discovery and `.btf` rendezvous -dials through Tor, refuses direct `.onion` resolution, and keeps external-IP -probes disabled. Use `-tor=HOST:PORT` when Tor listens somewhere else. +`127.0.0.1:9050`. It routes outbound Nostr discovery, `.btf` rendezvous dials, +and signed direct `.onion` peer dials through Tor, and keeps external-IP probes +disabled. Use `-tor=HOST:PORT` when Tor listens somewhere else. To make your own +node reachable without a rendezvous relay, expose port `8433` as a Tor hidden +service and pass `-onionservice=HOST.onion:8433`; peers with `-tor` will try it +before falling back to rendezvous. ### When something looks wrong diff --git a/docs/rendezvous.md b/docs/rendezvous.md index ac8e598..e1888b9 100644 --- a/docs/rendezvous.md +++ b/docs/rendezvous.md @@ -18,11 +18,16 @@ A connection to a `.btf` service has three layers: 1. **Discovery (Nostr).** The service publishes a signed descriptor as a Nostr event. A caller fetches it by the service public key and verifies the signature. The descriptor says which rendezvous relay the service is waiting - at and which encryption key to use. + at, which encryption key to use, and optionally which Tor hidden service can + be dialed directly. 2. **Rendezvous (TCP).** Caller and service both connect out to the same relay and are paired by public key. Neither needs an inbound port or a public IP. After pairing the relay is a blind byte pipe. -3. **Encrypted channel (X25519 + XChaCha20-Poly1305).** Over the paired pipe the +3. **Direct onion fallback bypass.** If the descriptor carries a valid signed + `.onion:port` endpoint and the caller is running with Tor mode, the caller + tries that endpoint before using rendezvous. This removes the rendezvous + relay from the data path for peers that choose to run hidden services. +4. **Encrypted channel (X25519 + XChaCha20-Poly1305).** Over the paired pipe the caller and service run an ephemeral to static handshake and then exchange authenticated frames. The relay sees only ciphertext. @@ -107,6 +112,8 @@ The default rendezvous port is `8434`. The descriptor is a JSON object, signed with the identity key over a domain separated digest of its own fields. +Legacy descriptor: + ```json { "v": 2, @@ -118,7 +125,22 @@ separated digest of its own fields. } ``` -The signed digest is: +Onion-capable descriptor: + +```json +{ + "v": 3, + "pubkey": "", + "enc": "", + "meeting_node": "host:port", + "onion": "<56-char-v3-name>.onion:8433", + "created": , + "sig": "", + "sig3": "" +} +``` + +The legacy signed digest is: ``` digest = SHA256( ".btf-descriptor-v2" @@ -128,17 +150,37 @@ digest = SHA256( ".btf-descriptor-v2" || created (8 bytes, big endian) ) ``` -The signature is a deterministic BIP340 Schnorr signature (no auxiliary -randomness) over `digest` by the identity key. +`sig` is kept on v3 descriptors so old nodes can still resolve and dial through +the rendezvous relay. The onion-capable digest is: + +``` +digest3 = SHA256( ".btf-descriptor-v3-onion" + || pubkey[32] + || enc (raw bytes of the string) + || meeting_node (raw bytes of the string) + || onion (raw bytes of the normalized string) + || created (8 bytes, big endian) ) +``` + +`sig` and `sig3` are deterministic BIP340 Schnorr signatures (no auxiliary +randomness) over their respective digests by the identity key. **Verification** (untrusted input, must never throw): parse the JSON, require all fields with the right types, confirm `pubkey` equals the address being resolved, recompute the digest, and verify the Schnorr signature. Any failure rejects the descriptor. +If `onion` is present, readers accept it only when it is a normalized v3 onion +endpoint and `sig3` verifies. A bad or tampered onion field is ignored; the v2 +descriptor can still be used for rendezvous fallback if `sig` verifies. + `created` lets a reader prefer the freshest descriptor when more than one is -seen. A node only publishes a descriptor once it has actually registered at a -`meeting_node`, so it never advertises a relay it cannot be reached at. +seen. A node without a direct onion endpoint only publishes a descriptor once it +has actually registered at a `meeting_node`, so it never advertises a relay it +cannot be reached at. A node with a direct onion endpoint may publish before +rendezvous registration using `meeting_node = "rendezvous-pending"`; Tor peers +can still dial the signed onion endpoint, and rendezvous becomes fallback once +registration succeeds. ## 6. Rendezvous transport @@ -243,8 +285,9 @@ tunnel. not published anywhere. - **Forward secrecy.** The caller's per connection ephemeral key means a later compromise of the service encryption key does not decrypt past sessions. -- **IP privacy.** Neither side needs a public IP or an inbound port. The observable - network fact is that each side has a TCP connection to a relay. +- **IP privacy.** Neither side needs a public IP or an inbound port for + rendezvous. With a signed `.onion` endpoint, the reachable side exposes only a + Tor hidden service and the relay is not in the peer connection path. ## 10. Threat model and limitations @@ -265,6 +308,9 @@ tunnel. unreachable, discovery stalls until one is reachable again. Relay TLS is verified, which closes a man in the middle path on discovery, but availability still rests on the relay set. +- **Direct onion is not automatic Tor configuration.** Bitflash signs and + advertises a hidden-service endpoint, and Tor-mode peers can dial it. The Tor + daemon still owns hidden-service creation, private keys, rotation and uptime. ## 11. Wire reference @@ -273,9 +319,9 @@ tunnel. | `.btf` Base32 alphabet | `abcdefghijklmnopqrstuvwxyz234567`, no padding | | Address payload | `pubkey[32] || checksum[2]`, 55 Base32 chars | | Address checksum | `SHA256(".btf-checksum-v1" || pubkey)[0..2]` | -| Descriptor domain sep | `.btf-descriptor-v2` | -| Descriptor version | `2` | -| Descriptor signature | BIP340 Schnorr, deterministic (no aux rand) | +| Descriptor domain sep | `.btf-descriptor-v2`; optional onion sep `.btf-descriptor-v3-onion` | +| Descriptor version | `2`; `3` when a signed onion endpoint is present | +| Descriptor signature | BIP340 Schnorr, deterministic (no aux rand), v3 keeps `sig` plus `sig3` | | Nostr descriptor event | kind `38501`, `d = btf-descriptor-2` | | Nostr relay event | kind `38502`, `d = btf-relay-2` | | Nostr pool event | kind `38503`, `d = btf-pool-2` | diff --git a/docs/tor.md b/docs/tor.md index 69b29f1..b4f88f9 100644 --- a/docs/tor.md +++ b/docs/tor.md @@ -40,6 +40,8 @@ When Tor mode is enabled: - outbound Nostr relay dials use Tor; - outbound `.btf` rendezvous relay dials use Tor; +- outbound direct peer dials prefer signed `.onion` endpoints when a peer + advertises one; - destination names are sent to Tor as SOCKS5 domain-name CONNECT requests, so the local DNS resolver does not see them; - direct `.onion` dials are refused unless a SOCKS5/Tor proxy is enabled; @@ -98,7 +100,7 @@ bitflash -operator -tor \ -announcerelay=exampleexampleexampleexampleexampleexampleexampleexample.onion:8434 ``` -## Full-node hidden service +## Direct full-node hidden service The legacy P2P listener still binds to port `8433`. You can expose it through Tor manually: @@ -108,6 +110,35 @@ HiddenServiceDir /var/lib/tor/bitflash-node/ HiddenServicePort 8433 127.0.0.1:8433 ``` -Current automatic peer discovery is `.btf`/rendezvous based, not onion-address -gossip. Treat direct full-node onion access as an operator/admin tool unless a -future release adds first-class onion peer advertisements. +After restarting Tor, read the generated onion name: + +```bash +sudo cat /var/lib/tor/bitflash-node/hostname +``` + +Then start Bitflash with Tor outbound enabled and advertise that hidden service: + +```bash +bitflash -tor \ + -onionservice=exampleexampleexampleexampleexampleexampleexampleexample.onion:8433 +``` + +That onion endpoint is signed into this node's self-certifying `.btf` +descriptor. New peers that resolve the descriptor and also run with `-tor` try +the `.onion:8433` P2P connection first. If it fails, they fall back to the +ordinary encrypted rendezvous path. Older nodes ignore the onion field and still +use the rendezvous relay because the descriptor keeps the legacy signature too. + +If the node has `-onionservice` but has not registered at any rendezvous relay +yet, it can still publish an onion-capable descriptor with +`meeting_node = rendezvous-pending`. Tor-capable peers can dial the hidden +service directly from that descriptor. Rendezvous becomes a fallback, not a +precondition for being discoverable. + +This means rendezvous relays stop being the only way to reach a node that has +published a hidden service. They remain useful bootstrap/fallback infrastructure, +but an already-discovered onion-capable peer can be reached directly over Tor. + +The node does not create or rotate Tor hidden services itself. Tor owns the +private key under `HiddenServiceDir`; back it up if you want the onion name to +stay stable. diff --git a/src/btfaddr.cpp b/src/btfaddr.cpp index 6edcc91..ce2ac86 100644 --- a/src/btfaddr.cpp +++ b/src/btfaddr.cpp @@ -19,6 +19,8 @@ #include #include #include +#include +#include using json = nlohmann::json; @@ -166,10 +168,47 @@ static bool HexDecode(const std::string& s, unsigned char* out, size_t n) return true; } +bool NormalizeOnionEndpoint(const std::string& in, std::string& out) +{ + out.clear(); + std::string s = ToLowerTrim(in); + size_t colon = s.rfind(':'); + if (colon == std::string::npos || colon == 0 || colon + 1 >= s.size()) + return false; + + std::string host = s.substr(0, colon); + std::string port = s.substr(colon + 1); + while (!host.empty() && host.back() == '.') host.pop_back(); + static const char* suffix = ".onion"; + const size_t suffixLen = strlen(suffix); + if (host.size() != 56 + suffixLen) + return false; + if (host.compare(host.size() - suffixLen, suffixLen, suffix) != 0) + return false; + for (size_t i = 0; i < 56; i++) + { + char c = host[i]; + if (!((c >= 'a' && c <= 'z') || (c >= '2' && c <= '7'))) + return false; + } + for (size_t i = 0; i < port.size(); i++) + if (!isdigit((unsigned char)port[i])) + return false; + + errno = 0; + char* end = NULL; + long nPort = strtol(port.c_str(), &end, 10); + if (errno == ERANGE || end == NULL || *end != '\0' || nPort <= 0 || nPort > 65535) + return false; + + out = host + ":" + port; + return true; +} + // Digest signed over the descriptor fields (domain-separated). -static void DescriptorDigest(const unsigned char pubkey[32], const std::string& enc, - const std::string& meeting_node, uint64_t created, - unsigned char out[32]) +static void DescriptorDigestV2(const unsigned char pubkey[32], const std::string& enc, + const std::string& meeting_node, uint64_t created, + unsigned char out[32]) { static const char* DS = ".btf-descriptor-v2"; SHA256_CTX ctx; @@ -184,9 +223,27 @@ static void DescriptorDigest(const unsigned char pubkey[32], const std::string& SHA256_Final(out, &ctx); } +static void DescriptorDigestV3(const unsigned char pubkey[32], const std::string& enc, + const std::string& meeting_node, const std::string& onion, + uint64_t created, unsigned char out[32]) +{ + static const char* DS = ".btf-descriptor-v3-onion"; + SHA256_CTX ctx; + SHA256_Init(&ctx); + SHA256_Update(&ctx, (const unsigned char*)DS, strlen(DS)); + SHA256_Update(&ctx, pubkey, 32); + SHA256_Update(&ctx, (const unsigned char*)enc.data(), enc.size()); + SHA256_Update(&ctx, (const unsigned char*)meeting_node.data(), meeting_node.size()); + SHA256_Update(&ctx, (const unsigned char*)onion.data(), onion.size()); + unsigned char be[8]; + for (int i = 0; i < 8; i++) be[i] = (unsigned char)((created >> (8 * (7 - i))) & 0xff); + SHA256_Update(&ctx, be, 8); + SHA256_Final(out, &ctx); +} + std::string SignDescriptor(void* ctxv, const unsigned char seckey[32], const std::string& enc, const std::string& meeting_node, - uint64_t created) + uint64_t created, const std::string& onion) { secp256k1_context* ctx = (secp256k1_context*)ctxv; secp256k1_keypair kp; @@ -197,17 +254,28 @@ std::string SignDescriptor(void* ctxv, const unsigned char seckey[32], secp256k1_xonly_pubkey_serialize(ctx, pubkey, &xpub); unsigned char digest[32]; - DescriptorDigest(pubkey, enc, meeting_node, created, digest); + DescriptorDigestV2(pubkey, enc, meeting_node, created, digest); unsigned char sig[64]; // Deterministic signature (NULL aux_rand), matching Itzal's no-aux-rand signing. if (!secp256k1_schnorrsig_sign32(ctx, sig, digest, &kp, NULL)) return std::string(); json v = json::object(); - v["v"] = 2; + v["v"] = onion.empty() ? 2 : 3; v["pubkey"] = HexEncode(pubkey, 32); v["enc"] = enc; v["meeting_node"] = meeting_node; + if (!onion.empty()) + { + std::string onionNorm; + if (!NormalizeOnionEndpoint(onion, onionNorm)) return std::string(); + unsigned char digest3[32]; + DescriptorDigestV3(pubkey, enc, meeting_node, onionNorm, created, digest3); + unsigned char sig3[64]; + if (!secp256k1_schnorrsig_sign32(ctx, sig3, digest3, &kp, NULL)) return std::string(); + v["onion"] = onionNorm; + v["sig3"] = HexEncode(sig3, 64); + } v["created"] = created; v["sig"] = HexEncode(sig, 64); return v.dump(); @@ -242,15 +310,35 @@ bool VerifyDescriptor(void* ctxv, const std::string& jsonStr, if (!HexDecode(v["sig"].get(), sig, 64)) return false; unsigned char digest[32]; - DescriptorDigest(expect_pubkey, enc, meeting_node, created, digest); + DescriptorDigestV2(expect_pubkey, enc, meeting_node, created, digest); secp256k1_xonly_pubkey xpub; if (!secp256k1_xonly_pubkey_parse(ctx, &xpub, expect_pubkey)) return false; if (!secp256k1_schnorrsig_verify(ctx, sig, digest, 32, &xpub)) return false; + std::string onion; + if (v.contains("onion")) + { + if (v["onion"].is_string() && v.contains("sig3") && v["sig3"].is_string()) + { + std::string onionNorm; + std::string onionRaw = v["onion"].get(); + if (NormalizeOnionEndpoint(onionRaw, onionNorm) && onionNorm == onionRaw) + { + unsigned char sig3[64]; + unsigned char digest3[32]; + DescriptorDigestV3(expect_pubkey, enc, meeting_node, onionNorm, created, digest3); + if (HexDecode(v["sig3"].get(), sig3, 64) && + secp256k1_schnorrsig_verify(ctx, sig3, digest3, 32, &xpub)) + onion = onionNorm; + } + } + } + memcpy(out.pubkey, expect_pubkey, 32); out.enc = enc; out.meeting_node = meeting_node; + out.onion = onion; out.created = created; return true; } diff --git a/src/btfaddr.h b/src/btfaddr.h index 1addf8f..55a3ebd 100644 --- a/src/btfaddr.h +++ b/src/btfaddr.h @@ -52,15 +52,21 @@ struct Descriptor unsigned char pubkey[32]; std::string enc; // service x25519 public key (hex) for the E2E channel std::string meeting_node; // rendezvous node the service is registered at + std::string onion; // optional direct Tor hidden-service endpoint (host.onion:port) uint64_t created; }; +// Normalize and validate a direct Tor hidden-service endpoint. Only v3 onion +// names are accepted: 56 base32 chars plus ".onion", followed by ":PORT". +bool NormalizeOnionEndpoint(const std::string& in, std::string& out); + // Sign a descriptor. `ctx` is a secp256k1_context* (passed as void* to keep this // header free of secp headers); `seckey` is the 32-byte service secret key. // Returns the descriptor JSON as a string, or "" on failure. std::string SignDescriptor(void* ctx, const unsigned char seckey[32], const std::string& enc, const std::string& meeting_node, - uint64_t created); + uint64_t created, + const std::string& onion = std::string()); // Verify a descriptor is validly signed by `expect_pubkey` (the key the resolved // `.btf` address encodes). Returns true and fills `out` on success. diff --git a/src/main_gui.cpp b/src/main_gui.cpp index bef8503..239fb60 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -1,6 +1,7 @@ // Bitflash entry point -- starts node threads then runs GUI (or headless). #include "headers_core.h" +#include "nostr.h" #include "proxy.h" #include "selftest.h" #include "walletcmd.h" @@ -134,10 +135,11 @@ static void PrintUsage() printf(" /connectbtf=PEER_BTF_ADDRESS\n"); printf(" /rvrelay=HOST:PORT\n"); printf(" /announcerelay=HOST:PORT\n"); + printf(" /onionservice=HOST.onion:PORT (advertise this node's Tor hidden service)\n"); printf("\n"); printf("Network:\n"); printf(" /port=N (P2P listen port, default 8433)\n"); - printf(" /socks=HOST:PORT (SOCKS5 proxy for outbound Nostr and .btf relay dials)\n"); + printf(" /socks=HOST:PORT (SOCKS5 proxy for Nostr, .btf relay, and onion dials)\n"); printf(" /tor[=HOST:PORT] (Tor mode; default SOCKS5 proxy is 127.0.0.1:9050)\n"); printf(" /btfseed=ADDRESS:ENCHEX (extra bootstrap peer, repeatable)\n"); printf("\n"); @@ -286,6 +288,17 @@ static void ParseStartupArguments(int argc, char* argv[]) if (!announceRelay.empty()) strBtfAnnounceRelay = announceRelay; + string onionService = argval2(argc, argv, "/onionservice", "-onionservice"); + if (!onionService.empty()) + { + string err; + if (!BtfSetLocalOnionEndpoint(onionService, err)) + fprintf(stderr, "Ignoring /onionservice=%s: %s\n", onionService.c_str(), err.c_str()); + else + fprintf(stderr, "Direct onion peer endpoint advertised: %s\n", + BtfLocalOnionEndpoint().c_str()); + } + bool fTorMode = arg(argc, argv, "/tor") || arg(argc, argv, "-tor"); if (fTorMode) { diff --git a/src/net.cpp b/src/net.cpp index c24547e..ab17332 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -17,6 +17,8 @@ #include #endif #include +#include +#include #include "btfaddr.h" #include "btftunnel.h" #include "proxy.h" @@ -170,7 +172,7 @@ static const char* pszSockSite[SOCK_SITES] = { "external-ip probe", "listen socket", "inbound accept", "rendezvous dial", "rendezvous listen", "rendezvous accept", "loopback pair listener", "loopback pair app end", "loopback pair pump end", - "nostr relay", "stratum bridge" + "nostr relay", "direct onion peer", "stratum bridge" }; static string SockAccountingText() @@ -627,6 +629,7 @@ struct CachedBtfPeer { string btfAddr; string meeting; + string onion; string encHex; int64 lastSeen; // The peer's own signed descriptor, as it announced itself. Kept verbatim @@ -685,6 +688,8 @@ void LoadCachedBtfPeers(vector& out) CachedBtfPeer p; p.btfAddr = o["btf"].get(); p.meeting = o["meeting"].get(); + if (o.contains("onion") && o["onion"].is_string()) + btf::NormalizeOnionEndpoint(o["onion"].get(), p.onion); p.encHex = o["enc"].get(); p.lastSeen = o.value("seen", (int64)0); if (o.contains("desc") && o["desc"].is_string()) @@ -708,7 +713,8 @@ static CCriticalSection cs_btfPeerCache; // learned about by exchange must not cost us the ability to pass it on. static void RememberBtfPeer(const string& strBtfAddr, const string& strMeeting, const unsigned char enc_pub[32], - const string& strDesc = string()) + const string& strDesc = string(), + const string& strOnion = string()) { CRITICAL_BLOCK(cs_btfPeerCache) { @@ -716,11 +722,15 @@ static void RememberBtfPeer(const string& strBtfAddr, const string& strMeeting, LoadCachedBtfPeers(peers); string strKeepDesc = strDesc; + string strKeepOnion; + btf::NormalizeOnionEndpoint(strOnion, strKeepOnion); for (size_t i = 0; i < peers.size(); i++) if (peers[i].btfAddr == strBtfAddr) { if (strKeepDesc.empty()) strKeepDesc = peers[i].desc; + if (strKeepOnion.empty()) + strKeepOnion = peers[i].onion; peers.erase(peers.begin() + i); break; } @@ -728,6 +738,7 @@ static void RememberBtfPeer(const string& strBtfAddr, const string& strMeeting, CachedBtfPeer p; p.btfAddr = strBtfAddr; p.meeting = strMeeting; + p.onion = strKeepOnion; p.encHex = BytesToHex(enc_pub, 32); p.lastSeen = GetTime(); p.desc = strKeepDesc; @@ -742,6 +753,8 @@ static void RememberBtfPeer(const string& strBtfAddr, const string& strMeeting, nlohmann::json o; o["btf"] = q.btfAddr; o["meeting"] = q.meeting; + if (!q.onion.empty()) + o["onion"] = q.onion; o["enc"] = q.encHex; o["seen"] = q.lastSeen; if (!q.desc.empty()) @@ -830,7 +843,7 @@ static int TryBtfSeeds() foreach(const string& strRelay, relays) { if (fShutdown) return nConnected; - if (ConnectNodeBtfResolved(s.first, strRelay, enc)) + if (ConnectNodeBtfResolved(s.first, strRelay, "", enc)) { LogPrint("net", "btfseed: reached %s via %s\n", s.first.c_str(), strRelay.c_str()); @@ -868,7 +881,7 @@ void ThreadReconnectCachedBtfPeers(void* parg) if (fShutdown) return; unsigned char enc[32]; if (!HexToBytes(p.encHex, enc, 32)) continue; - if (ConnectNodeBtfResolved(p.btfAddr, p.meeting, enc)) + if (ConnectNodeBtfResolved(p.btfAddr, p.meeting, p.onion, enc)) { nConnected++; if (nConnected >= 8) break; // enough to bootstrap; the rest can wait @@ -959,14 +972,37 @@ int BtfPexAccept(const vector& vDesc) if (!HexToBytes(d.enc, enc, 32)) continue; - RememberBtfPeer(strAddr, d.meeting_node, enc, strDesc); + RememberBtfPeer(strAddr, d.meeting_node, enc, strDesc, d.onion); nKept++; } return nKept; } +static bool SplitHostPort(const string& strHostPort, string& strHost, unsigned short& nPort) +{ + size_t colon = strHostPort.rfind(':'); + if (colon == string::npos || colon == 0 || colon + 1 >= strHostPort.size()) + return false; + string port = strHostPort.substr(colon + 1); + for (size_t i = 0; i < port.size(); i++) + if (!isdigit((unsigned char)port[i])) + return false; + + errno = 0; + char* end = NULL; + long n = strtol(port.c_str(), &end, 10); + if (errno == ERANGE || end == NULL || *end != '\0' || n <= 0 || n > 65535) + return false; + + strHost = strHostPort.substr(0, colon); + nPort = (unsigned short)n; + return true; +} + static CNode* ConnectNodeBtfTail(const string& strBtfAddr, const unsigned char pk[32], - const string& strMeeting, const unsigned char enc_pub[32]) + const string& strMeeting, const string& strOnion, + const unsigned char enc_pub[32], + const string& strDesc = string()) { CAddress addr = BtfMarkerAddr(pk); CNode* pnode = FindNode(addr.ip); @@ -976,16 +1012,42 @@ static CNode* ConnectNodeBtfTail(const string& strBtfAddr, const unsigned char p return pnode; } - BtfChurnNoteDialAttempt(strBtfAddr, strMeeting); - size_t colon = strMeeting.rfind(':'); - if (colon == string::npos) + string strOnionNorm; + if (BtfSocks5ProxyEnabled() && btf::NormalizeOnionEndpoint(strOnion, strOnionNorm)) { - BtfChurnNoteDialResult(strBtfAddr, strMeeting, false); - return NULL; + string strOnionHost; + unsigned short nOnionPort = 0; + if (SplitHostPort(strOnionNorm, strOnionHost, nOnionPort)) + { + BtfChurnNoteDialAttempt(strBtfAddr, strOnionNorm); + SOCKET hOnionSocket = BtfConnectSocket(strOnionHost, nOnionPort, SOCK_ONION_PEER, 20); + if (hOnionSocket != INVALID_SOCKET) + { + if (fDebug) + LogPrint("net", "connected %s via direct onion %s\n", + strBtfAddr.c_str(), strOnionNorm.c_str()); + BtfChurnNoteDialResult(strBtfAddr, strOnionNorm, true); + RememberBtfPeer(strBtfAddr, strMeeting, enc_pub, strDesc, strOnionNorm); + + pnode = new CNode(hOnionSocket, addr, false); + pnode->strBtfAddr = strBtfAddr; + pnode->strBtfMeeting = string("onion ") + strOnionNorm; + pnode->AddRef(); + CRITICAL_BLOCK(cs_vNodes) + vNodes.push_back(pnode); + return pnode; + } + if (fDebug) + LogPrint("net", "ConnectNodeBtf: direct onion to %s at %s failed, falling back to rendezvous\n", + strBtfAddr.c_str(), strOnionNorm.c_str()); + BtfChurnNoteDialResult(strBtfAddr, strOnionNorm, false); + } } - string strHost = strMeeting.substr(0, colon); - int nPort = atoi(strMeeting.substr(colon + 1).c_str()); - if (nPort <= 0 || nPort > 65535) + + BtfChurnNoteDialAttempt(strBtfAddr, strMeeting); + string strHost; + unsigned short nPort = 0; + if (!SplitHostPort(strMeeting, strHost, nPort)) { BtfChurnNoteDialResult(strBtfAddr, strMeeting, false); return NULL; @@ -1005,7 +1067,7 @@ static CNode* ConnectNodeBtfTail(const string& strBtfAddr, const unsigned char p BtfChurnNoteDialResult(strBtfAddr, strMeeting, true); // This one answered -- worth trying first next time we start. - RememberBtfPeer(strBtfAddr, strMeeting, enc_pub); + RememberBtfPeer(strBtfAddr, strMeeting, enc_pub, strDesc, strOnionNorm); // Add node pnode = new CNode(hSocket, addr, false); @@ -1035,9 +1097,10 @@ CNode* ConnectNodeBtf(const string& strBtfAddr) LogPrint("net", "trying %s\n", strBtfAddr.c_str()); string strMeeting; + string strOnion; unsigned char enc_pub[32]; BtfChurnNoteResolveAttempt(); - if (!BtfResolve(strBtfAddr, strMeeting, enc_pub)) + if (!BtfResolve(strBtfAddr, strMeeting, enc_pub, &strOnion)) { BtfChurnNoteResolveResult(false); if (fDebug) @@ -1045,7 +1108,7 @@ CNode* ConnectNodeBtf(const string& strBtfAddr) return NULL; } BtfChurnNoteResolveResult(true); - return ConnectNodeBtfTail(strBtfAddr, pk, strMeeting, enc_pub); + return ConnectNodeBtfTail(strBtfAddr, pk, strMeeting, strOnion, enc_pub); } // Same as ConnectNodeBtf, but skips the Nostr resolve step because the caller @@ -1054,7 +1117,8 @@ CNode* ConnectNodeBtf(const string& strBtfAddr) // address). Makes zero relay connections -- only talks to the peer's // rendezvous meeting node. CNode* ConnectNodeBtfResolved(const string& strBtfAddr, const string& strMeeting, - const unsigned char enc_pub[32]) + const string& strOnion, const unsigned char enc_pub[32], + const string& strDesc) { unsigned char pk[32]; if (!btf::ParseAddress(strBtfAddr, pk)) @@ -1064,7 +1128,7 @@ CNode* ConnectNodeBtfResolved(const string& strBtfAddr, const string& strMeeting } if (BtfLocalAddress() == strBtfAddr) return NULL; // ourselves - return ConnectNodeBtfTail(strBtfAddr, pk, strMeeting, enc_pub); + return ConnectNodeBtfTail(strBtfAddr, pk, strMeeting, strOnion, enc_pub, strDesc); } // Anonymous inbound listener (this node's `.btf` hidden service). Registers at diff --git a/src/net.h b/src/net.h index feecf96..9300169 100644 --- a/src/net.h +++ b/src/net.h @@ -28,7 +28,8 @@ enum bool GetMyExternalIP(unsigned int& ipRet); CNode* ConnectNodeBtf(const string& strBtfAddr); CNode* ConnectNodeBtfResolved(const string& strBtfAddr, const string& strMeeting, - const unsigned char enc_pub[32]); + const string& strOnion, const unsigned char enc_pub[32], + const string& strDesc=string()); void ThreadBtfAccept(void* parg); void ThreadBtfConnect(void* parg); extern string strBtfConnect; diff --git a/src/nostr.cpp b/src/nostr.cpp index d286767..0c1b4b6 100644 --- a/src/nostr.cpp +++ b/src/nostr.cpp @@ -112,6 +112,8 @@ vector vBtfMeetingRelays = { }; string strBtfActiveRelay; static CCriticalSection cs_activeRelay; +static string strBtfOnionEndpoint; +static CCriticalSection cs_onionEndpoint; // Only the rendezvous we actually registered at (BtfSetActiveRelay, called from // ThreadBtfAccept once registration succeeds). Empty until then, on purpose: it @@ -133,6 +135,26 @@ void BtfSetActiveRelay(const string& relay) strBtfActiveRelay = relay; } +bool BtfSetLocalOnionEndpoint(const string& endpoint, string& errOut) +{ + string norm; + if (!btf::NormalizeOnionEndpoint(endpoint, norm)) + { + errOut = "expected v3 onion endpoint HOST.onion:PORT"; + return false; + } + CRITICAL_BLOCK(cs_onionEndpoint) + strBtfOnionEndpoint = norm; + return true; +} + +string BtfLocalOnionEndpoint() +{ + CRITICAL_BLOCK(cs_onionEndpoint) + return strBtfOnionEndpoint; + return ""; +} + // A relay this node advertises on Nostr for others to discover (/announcerelay). string strBtfAnnounceRelay; // Relays learned from other operators' Nostr announcements. @@ -370,10 +392,16 @@ std::string BtfLocalDescriptor() string meeting; CRITICAL_BLOCK(cs_activeRelay) meeting = strBtfActiveRelay; + string onion = BtfLocalOnionEndpoint(); if (meeting.empty()) - return ""; + { + if (onion.empty()) + return ""; + meeting = "rendezvous-pending"; + } return btf::SignDescriptor(g_nostrKey.ctx, g_nostrKey.seckey, - g_nostrKey.EncPubHex(), meeting, (uint64_t)GetTime()); + g_nostrKey.EncPubHex(), meeting, (uint64_t)GetTime(), + onion); } // The shared secp256k1 context, so net.cpp can verify descriptors that arrive @@ -806,17 +834,21 @@ static void PublishDescriptor(CWebSocket& ws, CNostrKey& key) // meeting_node is the rendezvous relay this node's hidden service // (ThreadBtfAccept in net.cpp) is registered at -- where clients dial us. string meeting_node = BtfActiveRelay(); + string onion = BtfLocalOnionEndpoint(); if (meeting_node.empty()) { - // Not registered anywhere yet. Publishing now would advertise a meeting - // node we can't be reached at, and peers would waste dials on it. The - // ThreadNostrSeed loop republishes on every pass, so skipping costs - // nothing but the delay until ThreadBtfAccept registers. - LogPrint("nostr", "Nostr: skipping descriptor publish, no rendezvous registered yet\n"); - return; + if (onion.empty()) + { + // Not registered anywhere yet, and no direct onion endpoint exists. + // Publishing now would advertise a meeting node we can't be reached at. + LogPrint("nostr", "Nostr: skipping descriptor publish, no rendezvous registered yet\n"); + return; + } + meeting_node = "rendezvous-pending"; } string desc = btf::SignDescriptor(key.ctx, key.seckey, key.EncPubHex(), - meeting_node, (uint64_t)GetTime()); + meeting_node, (uint64_t)GetTime(), + onion); if (desc.empty()) return; json tags = json::array({ json::array({ "d", BTF_DESC_DTAG }) }); @@ -1018,7 +1050,7 @@ static void HandlePoolAnnouncement(const json& ev) // Resolve a `.btf` address via a relay: fetch the descriptor published by that // address's key and verify it self-certifies under the decoded pubkey. static bool ResolveDescriptor(CWebSocket& ws, void* ctx, const string& btfAddr, - btf::Descriptor& out) + btf::Descriptor& out, string* rawOut = NULL) { unsigned char pk[32]; if (!btf::ParseAddress(btfAddr, pk)) @@ -1045,7 +1077,11 @@ static bool ResolveDescriptor(CWebSocket& ws, void* ctx, const string& btfAddr, const json& ev = j[2]; if (ev.contains("content") && btf::VerifyDescriptor(ctx, ev["content"].get(), pk, out)) + { + if (rawOut) + *rawOut = ev["content"].get(); return true; + } } else if (t == "EOSE") break; @@ -1057,8 +1093,10 @@ static bool ResolveDescriptor(CWebSocket& ws, void* ctx, const string& btfAddr, // public discovery relays for the owner's self-certified descriptor. Used by // ConnectNodeBtf in net.cpp. bool BtfResolve(const std::string& btfAddr, std::string& meetingHostPort, - unsigned char enc_pub[32]) + unsigned char enc_pub[32], std::string* onionHostPort) { + if (onionHostPort) + onionHostPort->clear(); if (!EnsureNostrKey()) return false; for (int i = 0; i < nNostrRelays && !fShutdown; i++) @@ -1076,10 +1114,15 @@ bool BtfResolve(const std::string& btfAddr, std::string& meetingHostPort, } lease.fOk = true; if (d.meeting_node.empty() || d.meeting_node == "rendezvous-pending") - continue; // descriptor predates the owner's relay config + { + if (!onionHostPort || d.onion.empty()) + continue; // caller needs rendezvous, or descriptor has no direct path + } if (!HexDecode(d.enc, enc_pub, 32)) continue; meetingHostPort = d.meeting_node; + if (onionHostPort) + *onionHostPort = d.onion; return true; } CATCH_PRINT_EXCEPTION("BtfResolve") @@ -1168,12 +1211,15 @@ bool BtfResolveMany(const std::vector& btfAddrs, btf::Descriptor d; if (!btf::VerifyDescriptor(g_nostrKey.ctx, ev["content"].get(), pk, d)) continue; - if (d.meeting_node.empty() || d.meeting_node == "rendezvous-pending") + if ((d.meeting_node.empty() || d.meeting_node == "rendezvous-pending") && + d.onion.empty()) continue; BtfResolvedPeer rp; if (!HexDecode(d.enc, rp.enc_pub, 32)) continue; rp.meetingHostPort = d.meeting_node; + rp.onionHostPort = d.onion; + rp.descriptor = ev["content"].get(); out[ai->second] = rp; pending.erase(ai->second); } @@ -1650,11 +1696,13 @@ static void ConnectDiscoveredBtfPeers() DialCtx* ctx = (DialCtx*)arg; string addr = ctx->addr; string meeting = ctx->rp.meetingHostPort; + string onion = ctx->rp.onionHostPort; + string desc = ctx->rp.descriptor; unsigned char enc_pub[32]; memcpy(enc_pub, ctx->rp.enc_pub, 32); delete ctx; - CNode* pnode = ConnectNodeBtfResolved(addr, meeting, enc_pub); + CNode* pnode = ConnectNodeBtfResolved(addr, meeting, onion, enc_pub, desc); CRITICAL_BLOCK(cs_btfPeerState) { if (pnode) diff --git a/src/nostr.h b/src/nostr.h index b5eb5e3..dc4288c 100644 --- a/src/nostr.h +++ b/src/nostr.h @@ -40,6 +40,13 @@ std::string BtfActiveRelay(); // Record the relay this node just registered its service at (thread-safe). void BtfSetActiveRelay(const std::string& relay); +// Optional Tor hidden-service endpoint for this node's normal P2P listener. +// Set by /onionservice=HOST.onion:PORT. The endpoint is signed into this node's +// .btf descriptor, so peers with -tor can dial it directly before falling back +// to rendezvous relays. +bool BtfSetLocalOnionEndpoint(const std::string& endpoint, std::string& errOut); +std::string BtfLocalOnionEndpoint(); + // If set (via /announcerelay=host:port), this node announces that relay on // Nostr so other nodes discover it automatically -- no manual seed-list edit. extern std::string strBtfAnnounceRelay; @@ -94,12 +101,15 @@ void* BtfSecpContext(); // self-certified descriptor and return its meeting node ("host:port") and // x25519 public key for the end-to-end channel. bool BtfResolve(const std::string& btfAddr, std::string& meetingHostPort, - unsigned char enc_pub[32]); + unsigned char enc_pub[32], + std::string* onionHostPort = NULL); // Result of resolving one .btf address via BtfResolveMany. struct BtfResolvedPeer { std::string meetingHostPort; + std::string onionHostPort; + std::string descriptor; unsigned char enc_pub[32]; }; diff --git a/src/readme.txt b/src/readme.txt index 794fe20..1e9cffc 100644 --- a/src/readme.txt +++ b/src/readme.txt @@ -43,11 +43,11 @@ Command-line options (in addition to the original ones) ------------------------------------------------------- /port=N listen on P2P port N (default 8433) /socks=HOST:PORT - route outbound Nostr and .btf rendezvous dials through a - SOCKS5 proxy, e.g. /socks=127.0.0.1:9050 for local Tor + route outbound Nostr, .btf rendezvous, and direct onion peer + dials through a SOCKS5 proxy, e.g. /socks=127.0.0.1:9050 for local Tor or /socks=[::1]:9050 for an IPv6 loopback proxy /tor[=HOST:PORT] - Tor mode for outbound Nostr and .btf rendezvous dials; + Tor mode for outbound Nostr, .btf rendezvous, and direct onion peer dials; defaults to the local Tor SOCKS5 proxy at 127.0.0.1:9050 /solomine mine without requiring a connected peer (local testing) /operator operator mode (run pool server) @@ -72,6 +72,8 @@ Command-line options (in addition to the original ones) override meeting relay list with one relay /announcerelay=HOST:PORT announce this relay on Nostr for discovery + /onionservice=HOST.onion:PORT + advertise this node's Tor hidden service in its signed .btf descriptor Roadmap diff --git a/src/selftest.cpp b/src/selftest.cpp index bcbf9d3..a0d9edd 100644 --- a/src/selftest.cpp +++ b/src/selftest.cpp @@ -6,6 +6,7 @@ // and against a temporary data directory. #include "headers_core.h" +#include "btfaddr.h" #include "bip32.h" #include "proxy.h" #include "selftest.h" @@ -1507,6 +1508,14 @@ static int RunSocks5ProxySelfTest() !BtfIsTorOnionHost("relay.example") && !BtfIsTorOnionHost(".onion"), "detects .onion hosts without accepting lookalikes") ? 0 : 1; + std::string onion; + nFail += Check(btf::NormalizeOnionEndpoint("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABCD.onion.:8433", onion) && + onion == "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd.onion:8433", + "normalizes v3 onion peer endpoint") ? 0 : 1; + nFail += Check(!btf::NormalizeOnionEndpoint("short.onion:8433", onion) && + !btf::NormalizeOnionEndpoint("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd.onion:0", onion) && + !btf::NormalizeOnionEndpoint("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabc1.onion:8433", onion), + "rejects malformed onion peer endpoints") ? 0 : 1; BtfClearSocks5Proxy(); nFail += Check(!BtfSocks5ProxyEnabled(), "starts disabled after clear") ? 0 : 1; diff --git a/src/sockcount.h b/src/sockcount.h index 5147f55..a63c6be 100644 --- a/src/sockcount.h +++ b/src/sockcount.h @@ -63,6 +63,7 @@ enum SOCK_PAIR_APP, // loopback pair: the app end handed to CNode SOCK_PAIR_PUMP, // loopback pair: the pump end SOCK_NOSTR, // outbound to a Nostr relay + SOCK_ONION_PEER, // direct outbound to a peer's Tor hidden service SOCK_STRATUM_BRIDGE, // local Stratum bridge listener/miner sockets SOCK_SITES }; diff --git a/src/test_btfaddr.cpp b/src/test_btfaddr.cpp index b40dcc1..8de426e 100644 --- a/src/test_btfaddr.cpp +++ b/src/test_btfaddr.cpp @@ -86,6 +86,7 @@ int main() } const std::string ENC_HEX = "aabbccddeeff00112233445566778899aabbccddeeff00112233445566778899"; + const std::string ONION = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcd.onion:8433"; // helper: fresh keypair -> (seckey, xonly pubkey) auto newKey = [&](unsigned char sk[32], unsigned char pk[32]) { @@ -108,6 +109,17 @@ int main() CHECK(!btf::VerifyDescriptor(ctx, d, pk2, bad), "different key rejected"); } + printf("descriptor_signs_optional_onion_endpoint\n"); + { + unsigned char sk[32], pk[32]; newKey(sk, pk); + std::string d = btf::SignDescriptor(ctx, sk, ENC_HEX, "meeting-node-abc", 1000, ONION); + CHECK(!d.empty(), "sign produced onion descriptor"); + btf::Descriptor got; + CHECK(btf::VerifyDescriptor(ctx, d, pk, got), "onion descriptor verifies"); + CHECK(got.meeting_node == "meeting-node-abc" && got.enc == ENC_HEX && + got.created == 1000 && got.onion == ONION, "onion fields match"); + } + printf("descriptor_rejects_tampering\n"); { unsigned char sk[32], pk[32]; newKey(sk, pk); @@ -117,6 +129,16 @@ int main() CHECK(!btf::VerifyDescriptor(ctx, j.dump(), pk, o), "tampered meeting_node rejected"); json j2 = json::parse(d); j2["enc"] = "00000000000000000000000000000000000000000000000000000000deadbeef"; CHECK(!btf::VerifyDescriptor(ctx, j2.dump(), pk, o), "tampered enc rejected"); + + std::string d3 = btf::SignDescriptor(ctx, sk, ENC_HEX, "node-1", 5, ONION); + json j3 = json::parse(d3); + j3["onion"] = "bcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcde.onion:8433"; + CHECK(btf::VerifyDescriptor(ctx, j3.dump(), pk, o) && o.onion.empty(), + "tampered onion ignored rather than trusted"); + json j4 = json::parse(d3); + j4["sig3"] = std::string(128, '0'); + CHECK(btf::VerifyDescriptor(ctx, j4.dump(), pk, o) && o.onion.empty(), + "bad onion signature ignored rather than trusted"); } printf("full_resolve_chain_from_address\n"); -- cgit v1.2.3 From 3fe9280fc11bc4ceaff3bb21533224b7b3e88da7 Mon Sep 17 00:00:00 2001 From: bitflash-maintainer Date: Wed, 26 Aug 2026 22:43:41 +0000 Subject: btfaddr: reject descriptors whose onion endpoint is not signed Upstream 1.2.19 signs the onion endpoint only under the optional sig3, and VerifyDescriptor treated sig3 failure as 'drop the onion, accept the rest'. Any relay could therefore strip an onion endpoint down to a rendezvous-only descriptor (or, under /oniononly, cut the peer off) by deleting one field. Now an onion field must arrive with a valid sig3 over the V3 digest or the whole descriptor is rejected. Honest 1.2.19 writers always emit both fields, so interop is preserved. The full two-field strip still verifies -- it is indistinguishable from a peer that never had an onion -- and needs the onion bound into the primary sig, which only upstream can do without breaking every 1.2.18/1.2.19 verifier; reported as an upstream protocol defect. test_btfaddr flips the two upstream checks that enshrined the soft drop and adds unsigned-onion and full-strip cases. --- src/btfaddr.cpp | 40 ++++++++++++++++++++++++++-------------- src/test_btfaddr.cpp | 19 +++++++++++++++---- 2 files changed, 41 insertions(+), 18 deletions(-) (limited to 'src/test_btfaddr.cpp') diff --git a/src/btfaddr.cpp b/src/btfaddr.cpp index ce2ac86..502220e 100644 --- a/src/btfaddr.cpp +++ b/src/btfaddr.cpp @@ -319,20 +319,32 @@ bool VerifyDescriptor(void* ctxv, const std::string& jsonStr, std::string onion; if (v.contains("onion")) { - if (v["onion"].is_string() && v.contains("sig3") && v["sig3"].is_string()) - { - std::string onionNorm; - std::string onionRaw = v["onion"].get(); - if (NormalizeOnionEndpoint(onionRaw, onionNorm) && onionNorm == onionRaw) - { - unsigned char sig3[64]; - unsigned char digest3[32]; - DescriptorDigestV3(expect_pubkey, enc, meeting_node, onionNorm, created, digest3); - if (HexDecode(v["sig3"].get(), sig3, 64) && - secp256k1_schnorrsig_verify(ctx, sig3, digest3, 32, &xpub)) - onion = onionNorm; - } - } + // A descriptor that carries an onion endpoint must prove it. The + // endpoint is covered by sig3 and only sig3, so any failure here -- + // missing sig3, bad hex, unnormalised endpoint, bad signature -- + // means the descriptor was tampered with, and a tampered + // descriptor is rejected outright. Upstream dropped just the onion + // and accepted the rest, which let any relay convert an onion + // descriptor into a rendezvous-only one by deleting a field. + // + // Residual, by design: removing BOTH "onion" and "sig3" still + // verifies, because the result is indistinguishable from a peer + // that never had an onion endpoint. Closing that requires binding + // the onion into the primary sig (the V2 digest), which every + // upstream 1.2.18/1.2.19 verifier would reject -- an upstream + // protocol change, not something this fork can do unilaterally. + if (!v["onion"].is_string()) return false; + if (!v.contains("sig3") || !v["sig3"].is_string()) return false; + std::string onionNorm; + std::string onionRaw = v["onion"].get(); + if (!NormalizeOnionEndpoint(onionRaw, onionNorm) || onionNorm != onionRaw) + return false; + unsigned char sig3[64]; + unsigned char digest3[32]; + DescriptorDigestV3(expect_pubkey, enc, meeting_node, onionNorm, created, digest3); + if (!HexDecode(v["sig3"].get(), sig3, 64)) return false; + if (!secp256k1_schnorrsig_verify(ctx, sig3, digest3, 32, &xpub)) return false; + onion = onionNorm; } memcpy(out.pubkey, expect_pubkey, 32); diff --git a/src/test_btfaddr.cpp b/src/test_btfaddr.cpp index 8de426e..9d33d63 100644 --- a/src/test_btfaddr.cpp +++ b/src/test_btfaddr.cpp @@ -133,12 +133,23 @@ int main() std::string d3 = btf::SignDescriptor(ctx, sk, ENC_HEX, "node-1", 5, ONION); json j3 = json::parse(d3); j3["onion"] = "bcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcde.onion:8433"; - CHECK(btf::VerifyDescriptor(ctx, j3.dump(), pk, o) && o.onion.empty(), - "tampered onion ignored rather than trusted"); + CHECK(!btf::VerifyDescriptor(ctx, j3.dump(), pk, o), + "tampered onion rejects the descriptor"); json j4 = json::parse(d3); j4["sig3"] = std::string(128, '0'); - CHECK(btf::VerifyDescriptor(ctx, j4.dump(), pk, o) && o.onion.empty(), - "bad onion signature ignored rather than trusted"); + CHECK(!btf::VerifyDescriptor(ctx, j4.dump(), pk, o), + "bad onion signature rejects the descriptor"); + json j5 = json::parse(d3); + j5.erase("sig3"); + CHECK(!btf::VerifyDescriptor(ctx, j5.dump(), pk, o), + "unsigned onion rejects the descriptor"); + // Removing both fields still verifies: the result is indistinguishable + // from a peer that never had an onion endpoint. That residual strip + // needs the onion bound into the primary sig, an upstream change. + json j6 = json::parse(d3); + j6.erase("onion"); j6.erase("sig3"); + CHECK(btf::VerifyDescriptor(ctx, j6.dump(), pk, o) && o.onion.empty(), + "full strip indistinguishable from no-onion (documented residual)"); } printf("full_resolve_chain_from_address\n"); -- cgit v1.2.3