diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 213c5b4..0c0d497 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -60,15 +60,15 @@ behind the general rule. | COMP-050 | Go wallet-wire processors return malformed requests as transport errors and pass the originator to each wallet method; `@bsv/sdk` 4.1.1 answers every failure in-band. | Swift provides bounded transport-neutral processors and transceivers with a required originator authorizer. Every processor failure, including unknown calls and malformed requests, is an error frame with the TypeScript message. | A TypeScript transceiver must see an error frame, not a dead transport, and must be able to fall back after the call-29 probe. See [COMP-050](Rulings/COMP-050-Wallet-Wire-Substrates.md). | | COMP-051 | Go's interpreter debugger stores mutable callback lists and clones mutable VM state; its declared rewind option is unimplemented. | Swift uses an opt-in bounded immutable `Sendable` event stream, redacts descriptions/reflection, and omits rewind. | Preserves deterministic lifecycle observability without exposing mutable execution state or creating callback races. | | COMP-052 | Pinned Go auth accepts variable nonce lengths, can lose random-source failures, authenticates an unsigned initial request, and does not enforce the expected peer identity. BRC-103 uses version `0.1`, while some BRC-104 material shows `1.0`. | Swift emits and accepts BRC-103 version `0.1`, accepts 32-byte nonces and the exact 48-byte Go form, propagates random failures, binds the expected peer, and authenticates a responder only after a signed general message. The transport-neutral BRC-104 payload has no separate version field. | Canonical shared messages and payloads remain interoperable. Strict JSON, low-S DER, replay checks, cancellation, session limits, and payload limits prevent the pinned defects and ambiguous input from entering session state. | -| COMP-053 | Go combines overlay values with HTTP facilitators, mutable resolver defaults, wallet-backed admin tokens, and `any`-typed lookup values. | `BSVOverlay` provides only bounded SHIP/SLAP values and transport-neutral async facilitator protocols with typed byte payloads. | Preserves useful Go vocabulary without accepting unbounded data, hidden network policy, or mutable or erased result state. | +| COMP-053 | Go combines overlay values with HTTP facilitators, mutable resolver defaults, wallet-backed admin tokens, and `any`-typed lookup values. | `BSVOverlay` provides only bounded SHIP/SLAP values and transport-neutral async facilitator protocols with typed byte payloads. Topic and service names follow the `@bsv/sdk` 4.1.1 grammar, and lookup outputs carry the optional TS `context` and `txid`. | Preserves useful Go vocabulary without accepting unbounded data, hidden network policy, or mutable or erased result state. | | COMP-054 | Pinned Go identity creates fallback wallets and concrete network broadcasters, discards a disclosure verifier secret, emits raw key bytes as display text, and exports an accepting verifier. TypeScript 4.1.1 and `tm_identity` require `[1,"identity"]` and the fixed "anyone" verifier. | `BSVIdentity` requires typed wallet, broadcaster, and bounded limits; proves to the "anyone" verifier; locks under `[1,"identity"]` by default; emits canonical compressed-key hex; verifies certificates; and checks the proved keyring exactly. | Produces tokens TypeScript overlay hosts admit, without copying unsafe capability and encoding defects. | | COMP-055 | Pinned Go registry combines mutable clients, factory setters, default network state, wallet orchestration, HTTP overlay discovery, and an open definition interface. TypeScript 4.1.1 tokens carry an operator signature and use level-1 protocols. | `BSVRegistry` provides bounded immutable definition values, the TypeScript signed 7/7/8-field PushDrop codec with operator key linkage, typed records and queries, plus narrow `Sendable` lookup and publisher boundaries. | Reads and writes the tokens TypeScript hosts admit without hidden transport, wallet orchestration, persistence, mutable state, or erased values. | | COMP-056 | Pinned Go KVStore combines PushDrop token encoding with wallet actions, BEEF state resolution, encryption, mutable local state, and undocumented output ordering. Go writes one field; TypeScript 4.1.1 `LocalKVStore` requires two (value and signature). | `BSVKVStore` provides bounded immutable two-field signed tokens and locators in the lock-before layout, with wallet signing and owner-key checks. | Matches the token TypeScript reads without claiming storage, ordering, encryption, persistence, or transport semantics. | | COMP-057 | Pinned Go storage combines UHRP value conversion with unbounded overlay resolution, downloader HTTP, authenticated upload APIs, mutable HTTP clients, and type-erased service data. | `BSVStorage` provides bounded UHRP identifiers, content values, signed host-advertisement decoding, and a narrow `Sendable` content-provider boundary. | Preserves the UHRP Base58Check and SHA-256 format and the TypeScript advertisement layout without embedding HTTP policy, discovery, wallet authority, persistence, or erased response state. | -| COMP-058 | Pinned Go treats an overlay administration token as a mutable wallet template, accepts surplus or malformed data fields, and does not verify its appended signature before discovery uses it. | `BSVOverlay` decodes only bounded, exact signed `beforeCompatibility` PushDrop advertisements and verifies the signature against the locking key. Wallet construction and spending remain separate. | Preserves signed SHIP/SLAP advertisement data without importing wallet orchestration, default resolvers, HTTP policy, or mutable factories. | +| COMP-058 | Pinned Go treats an overlay administration token as a mutable wallet template, accepts surplus or malformed data fields, and does not verify its appended signature before discovery uses it. | `BSVOverlay` decodes only bounded, exact signed `beforeCompatibility` PushDrop advertisements and verifies the signature against the locking key, which must be the identity's BRC-42 SHIP or SLAP child as in `@bsv/sdk` 4.1.1. URI, field-size, and DER rules also match TS. Wallet construction and spending remain separate. | Preserves signed SHIP/SLAP advertisement data without importing wallet orchestration, default resolvers, HTTP policy, or mutable factories. | | COMP-059 | Pinned Go joins BRC-104 HTTP framing to concrete clients, callback state, unauthenticated fallback, and automatic payment. | Swift provides a bounded transport-neutral HTTP frame codec for signed general messages. It requires canonical authentication headers and exact request-ID correlation. | Preserves the authenticated HTTP wire fields without selecting endpoint, retry, fallback, payment, or persistence policy. The unsigned requested-certificate header remains rejected; signed exchange uses COMP-060. | | COMP-060 | Pinned Go certificate exchange does not enforce requested field or type completeness, does not correlate a response with one pending request, and carries an unsigned requested-certificate HTTP header. | Swift provides bounded typed post-authentication certificate requests and responses. It signs canonical request or response JSON, correlates one exact pending request, and requires separate BRC-52 certificate validation. The HTTP header remains rejected. | Canonical signed BRC-103 messages remain compatible. Swift does not accept missing disclosures, unsolicited responses, or unsigned HTTP certificate requests. | -| COMP-061 | Pinned Go overlay HTTP and policy use unbounded response reads, unsafe binary counts and indexes, default trackers, unbounded fan-out, and scheduler-dependent result order. | Swift places bounded HTTPS facilitators in `BSVNetwork` and deterministic resolver and one-shot broadcaster policy in `BSVOverlay`. All hosts and limits are explicit, discovery verifies signed tokens, and failed submission has uncertain delivery. | Preserves canonical SHIP and SLAP requests and results without hidden network policy, unsafe retry, unbounded work, or nondeterministic aggregation. | +| COMP-061 | Pinned Go overlay HTTP and policy use unbounded response reads, unsafe binary counts and indexes, default trackers, unbounded fan-out, and scheduler-dependent result order. | Swift places bounded HTTPS facilitators in `BSVNetwork` and deterministic resolver and one-shot broadcaster policy in `BSVOverlay`. All hosts and limits are explicit, discovery verifies signed tokens, and failed submission has uncertain delivery. The wire formats (aggregated answers, JSON outputs, camelCase STEAK, comma-separated topics, off-chain values, any 2xx) and per-host topics follow `@bsv/sdk` 4.1.1 hosts. | Preserves canonical SHIP and SLAP requests and results without hidden network policy, unsafe retry, unbounded work, or nondeterministic aggregation. | | COMP-062 | Pinned Go provides one concrete UHRP downloader with internal resolver, tracker, and HTTP policy. | Swift keeps UHRP values in `BSVStorage` and places the injected resolver and bounded HTTPS downloader in `BSVNetwork`. It authenticates the signed six-field TypeScript advertisement, binds it to the requested hash, sorts hosts, makes one GET per host, and verifies the SHA-256 result. | Preserves the TypeScript `ls_uhrp` query and advertisement layout without hidden trackers, cleartext hosts, unbounded bodies, automatic retry, or mutable network policy. | | COMP-063 | BRC-157 composes BIP-39, BIP-32, and BRC-140 without storage, transport, or a concrete wallet implementation. Go and TypeScript expose the constituent behavior from their SDK packages. | Swift places the composed entropy-backup and hardened-profile API in opt-in `BSVCompat`, which already owns BIP-39 and BIP-32 and depends on `BSVKeys` for BRC-140. It remains outside the modern `BSV` umbrella. | Keeps the reusable backup primitive in the SDK while preserving the explicit compatibility boundary required by BIP-39 and BIP-32. Toolbox wallets may consume it without owning or duplicating the primitive. | | COMP-064 | The interpreter was pinned to Go v1.3.3. TypeScript `@bsv/sdk` 4.1.1 and Go disagree with it on Chronicle splice operands, numeric shifts, the Chronicle number limit (32,000,000 bytes, not 32 MiB), `SIGHASH_CHRONICLE`, malleability relaxation for transaction version above 1, alt-stack clearing, signature and public-key checks, structural-only DER, and the bound on arithmetic results. | Swift follows SV Node v1.2.3 for all of them. It adds `ScriptVerificationFlags.chronicle`, implied by the `.afterChronicle` era, and the consensus failures `illegalChronicle` and `scriptNumberOverflow`. | Script validity is consensus, so the node decides. With `.enableForkID` a signature without the ForkID bit is rejected, and callers must pass `.chronicle` themselves for older outputs spent after Chronicle activation. Where Go differs, Swift no longer matches Go. `NodeConformanceRegressionTests` runs all 21 TypeScript node vectors and a test per rule. See [COMP-064](Rulings/COMP-064-Interpreter-Node-Chronicle-Rules.md). | diff --git a/Documentation/Compatibility/Rulings/COMP-053-Overlay-Core.md b/Documentation/Compatibility/Rulings/COMP-053-Overlay-Core.md index d4cf7cd..568c8dc 100644 --- a/Documentation/Compatibility/Rulings/COMP-053-Overlay-Core.md +++ b/Documentation/Compatibility/Rulings/COMP-053-Overlay-Core.md @@ -29,3 +29,16 @@ limit. This core packet added no wire codec. COMP-061 adds the bounded HTTP formats, deterministic resolver, and one-shot broadcaster without changing these core value rules. + +## @bsv/sdk 4.1.1 alignment + +Live overlay hosts run `@bsv/sdk` 4.1.1 (ts-stack `3b1abc569`). These core rules +now follow it: + +- Topic and service names use the `@bsv/sdk` grammar (`overlay-tools/OverlayNames.ts`): + `tm_` or `ls_`, then lowercase ASCII letters and digits in segments joined by + single underscores, 256 bytes at most. The earlier rule allowed uppercase, + repeated or trailing underscores, and longer names that TS hosts reject. +- A lookup output may carry the optional `context` bytes and `txid` that TS + hosts return. `OverlayLimits.maximumLookupContextByteCount` (1 MiB by default) + bounds each context, and the aggregate answer limit counts context bytes. diff --git a/Documentation/Compatibility/Rulings/COMP-058-Overlay-Admin-Token-Verification.md b/Documentation/Compatibility/Rulings/COMP-058-Overlay-Admin-Token-Verification.md index 7c93153..eb4b47f 100644 --- a/Documentation/Compatibility/Rulings/COMP-058-Overlay-Admin-Token-Verification.md +++ b/Documentation/Compatibility/Rulings/COMP-058-Overlay-Admin-Token-Verification.md @@ -21,3 +21,42 @@ Swift does not select HTTP endpoints, trackers, retry policy, resolver hosts, or a wallet capability. It also does not provide a partial unsigned token constructor. Later construction and spending work must use explicit wallet capabilities and preserve the verified four-field signing payload. + +## @bsv/sdk 4.1.1 alignment + +Verification now matches `OverlayAdminTokenTemplate.ts:159-222`, which is what +live discovery applies: + +- The PushDrop locking key must be the BRC-42 child of the advertised identity + key for invoice `2-service host interconnect-1` (SHIP) or + `2-service lookup availability-1` (SLAP), with the "anyone" key (scalar 1) + as counterparty. The signature must verify under that derived key. A key that + is not derived from the identity no longer authenticates the identity, so a + forged advertisement cannot claim another operator's identity. A correctly + signed token whose locking key belongs to another identity throws + `unlinkedLockingKey`. Legacy advertisements signed with a self-derived key + fail with `invalidSignature`, as they do in TS. +- The identity key must be canonical compressed (`02` or `03`). +- Each field is at most 4096 bytes and all five together at most 8192 bytes. +- The signature field is 8 to 80 bytes of canonical DER. +- The host field must be an advertisement URI TS accepts: an `https`, + `https+bsvauth`, `https+bsvauth+smf`, `https+bsvauth+scrypt-offchain` or + `https+rtt` origin, a `wss` URL, or a `js8c+bsvauth+smf` coordinate URI. + Localhost, punycode labels, credentials, fragments, and control characters + are rejected. +- Hosts are parsed as the WHATWG URL parser in TS parses them. A host that + ends in a number must be a valid IPv4 address in one of the WHATWG forms + (`2130706433`, `0x7f.1`, `1.2.3`, octal parts), and is written as a dotted + quad, so `https://2130706433/` is the origin `https://127.0.0.1`. Hosts such + as `1.2.3.4.5`, `256.1.1.1` and `a.b.c.1` are rejected. Bracketed IPv6 hosts + are validated and written in canonical form (`[0:0:0:0:0:0:0:1]` is `[::1]`). + Before this, Swift kept those hosts as written, so one address under two + spellings was two hosts, and malformed IP hosts that TS rejects were accepted. +- Swift accepts nothing TS rejects. It rejects a few forms the WHATWG parser + repairs and no advertisement writer emits: percent-encoded or non-ASCII host + text (TS applies IDNA), any `@` in the authority, backslashes, dot segments + or other text in a path that must be `/`, extra slashes after the scheme, and + leading or trailing spaces. + +Discovery (COMP-061) also requires the advertising output to hold exactly one +satoshi, as `LookupResolver.ts` and `SHIPBroadcaster.ts` do. diff --git a/Documentation/Compatibility/Rulings/COMP-061-Overlay-HTTP-and-Policy.md b/Documentation/Compatibility/Rulings/COMP-061-Overlay-HTTP-and-Policy.md index f8691fd..c12c6b8 100644 --- a/Documentation/Compatibility/Rulings/COMP-061-Overlay-HTTP-and-Policy.md +++ b/Documentation/Compatibility/Rulings/COMP-061-Overlay-HTTP-and-Policy.md @@ -5,20 +5,134 @@ unbounded fan-out, scheduler-dependent aggregation, and a transaction object that retains its full source-transaction graph. `BSVNetwork` provides bounded HTTPS lookup and topic facilitators. They require -an absolute HTTPS origin without credentials, path, query, fragment, or a -trailing slash. Lookup accepts only strict bounded JSON or aggregated BEEF. -Topic submission is one POST. A transport failure or cancellation after that -POST begins has uncertain delivery and is not retried. +an absolute HTTPS origin without credentials, path, query, or fragment; a +single trailing slash is accepted, as in `@bsv/sdk`. Lookup accepts bounded +JSON or aggregated BEEF. Topic submission is one POST. A transport failure or +cancellation after that POST begins has uncertain delivery and is not retried. `BSVOverlay` provides an immutable `LookupResolver`. Callers supply all trackers, overrides, additional hosts, limits, and transport. The resolver deduplicates and sorts hosts, caps host count and concurrent work, verifies signed SLAP advertisements, selects the first freeform answer in sorted host -order, and sorts merged output keys by transaction ID and output index. It -rejects mixed answer representations. +order, and sorts merged output keys by transaction ID and output index. When +hosts answer with both representations, the output lists win. `OverlayTopicBroadcaster` accepts caller-supplied Atomic BEEF because the Swift transaction value does not retain a full ancestor graph. It verifies signed -SHIP advertisements, submits once to each sorted interested host, and applies -explicit acknowledgment rules. It does not add default hosts, wallet behavior, -persistence, automatic retry, or a partial transaction-to-BEEF conversion. +SHIP advertisements, submits once to each sorted interested host with the +topics that host advertised, and applies explicit acknowledgment rules. It does +not add default hosts, wallet behavior, persistence, automatic retry, or a +partial transaction-to-BEEF conversion. + +## @bsv/sdk 4.1.1 wire alignment + +Live overlay hosts run `@bsv/sdk` 4.1.1 and Overlay Express (ts-stack +`3b1abc569`). Where the earlier rules differed on the wire, Swift now follows +the TS hosts: + +- **Aggregated lookup answers.** The octet-stream answer holds many outputs and + one shared BEEF. Swift used to give every output the shared BEEF, so a reader + that took its last transaction saw one transaction for every outpoint. Each + output now gets Atomic BEEF for its own transaction, selected the way + `Beef.toBinaryAtomic` does (`LookupResolver.ts:880-935`), plus its + `transactionID` and `context`. When the shared BEEF lacks part of that + transaction's ancestry, the output keeps the shared BEEF and its + `transactionID` names the subject. Any other failure to build the Atomic + BEEF fails the answer. Merkle paths are kept and renumbered as TS does: those + the selected records reference, in first-reference order. Swift reads that + order from its parents-first records and TS from the order the records + arrived in, so when a sender lists a child before its parents the two can + write the same paths in a different order; both envelopes are valid. + Atomic BEEF for a chain of unproven transactions grows with the chain, so + the bytes generated and handed out are counted as they are built and the + answer fails with `resourceLimit` once either passes the answer limit, as + `extractAtomicOutputs` does (`LookupResolver.ts:917-938`). +- **Reading an output.** `OutputListItem.transaction(beefLimits:)` is public, so + callers read the transaction an output belongs to the way the resolver does: + the `transactionID` when present, else the Atomic BEEF subject, else the last + transaction. +- **JSON answers.** `beef` may be a byte array (what `res.json` sends), an + object with numeric keys, or canonical base64. Outputs may carry `context` + (byte array) and `txid`; unknown keys are ignored. A null or missing + `outputs` still reads as empty for Go hosts. Output lists are read straight + from the bytes, so a byte array costs one byte per element rather than one + boxed number; `JSONSerialization` is used only for a freeform `result`, whose + text may be at most twice the freeform limit. +- **STEAK.** The camelCase keys TS hosts send (`outputsToAdmit`, + `coinsToRetain`, optional `coinsRemoved`) are read, as is Go's PascalCase. + A STEAK naming a topic that was not submitted is malformed. So is an + instruction object with no keys: `validateSTEAK` requires `outputsToAdmit` + and `coinsToRetain` (`SHIPBroadcaster.ts:255-256`), and Go always writes + every field, so the host counts as failed. +- **Submission.** `X-Topics` is comma-separated, as `SHIPBroadcaster.ts` sends + and Overlay Express reads. Off-chain values are sent, not dropped: header + `x-includes-off-chain-values: true` and body `varint(beef length) || beef || + offChainValues` (`SHIPBroadcaster.ts:331-372`). +- **Status and content type.** Any 2xx status is success, and every response + that is not `application/octet-stream` is parsed as JSON, as `response.ok` + and `response.json()` do in TS. Body size limits still apply first. +- **Per-host topics.** Each SHIP host is sent only the topics it advertised + (`SHIPBroadcaster.ts:468-482`). +- **Acknowledgment.** Requirements follow `SHIPBroadcaster.ts:466-545`. By + default some host must acknowledge every topic and other hosts may fail, so + one bogus one-satoshi advertisement no longer fails every broadcast. A host + whose submission fails, whose STEAK is empty, or that acknowledges a topic it + was not sent counts as acknowledging nothing; a requirement on every host or + on that host then fails. An unmet requirement throws `acknowledgmentFailed` + when every host answered and `uncertainDelivery` when a host failed, since + that host may have admitted the transaction. `broadcastDetailed` reports each + host's acknowledged topics and each failure with its error. Hosts past the + host limit are left out, as TS stops at its host cap, instead of failing; + hosts named in `acknowledgmentByHost` always keep their places, and + `OverlayBroadcastReport.skippedHostCount` counts the rest. A named host + that discovery did not return fails its requirement, even `.none`, as in + `SHIPBroadcaster.ts:659-662`. Acknowledgment-policy keys that are not + `https://` origins are rejected when the broadcaster is made, since no + discovered host could match them. +- **Lookup host limit.** SLAP discovery shares the host limit as TS does. + Caller hosts keep their places. Each tracker may name at most an equal + share of the rest (`LookupDiscovery.ts:107-110`), and hosts are then taken + from the trackers in turn (`LookupHostQueue.ts:47-59`), so one tracker or + one flood of advertisements cannot fill every place. + `LookupResolution.skippedHostCount` counts hosts left out, and + `trackerFailures` lists trackers that failed while another answered. Hosts a + caller lists directly still throw `limitExceeded` past the limit, as TS + throws for more than 32. +- **Host normalization.** Discovered hosts, caller-supplied resolver hosts that + are `https://` origins, and acknowledgment-policy keys are normalized to the + origin TS requests (canonical host, no default port, no trailing slash), so + `https://a.example/` and `https://a.example` are one host. One origin twice + in a caller list is a duplicate, as in TS (`LookupResolver.ts:551-568`). + Advertisements that are not HTTPS origins are skipped. +- **Discovered hosts must be public.** By default (`discoveredHostPolicy: + .publicNetworkOnly`) discovery skips an advertised host that is a loopback, + private, link-local, shared, multicast or reserved IPv4 or IPv6 address, or + `localhost`, `.localhost`, `.local`, `.internal` or `.home.arpa` once a + trailing dot is removed. A domain with any other empty label, or made only + of digits and dots, is refused too (`PublicHTTPSFetch.ts:201-204`). Anyone + can publish a one-satoshi advertisement, and TS refuses such addresses in + `createPublicNetworkFetch` (`storage/PublicHTTPSFetch.ts:114-158`). + `.anyHTTPSOrigin` turns the filter off for private deployments. + Caller-supplied hosts are never filtered. +- **Known gap: DNS answers.** On Node, TS also resolves each name, refuses a + private answer and connects to the address it checked + (`PublicHTTPSFetch.ts:262-271`). Swift checks only the advertised text: the + `URLSession` transport resolves names itself and cannot be pinned to a + checked address, and a check before the request would leave the answer + free to change in between. An advertised domain that resolves to a private + address is therefore still contacted. TLS limits that to a connection + attempt whose certificate must match the advertised name, and the + transport refuses every redirect. +- **Bad outputs.** An output whose transaction cannot be read, whose `txid` + disagrees with its BEEF, or whose index is out of range is left out, as TS + does, instead of failing the lookup. `resolveDetailed` reports each such + output and each failed host with its error. `resolve` throws + `invalidLookupOutput` only when hosts returned outputs and none was usable. +- **Mixed answers.** Output lists win over freeform answers, as in + `LookupResolver.ts:1508-1528`. `inconsistentAnswerTypes` is no longer thrown. + When every host fails, Swift still throws `noSuccessfulResponses` instead of + returning an empty list as TS does: an empty list would hide that no host + answered. When every answer is freeform, the first in sorted host order is + returned, as before. +- **Context size.** The per-output context default is 1 MiB, the TS ceiling, + where it was 64 KiB. diff --git a/Sources/BSVNetwork/Overlay/OverlayHTTP.swift b/Sources/BSVNetwork/Overlay/OverlayHTTP.swift index d5a7df0..3549385 100644 --- a/Sources/BSVNetwork/Overlay/OverlayHTTP.swift +++ b/Sources/BSVNetwork/Overlay/OverlayHTTP.swift @@ -11,16 +11,61 @@ public struct OverlayHTTPConfiguration: Sendable { public let overlayLimits: OverlayLimits public let beefLimits: BEEFLimits - public let maximumContextByteCount: Int public let requestTimeout: Duration public let resourceTimeout: Duration + private let contextByteLimit: Int + /// The largest `context` accepted for one lookup output. + @available(*, deprecated, message: "Use OverlayLimits.maximumLookupContextByteCount.") + public var maximumContextByteCount: Int { contextByteLimit } + + /// The per-output context limit: `OverlayLimits.maximumLookupContextByteCount`, + /// or the deprecated `maximumContextByteCount` when that is smaller. + var lookupContextByteLimit: Int { + min(contextByteLimit, overlayLimits.maximumLookupContextByteCount) + } + + public init( + overlayLimits: OverlayLimits = .standard, + beefLimits: BEEFLimits, + requestTimeout: Duration = .seconds(30), + resourceTimeout: Duration = .seconds(30) + ) throws { + try self.init( + overlayLimits: overlayLimits, + beefLimits: beefLimits, + contextByteLimit: Self.maximumAllowedContextByteCount, + requestTimeout: requestTimeout, + resourceTimeout: resourceTimeout + ) + } + + @available( + *, deprecated, + message: "Set OverlayLimits.maximumLookupContextByteCount instead of maximumContextByteCount." + ) public init( overlayLimits: OverlayLimits = .standard, beefLimits: BEEFLimits, - maximumContextByteCount: Int = 64 * 1_024, + maximumContextByteCount: Int, requestTimeout: Duration = .seconds(30), resourceTimeout: Duration = .seconds(30) + ) throws { + try self.init( + overlayLimits: overlayLimits, + beefLimits: beefLimits, + contextByteLimit: maximumContextByteCount, + requestTimeout: requestTimeout, + resourceTimeout: resourceTimeout + ) + } + + private init( + overlayLimits: OverlayLimits, + beefLimits: BEEFLimits, + contextByteLimit: Int, + requestTimeout: Duration, + resourceTimeout: Duration ) throws { guard overlayLimits.maximumLookupQueryByteCount @@ -29,7 +74,7 @@ public struct OverlayHTTPConfiguration: Sendable { <= Self.maximumAllowedRequestByteCount, overlayLimits.maximumLookupAnswerByteCount <= Self.maximumAllowedResponseByteCount, - (0...Self.maximumAllowedContextByteCount).contains(maximumContextByteCount), + (0...Self.maximumAllowedContextByteCount).contains(contextByteLimit), requestTimeout > .zero, resourceTimeout > .zero else { @@ -37,7 +82,7 @@ public struct OverlayHTTPConfiguration: Sendable { } self.overlayLimits = overlayLimits self.beefLimits = beefLimits - self.maximumContextByteCount = maximumContextByteCount + self.contextByteLimit = contextByteLimit self.requestTimeout = requestTimeout self.resourceTimeout = resourceTimeout } @@ -108,41 +153,31 @@ public struct HTTPSOverlayLookupFacilitator: LookupFacilitator, Sendable { throw CancellationError() } catch NetworkServiceError.cancelled { throw CancellationError() - } catch NetworkServiceError.responseBodyTooLarge { - throw OverlayHTTPError.resourceLimit + } catch let error as NetworkServiceError { + NetworkLog.failure("HTTPSOverlayLookupFacilitator.lookup", request: request, underlying: error) + if case .responseBodyTooLarge = error { throw OverlayHTTPError.resourceLimit } + throw OverlayHTTPError.transport } catch { NetworkLog.failure("HTTPSOverlayLookupFacilitator.lookup", request: request, underlying: error) throw OverlayHTTPError.transport } try Task.checkCancellation() - guard response.statusCode == 200 else { + // `@bsv/sdk` accepts any 2xx and reads every answer that is not + // `application/octet-stream` as JSON (`LookupResolver.ts:815-872`). + guard (200...299).contains(response.statusCode) else { throw overlayRejection("HTTPSOverlayLookupFacilitator.lookup", request: request, response: response) } let bytes = [UInt8](response.body) - switch mediaType(response.headerValue(for: "Content-Type")) { - case "application/json": - return try loggingUnreadable("HTTPSOverlayLookupFacilitator.lookup", request, response) { - try OverlayHTTPCodec.lookupJSONResponse( - bytes, - limits: configuration.overlayLimits - ) - } - case "application/octet-stream": + if mediaType(response.headerValue(for: "Content-Type")) == "application/octet-stream" { return try loggingUnreadable("HTTPSOverlayLookupFacilitator.lookup", request, response) { try OverlayHTTPCodec.lookupBinaryResponse( bytes, configuration: configuration ) } - default: - NetworkLog.failure( - "HTTPSOverlayLookupFacilitator.lookup", - request: request, - statusCode: response.statusCode, - body: response.body, - reason: "unsupported Content-Type \(response.headerValue(for: "Content-Type") ?? "none")" - ) - throw OverlayHTTPError.unsupportedContentType + } + return try loggingUnreadable("HTTPSOverlayLookupFacilitator.lookup", request, response) { + try OverlayHTTPCodec.lookupJSONResponse(bytes, configuration: configuration) } } } @@ -181,14 +216,18 @@ public struct HTTPSOverlayTopicFacilitator: TopicFacilitator, Sendable { taggedBEEF.topics, limits: configuration.overlayLimits ) + var headers = [ + "Content-Type": "application/octet-stream", + "X-Topics": topics, + ] + if !taggedBEEF.offChainValues.isEmpty { + headers["x-includes-off-chain-values"] = "true" + } let request = HTTPRequest( method: .post, url: url, - headers: [ - "Content-Type": "application/octet-stream", - "X-Topics": topics, - ], - body: Data(taggedBEEF.beef) + headers: headers, + body: Data(try OverlayHTTPCodec.submitBody(taggedBEEF)) ) let response: HTTPResponse do { @@ -202,31 +241,29 @@ public struct HTTPSOverlayTopicFacilitator: TopicFacilitator, Sendable { throw OverlayHTTPError.uncertainDelivery } guard !Task.isCancelled else { throw OverlayHTTPError.uncertainDelivery } - guard response.statusCode == 200 else { + // `@bsv/sdk` accepts any 2xx and reads the body as JSON whatever its + // content type (`SHIPBroadcaster.ts:370-371`). + guard (200...299).contains(response.statusCode) else { throw overlayRejection("HTTPSOverlayTopicFacilitator.submit", request: request, response: response) } - guard mediaType(response.headerValue(for: "Content-Type")) == "application/json" else { - NetworkLog.failure( - "HTTPSOverlayTopicFacilitator.submit", - request: request, - statusCode: response.statusCode, - body: response.body, - reason: "unsupported Content-Type \(response.headerValue(for: "Content-Type") ?? "none")" - ) - throw OverlayHTTPError.unsupportedContentType - } return try loggingUnreadable("HTTPSOverlayTopicFacilitator.submit", request, response) { - try OverlayHTTPCodec.steakResponse( + let steak = try OverlayHTTPCodec.steakResponse( [UInt8](response.body), limits: configuration.overlayLimits ) + // `validateSTEAK` rejects an acknowledgment for a topic that was not sent. + guard Set(steak.instructions.keys).isSubset(of: taggedBEEF.topics) else { + throw OverlayHTTPError.malformedResponse + } + return steak } } } +/// The endpoint URL on an `https://` origin. As in `@bsv/sdk` +/// (`canonicalOverlayEndpoint`), the host may end in one `/`. private func overlayURL(host: OverlayHost, path: String) throws -> URL { guard host.rawValue.utf8.count <= 2_048, - !host.rawValue.hasSuffix("/"), let base = URL(string: host.rawValue), let components = URLComponents(url: base, resolvingAgainstBaseURL: false), components.scheme?.lowercased() == "https", @@ -235,7 +272,7 @@ private func overlayURL(host: OverlayHost, path: String) throws -> URL { components.password == nil, components.query == nil, components.fragment == nil, - components.path.isEmpty + components.path.isEmpty || components.path == "/" else { throw OverlayHTTPError.invalidHost } @@ -252,7 +289,7 @@ private func mediaType(_ value: String?) -> String? { .lowercased() } -/// A non-200 overlay answer: logged in full once, thrown with the overlay's short reason. +/// A non-2xx overlay answer: logged in full once, thrown with the overlay's short reason. private func overlayRejection( _ operation: String, request: HTTPRequest, diff --git a/Sources/BSVNetwork/Overlay/OverlayHTTPCodec.swift b/Sources/BSVNetwork/Overlay/OverlayHTTPCodec.swift index 37bf58d..fef12e4 100644 --- a/Sources/BSVNetwork/Overlay/OverlayHTTPCodec.swift +++ b/Sources/BSVNetwork/Overlay/OverlayHTTPCodec.swift @@ -37,6 +37,8 @@ enum OverlayHTTPCodec { return result } + /// The `X-Topics` value `@bsv/sdk` sends: topic names joined by commas + /// (`SHIPBroadcaster.ts:344`). Names cannot contain a comma. static func topicsHeader( _ topics: [OverlayTopic], limits: OverlayLimits @@ -44,87 +46,100 @@ enum OverlayHTTPCodec { guard !topics.isEmpty, topics.count <= limits.maximumTopicCount else { throw OverlayHTTPError.invalidQuery } - var bytes: [UInt8] = [0x5b] - bytes.reserveCapacity(min(8_192, 2 + topics.count * 16)) - for index in topics.indices { - if index > 0 { try append([0x2c], to: &bytes, maximum: 8_192) } - try append([0x22], to: &bytes, maximum: 8_192) - try append(Array(topics[index].rawValue.utf8), to: &bytes, maximum: 8_192) - try append([0x22], to: &bytes, maximum: 8_192) - } - try append([0x5d], to: &bytes, maximum: 8_192) - guard let result = String(bytes: bytes, encoding: .utf8) else { - throw OverlayHTTPError.invalidQuery + let value = topics.map(\.rawValue).joined(separator: ",") + guard value.utf8.count <= 8_192 else { throw OverlayHTTPError.resourceLimit } + return value + } + + /// The `/submit` body. With off-chain values it is + /// `CompactSize(beef.count) || beef || offChainValues`, which `@bsv/sdk` + /// sends with `x-includes-off-chain-values: true` (`SHIPBroadcaster.ts:346-355`). + static func submitBody(_ taggedBEEF: TaggedBEEF) throws -> [UInt8] { + guard !taggedBEEF.offChainValues.isEmpty else { return taggedBEEF.beef } + let prefix = CompactSize.encode(UInt64(taggedBEEF.beef.count)) + var count = 0 + for value in [prefix.count, taggedBEEF.beef.count, taggedBEEF.offChainValues.count] { + let (next, overflow) = count.addingReportingOverflow(value) + guard !overflow, next <= OverlayHTTPConfiguration.maximumAllowedRequestByteCount + else { throw OverlayHTTPError.resourceLimit } + count = next } - return result + var body: [UInt8] = [] + body.reserveCapacity(count) + body.append(contentsOf: prefix) + body.append(contentsOf: taggedBEEF.beef) + body.append(contentsOf: taggedBEEF.offChainValues) + return body } + /// A JSON lookup answer in the `@bsv/sdk` shape (`LookupResolver.ts:43-52,327-447`). + /// + /// An output's `beef` and `context` are JSON byte arrays, or the + /// numeric-key objects `JSON.stringify(Uint8Array)` once produced. `beef` + /// may also be base64 text, the form Go overlay hosts write. `txid` names + /// the output's transaction. Unknown keys are ignored, as in `@bsv/sdk`. + /// + /// Output lists are read with ``OverlayJSONReader`` so that a byte array + /// costs one byte per element. A freeform `result` is re-encoded through + /// `JSONSerialization`, so its text may be at most twice the freeform limit. static func lookupJSONResponse( _ bytes: [UInt8], - limits: OverlayLimits + configuration: OverlayHTTPConfiguration ) throws -> LookupAnswer { - guard bytes.count <= limits.maximumLookupAnswerByteCount, - StrictOverlayJSONPreflight.accepts(bytes), - let value = try? JSONSerialization.jsonObject(with: Data(bytes)), - let object = value as? [String: Any], - let type = object["type"] as? String + let limits = configuration.overlayLimits + guard bytes.count <= limits.maximumLookupAnswerByteCount else { + throw OverlayHTTPError.resourceLimit + } + guard StrictOverlayJSONPreflight.accepts(bytes), + bytes.first(where: { ![0x20, 0x09, 0x0a, 0x0d].contains($0) }) == 0x7b else { throw OverlayHTTPError.malformedResponse } + let reader = OverlayJSONReader(bytes) + var type: String? + var outputs: Range? + var result: Range? + try reader.readObject { key in + switch key { + case "type": + guard reader.next == 0x22 else { throw OverlayHTTPError.malformedResponse } + type = try reader.readString() + case "outputs": + outputs = try reader.valueRange() + case "result": + result = try reader.valueRange() + default: + try reader.skipValue() + } + } + switch type { case "output-list": - guard Set(object.keys).isSubset(of: ["type", "outputs"]), - object["result"] == nil - else { throw OverlayHTTPError.malformedResponse } - let rawOutputs: [Any] - if object["outputs"] == nil || object["outputs"] is NSNull { - rawOutputs = [] - } else if let outputs = object["outputs"] as? [Any] { - rawOutputs = outputs - } else { - throw OverlayHTTPError.malformedResponse - } - guard rawOutputs.count <= limits.maximumLookupOutputCount else { - throw OverlayHTTPError.resourceLimit - } - var outputs: [OutputListItem] = [] - outputs.reserveCapacity(rawOutputs.count) - for raw in rawOutputs { - guard let item = raw as? [String: Any], - Set(item.keys) == ["beef", "outputIndex"], - let text = item["beef"] as? String, - let beef = try? Base64Encoding.decode( - text, - maximumDecodedByteCount: limits.maximumLookupOutputBEEFByteCount - ), - Base64Encoding.encode(beef) == text, - let index = uint32(item["outputIndex"]) - else { throw OverlayHTTPError.malformedResponse } - do { - outputs.append( - try OutputListItem( - beef: beef, - outputIndex: index, - limits: limits - ) + let items = + try outputs.map { + try lookupOutputs( + OverlayJSONReader(bytes, offset: $0.lowerBound), + configuration: configuration ) - } catch { - throw OverlayHTTPError.resourceLimit - } - } + } ?? [] do { - return try LookupAnswer(outputList: outputs, limits: limits) + return try LookupAnswer(outputList: items, limits: limits) } catch { throw OverlayHTTPError.resourceLimit } case "freeform": - guard Set(object.keys) == ["type", "result"], - let result = object["result"] - else { throw OverlayHTTPError.malformedResponse } + guard let result else { throw OverlayHTTPError.malformedResponse } + let (doubled, overflow) = limits.maximumFreeformByteCount.multipliedReportingOverflow( + by: 2) + guard overflow || result.count <= doubled else { + throw OverlayHTTPError.resourceLimit + } let encoded: Data do { + let value = try JSONSerialization.jsonObject( + with: Data(bytes[result]), options: .fragmentsAllowed) encoded = try JSONSerialization.data( - withJSONObject: result, + withJSONObject: value, options: [.fragmentsAllowed, .sortedKeys, .withoutEscapingSlashes] ) } catch { @@ -141,6 +156,92 @@ enum OverlayHTTPCodec { } } + /// The `outputs` value of a JSON output list. `null` reads as no outputs, + /// for Go hosts that marshal an empty slice that way. + private static func lookupOutputs( + _ reader: OverlayJSONReader, + configuration: OverlayHTTPConfiguration + ) throws -> [OutputListItem] { + let limits = configuration.overlayLimits + if reader.readNull() { return [] } + guard reader.next == 0x5b else { throw OverlayHTTPError.malformedResponse } + let maximumContext = configuration.lookupContextByteLimit + var outputs: [OutputListItem] = [] + try reader.readArray { + guard outputs.count < limits.maximumLookupOutputCount else { + throw OverlayHTTPError.resourceLimit + } + guard reader.next == 0x7b else { throw OverlayHTTPError.malformedResponse } + var index: UInt32? + var beef: [UInt8]? + var context: [UInt8]? + var transactionID: TransactionID? + try reader.readObject { key in + switch key { + case "outputIndex": + guard let value = try reader.readUInt32() else { + throw OverlayHTTPError.malformedResponse + } + index = value + case "beef": + beef = try beefBytes( + reader, maximum: limits.maximumLookupOutputBEEFByteCount) + case "context": + context = try reader.readByteArray(maximum: maximumContext) + case "txid": + guard reader.next == 0x22 else { throw OverlayHTTPError.malformedResponse } + let text = try reader.readString() + guard text.utf8.count == 64, + let parsed = try? TransactionID(displayHex: text.lowercased()) + else { throw OverlayHTTPError.malformedResponse } + transactionID = parsed + default: + try reader.skipValue() + } + } + guard let index, let beef, !beef.isEmpty else { + throw OverlayHTTPError.malformedResponse + } + do { + outputs.append( + try OutputListItem( + beef: beef, + outputIndex: index, + context: context, + transactionID: transactionID, + limits: limits + ) + ) + } catch { + throw OverlayHTTPError.resourceLimit + } + } + return outputs + } + + /// A lookup output's `beef`: a byte array (see + /// ``OverlayJSONReader/readByteArray(maximum:)``) or canonical base64 text. + private static func beefBytes(_ reader: OverlayJSONReader, maximum: Int) throws -> [UInt8] { + guard reader.next == 0x22 else { return try reader.readByteArray(maximum: maximum) } + let text = try reader.readString() + guard + let beef = try? Base64Encoding.decode(text, maximumDecodedByteCount: maximum), + Base64Encoding.encode(beef) == text + else { throw OverlayHTTPError.malformedResponse } + return beef + } + + /// The aggregated answer Overlay Express sends for `X-Aggregation: yes` + /// (`OverlayExpress.ts:3063-3093`): a count, then per output its display + /// transaction ID, output index and context, then one BEEF holding every + /// transaction. + /// + /// Like `parseOctetStreamLookup` and `extractAtomicOutputs` in `@bsv/sdk` + /// (`LookupResolver.ts:877-950`), each output gets its own transaction as + /// Atomic BEEF, plus its transaction ID and context. If that transaction's + /// ancestry in the shared BEEF is incomplete, so that no valid Atomic BEEF + /// can be built, the output keeps the shared BEEF and names its + /// transaction with `transactionID` instead. static func lookupBinaryResponse( _ bytes: [UInt8], configuration: OverlayHTTPConfiguration @@ -163,10 +264,11 @@ enum OverlayHTTPCodec { struct Metadata { let transactionID: TransactionID let outputIndex: UInt32 + let context: [UInt8]? } + let maximumContext = configuration.lookupContextByteLimit var metadata: [Metadata] = [] metadata.reserveCapacity(min(Int(countValue), cursor.remaining / 34)) - var aggregateContext = 0 for _ in 0.. [UInt8] { + do { + return try beef.atomicBEEF(for: subject, identifiers: identifiers, limits: limits) + .serialized(limits: limits) + } catch BEEFError.missingAncestor { + return shared + } catch { + NetworkLog.error( + "OverlayHTTPCodec.lookupBinaryResponse: Atomic BEEF for \(subject.displayHex) " + + "failed: \(type(of: error)): \(String(reflecting: error))") + switch error { + case BEEFError.envelopeTooLarge, BEEFError.serializedSizeOverflow: + throw OverlayHTTPError.resourceLimit + default: + throw OverlayHTTPError.malformedResponse + } + } + } + static func steakResponse( _ bytes: [UInt8], limits: OverlayLimits @@ -271,18 +423,46 @@ enum OverlayHTTPCodec { } catch { throw OverlayHTTPError.malformedResponse } - guard let instructionObject = rawInstructions as? [String: Any], - Set(instructionObject.keys).isSubset(of: [ - "OutputsToAdmit", "CoinsToRetain", "CoinsRemoved", "AncillaryTxids", - ]) - else { throw OverlayHTTPError.malformedResponse } - let outputs = try uint32Array(instructionObject["OutputsToAdmit"], limits: limits) - let retained = try uint32Array(instructionObject["CoinsToRetain"], limits: limits) - let removed = try uint32Array(instructionObject["CoinsRemoved"], limits: limits) - let ancillary = try transactionIDArray( - instructionObject["AncillaryTxids"], - limits: limits - ) + guard let instructionObject = rawInstructions as? [String: Any] else { + throw OverlayHTTPError.malformedResponse + } + let keys = Set(instructionObject.keys) + let outputs: [UInt32] + let retained: [UInt32] + let removed: [UInt32] + let ancillary: [TransactionID] + // An empty object is neither shape: `validateSTEAK` in `@bsv/sdk` + // requires `outputsToAdmit` and `coinsToRetain` + // (`SHIPBroadcaster.ts:255-256`), and Go's encoder always writes + // every field. TS counts the host as failed, so this does too. + guard !keys.isEmpty else { throw OverlayHTTPError.malformedResponse } + if keys.isSubset(of: ["outputsToAdmit", "coinsToRetain", "coinsRemoved"]) { + // `validateSTEAK` in `@bsv/sdk` (`SHIPBroadcaster.ts:237-262`): + // `outputsToAdmit` and `coinsToRetain` are required arrays and + // `coinsRemoved` is an optional array. + guard instructionObject["outputsToAdmit"] is [Any], + instructionObject["coinsToRetain"] is [Any], + instructionObject["coinsRemoved"] == nil + || instructionObject["coinsRemoved"] is [Any] + else { throw OverlayHTTPError.malformedResponse } + outputs = try uint32Array(instructionObject["outputsToAdmit"], limits: limits) + retained = try uint32Array(instructionObject["coinsToRetain"], limits: limits) + removed = try uint32Array(instructionObject["coinsRemoved"], limits: limits) + ancillary = [] + } else if keys.isSubset(of: [ + "OutputsToAdmit", "CoinsToRetain", "CoinsRemoved", "AncillaryTxids", + ]) { + // The Go overlay engine's untagged field names. + outputs = try uint32Array(instructionObject["OutputsToAdmit"], limits: limits) + retained = try uint32Array(instructionObject["CoinsToRetain"], limits: limits) + removed = try uint32Array(instructionObject["CoinsRemoved"], limits: limits) + ancillary = try transactionIDArray( + instructionObject["AncillaryTxids"], + limits: limits + ) + } else { + throw OverlayHTTPError.malformedResponse + } do { entries[topic] = try AdmittanceInstructions( outputsToAdmit: outputs, diff --git a/Sources/BSVNetwork/Overlay/OverlayJSONReader.swift b/Sources/BSVNetwork/Overlay/OverlayJSONReader.swift new file mode 100644 index 0000000..09f54b9 --- /dev/null +++ b/Sources/BSVNetwork/Overlay/OverlayJSONReader.swift @@ -0,0 +1,209 @@ +import Foundation + +/// A forward-only reader over JSON that ``StrictOverlayJSONPreflight`` has +/// already accepted. +/// +/// Lookup answers carry BEEF as JSON arrays of numbers. Parsing those with +/// `JSONSerialization` boxes every byte as an object, so a 64 MiB answer could +/// cost gigabytes. This reader decodes byte arrays straight into `[UInt8]`, +/// skips values it does not need without building them, and so keeps memory +/// proportional to the body. +final class OverlayJSONReader { + private let bytes: [UInt8] + private var offset = 0 + + init(_ bytes: [UInt8], offset: Int = 0) { + self.bytes = bytes + self.offset = offset + } + + /// Calls `visit` with each member name of the object at the cursor. The + /// visitor must consume the member's value. + func readObject(_ visit: (String) throws -> Void) throws { + try consume(0x7b) + skipWhitespace() + if consumeIfPresent(0x7d) { return } + while true { + let key = try readKey() + skipWhitespace() + try consume(0x3a) + skipWhitespace() + try visit(key) + skipWhitespace() + if consumeIfPresent(0x7d) { return } + try consume(0x2c) + skipWhitespace() + } + } + + /// Calls `visit` for each element of the array at the cursor. The visitor + /// must consume the element. + func readArray(_ visit: () throws -> Void) throws { + try consume(0x5b) + skipWhitespace() + if consumeIfPresent(0x5d) { return } + while true { + try visit() + skipWhitespace() + if consumeIfPresent(0x5d) { return } + try consume(0x2c) + skipWhitespace() + } + } + + /// The first byte of the value at the cursor. + var next: UInt8? { offset < bytes.count ? bytes[offset] : nil } + + func readNull() -> Bool { + let literal: [UInt8] = [0x6e, 0x75, 0x6c, 0x6c] + guard bytes.count - offset >= 4, bytes[offset..<(offset + 4)].elementsEqual(literal) + else { return false } + offset += 4 + return true + } + + /// A JSON string value, with escapes decoded. + func readString() throws -> String { + let range = try valueRange() + guard bytes[range.lowerBound] == 0x22, + let text = try? JSONSerialization.jsonObject( + with: Data(bytes[range]), options: .fragmentsAllowed) as? String + else { throw OverlayHTTPError.malformedResponse } + return text + } + + /// A JSON number that is a whole number in `0...UInt32.max`, or nil for + /// any other value. The value is consumed either way. + func readUInt32() throws -> UInt32? { + let range = try valueRange() + let token = bytes[range] + if token.count <= 3, token.allSatisfy({ (0x30...0x39).contains($0) }) { + return token.reduce(UInt32(0)) { $0 * 10 + UInt32($1 - 0x30) } + } + guard let first = token.first, first == 0x2d || (0x30...0x39).contains(first), + let number = Double(String(decoding: token, as: UTF8.self)), + number.isFinite, + number.rounded(.towardZero) == number, + number >= 0, + number <= Double(UInt32.max) + else { return nil } + return UInt32(number) + } + + /// A JSON array of integers 0...255, or an object whose keys are exactly + /// "0" through "n-1" with byte values, as `normalizeBRC100ByteArray` in + /// `@bsv/sdk` reads it (`wallet/BRC100ByteEncoding.ts:45-87,126-146`). An + /// empty object is an empty byte array there. + func readByteArray(maximum: Int) throws -> [UInt8] { + switch next { + case 0x5b: + var result: [UInt8] = [] + try readArray { + guard result.count < maximum else { throw OverlayHTTPError.resourceLimit } + guard let value = try readUInt32(), value <= 255 else { + throw OverlayHTTPError.malformedResponse + } + result.append(UInt8(value)) + } + return result + case 0x7b: + var indexes: [Int] = [] + var values: [UInt8] = [] + try readObject { key in + guard indexes.count < maximum else { throw OverlayHTTPError.resourceLimit } + guard let index = Int(key), String(index) == key, + let value = try readUInt32(), value <= 255 + else { throw OverlayHTTPError.malformedResponse } + indexes.append(index) + values.append(UInt8(value)) + } + var result = [UInt8](repeating: 0, count: indexes.count) + var seen = [Bool](repeating: false, count: indexes.count) + for (index, value) in zip(indexes, values) { + guard result.indices.contains(index), !seen[index] else { + throw OverlayHTTPError.malformedResponse + } + seen[index] = true + result[index] = value + } + return result + default: + throw OverlayHTTPError.malformedResponse + } + } + + /// Skips the value at the cursor and returns where it was. + func valueRange() throws -> Range { + let start = offset + guard let first = next else { throw OverlayHTTPError.malformedResponse } + switch first { + case 0x22: + try skipString() + case 0x7b, 0x5b: + var depth = 0 + repeat { + guard let byte = next else { throw OverlayHTTPError.malformedResponse } + switch byte { + case 0x22: + try skipString() + continue + case 0x7b, 0x5b: depth += 1 + case 0x7d, 0x5d: depth -= 1 + default: break + } + offset += 1 + } while depth > 0 + default: + while let byte = next, + !(byte == 0x2c || byte == 0x7d || byte == 0x5d || byte == 0x20 + || byte == 0x09 || byte == 0x0a || byte == 0x0d) + { + offset += 1 + } + } + guard offset > start else { throw OverlayHTTPError.malformedResponse } + return start.. String { + try consume(0x22) + let start = offset + while let byte = next, byte != 0x22 { offset += 1 } + guard next == 0x22 else { throw OverlayHTTPError.malformedResponse } + let key = String(decoding: bytes[start.. Bool { + guard next == expected else { return false } + offset += 1 + return true + } +} diff --git a/Sources/BSVOverlay/Lookup.swift b/Sources/BSVOverlay/Lookup.swift index 61b8f4f..88a7ea9 100644 --- a/Sources/BSVOverlay/Lookup.swift +++ b/Sources/BSVOverlay/Lookup.swift @@ -1,3 +1,5 @@ +import BSVCore + /// A transport-neutral lookup request with an opaque, caller-defined bounded query payload. public struct LookupQuestion: Hashable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable @@ -21,22 +23,44 @@ public struct LookupQuestion: Hashable, Sendable, CustomStringConvertible, public var customMirror: Mirror { Mirror(reflecting: description) } } +/// One output in a lookup answer, in the `@bsv/sdk` `LookupAnswer` output shape. +/// +/// `beef` holds the output's transaction, normally as Atomic BEEF. When +/// `transactionID` is present it names the transaction that holds the output, +/// and `beef` alone is not enough to find it: `beef` may be a standard BEEF +/// carrying several transactions. Use ``transaction(beefLimits:)`` to read the +/// transaction the output belongs to. +/// +/// `context` is the lookup service's optional per-output data. It is host +/// data that nothing verifies. When several hosts return the same outpoint, +/// ``LookupResolver`` keeps the first host's item, context included. public struct OutputListItem: Hashable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { public let beef: [UInt8] public let outputIndex: UInt32 + public let context: [UInt8]? + public let transactionID: TransactionID? public init( beef: [UInt8], outputIndex: UInt32, + context: [UInt8]? = nil, + transactionID: TransactionID? = nil, limits: OverlayLimits = .standard ) throws { guard !beef.isEmpty else { throw OverlayError.emptyValue(name: "beef") } try enforceOverlayByteLimit( beef, name: "lookupOutputBEEF", maximum: limits.maximumLookupOutputBEEFByteCount) + if let context { + try enforceOverlayByteLimit( + context, name: "lookupOutputContext", + maximum: limits.maximumLookupContextByteCount) + } self.beef = beef self.outputIndex = outputIndex + self.context = context + self.transactionID = transactionID } public var description: String { "" } @@ -61,7 +85,11 @@ public enum LookupAnswer: Hashable, Sendable, CustomStringConvertible, } var totalByteCount = 0 for output in outputList { - let (next, overflow) = totalByteCount.addingReportingOverflow(output.beef.count) + let (withBEEF, beefOverflow) = totalByteCount.addingReportingOverflow( + output.beef.count) + let (next, contextOverflow) = withBEEF.addingReportingOverflow( + output.context?.count ?? 0) + let overflow = beefOverflow || contextOverflow guard !overflow, next <= limits.maximumLookupAnswerByteCount else { throw OverlayError.limitExceeded( name: "lookupAnswer", diff --git a/Sources/BSVOverlay/LookupResolver.swift b/Sources/BSVOverlay/LookupResolver.swift index 928aac0..039b6b4 100644 --- a/Sources/BSVOverlay/LookupResolver.swift +++ b/Sources/BSVOverlay/LookupResolver.swift @@ -5,6 +5,7 @@ import BSVTransaction public enum OverlayPolicyError: Error, Equatable, Sendable { case noCompetentHosts case noSuccessfulResponses + /// No longer thrown: output lists win over freeform answers. case inconsistentAnswerTypes case invalidLookupOutput case discoveryResponseNotOutputList @@ -12,6 +13,8 @@ public enum OverlayPolicyError: Error, Equatable, Sendable { case invalidAtomicBEEF case uncertainDelivery case acknowledgmentFailed + /// A host's STEAK was empty or acknowledged a topic it was not sent. + case invalidSteak } /// A bounded service that resolves one overlay lookup question. @@ -19,6 +22,71 @@ public protocol OverlayLookupResolving: Sendable { func resolve(_ question: LookupQuestion) async throws -> LookupAnswer } +/// Which advertised hosts discovery may contact. +public enum OverlayDiscoveredHostPolicy: Hashable, Sendable { + /// Only hosts that may be public network endpoints: no loopback, private, + /// link-local, shared, multicast or reserved address, and no `localhost`, + /// `.local` or `.internal` name. `@bsv/sdk` applies the same address rules + /// to every request through `createPublicNetworkFetch` + /// (`storage/PublicHTTPSFetch.ts:114-158`). This is the default, because + /// anyone can publish a one-satoshi advertisement. + /// + /// Only the advertised host text is checked. Unlike `@bsv/sdk` on Node, + /// a domain is not resolved first, so one whose DNS answer is a private + /// address is still contacted; see `COMP-061`. + case publicNetworkOnly + /// Any `https://` origin, for private deployments and tests. + case anyHTTPSOrigin +} + +/// A host that gave no usable answer, with the reason, for logging. +public struct OverlayHostFailure: Sendable { + public let host: OverlayHost + public let error: any Error + + public init(host: OverlayHost, error: any Error) { + self.host = host + self.error = error + } +} + +/// An output a host returned that the resolver left out, with the reason. +public struct LookupOutputRejection: Sendable { + public let host: OverlayHost + public let output: OutputListItem + public let error: any Error + + public init(host: OverlayHost, output: OutputListItem, error: any Error) { + self.host = host + self.output = output + self.error = error + } +} + +/// A lookup result with the hosts and outputs that were left out of it. +public struct LookupResolution: Sendable { + /// The merged answer, or nil when no host gave a usable one. + public let answer: LookupAnswer? + /// Hosts whose request failed, in sorted host order. + public let hostFailures: [OverlayHostFailure] + /// Outputs left out because their transaction or output could not be read. + public let rejectedOutputs: [LookupOutputRejection] + /// SLAP trackers that failed while another tracker answered, in sorted + /// host order. + public let trackerFailures: [OverlayHostFailure] + /// Advertised hosts left out because the host limit was reached. A + /// caller that needs every advertised host can treat a nonzero count as + /// a partial lookup. + public let skippedHostCount: Int +} + +/// The hosts one lookup will ask, and what discovery left out. +private struct LookupHostSelection { + var hosts: [OverlayHost] + var trackerFailures: [OverlayHostFailure] = [] + var skippedHostCount = 0 +} + /// An immutable, bounded resolver for SHIP and SLAP lookup services. /// /// The resolver has no built-in tracker, network, or transport policy. The @@ -31,8 +99,15 @@ public struct LookupResolver: OverlayLookupResolving, Sendable { private let additionalHosts: [OverlayService: [OverlayHost]] private let beefLimits: BEEFLimits private let adminTokenLimits: OverlayAdminTokenLimits + private let discoveredHostPolicy: OverlayDiscoveredHostPolicy private let limits: OverlayLimits + /// Hosts given here that are `https://` origins are normalized as + /// discovered hosts are (lowercase host, no default port, no trailing + /// slash), so one origin is queried once. Two spellings of one origin in + /// the same list are a duplicate, as in `@bsv/sdk` (`LookupResolver.ts:551-568`). + /// Other hosts are used as given. `discoveredHostPolicy` applies only to + /// hosts found through SLAP advertisements. public init( facilitator: any LookupFacilitator, slapTrackers: [OverlayHost], @@ -40,48 +115,112 @@ public struct LookupResolver: OverlayLookupResolving, Sendable { additionalHosts: [OverlayService: [OverlayHost]] = [:], beefLimits: BEEFLimits, adminTokenLimits: OverlayAdminTokenLimits = .standard, + discoveredHostPolicy: OverlayDiscoveredHostPolicy = .publicNetworkOnly, limits: OverlayLimits = .standard ) throws { - try Self.validateHosts(slapTrackers, limits: limits) - for hosts in hostOverrides.values { + let trackers = Self.normalized(slapTrackers, limits: limits) + let overrides = hostOverrides.mapValues { Self.normalized($0, limits: limits) } + let additional = additionalHosts.mapValues { Self.normalized($0, limits: limits) } + try Self.validateHosts(trackers, limits: limits) + for hosts in overrides.values { try Self.validateHosts(hosts, limits: limits) } - for hosts in additionalHosts.values { + for hosts in additional.values { try Self.validateHosts(hosts, limits: limits) } self.facilitator = facilitator - self.slapTrackers = Self.uniqueSorted(slapTrackers) - self.hostOverrides = hostOverrides.mapValues(Self.uniqueSorted) - self.additionalHosts = additionalHosts.mapValues(Self.uniqueSorted) + self.slapTrackers = trackers.sorted() + self.hostOverrides = overrides.mapValues { $0.sorted() } + self.additionalHosts = additional.mapValues { $0.sorted() } self.beefLimits = beefLimits self.adminTokenLimits = adminTokenLimits + self.discoveredHostPolicy = discoveredHostPolicy self.limits = limits } + /// Resolves `question` and returns the merged answer. + /// + /// Throws ``OverlayPolicyError/noSuccessfulResponses`` when no host + /// answered, and ``OverlayPolicyError/invalidLookupOutput`` when hosts + /// answered only with outputs that could not be read. Use + /// ``resolveDetailed(_:)`` to see which hosts failed and why. public func resolve(_ question: LookupQuestion) async throws -> LookupAnswer { - let hosts = try await competentHosts(for: question.service) - guard !hosts.isEmpty else { throw OverlayPolicyError.noCompetentHosts } - let responses = try await query(question, at: hosts) - return try aggregate(responses) + let resolution = try await resolveDetailed(question) + guard let answer = resolution.answer else { + throw resolution.rejectedOutputs.isEmpty + ? OverlayPolicyError.noSuccessfulResponses + : OverlayPolicyError.invalidLookupOutput + } + return answer + } + + /// Resolves `question` and reports each failed host and each output left + /// out, with its reason. + /// + /// As in `@bsv/sdk`, one host's bad output does not fail the lookup: an + /// output whose transaction cannot be read from its BEEF, whose `txid` + /// disagrees with its BEEF, or whose index is out of range is left out + /// (`resolveTxIdForOutput` in `LookupResolver.ts`). The answer is nil when + /// no host answered, or when every output any host returned was left out. + public func resolveDetailed(_ question: LookupQuestion) async throws -> LookupResolution { + let selection = try await hostSelection(for: question.service) + guard !selection.hosts.isEmpty else { throw OverlayPolicyError.noCompetentHosts } + let results = try await query(question, at: selection.hosts) + var answers: [(OverlayHost, LookupAnswer)] = [] + var failures: [OverlayHostFailure] = [] + for (host, result) in results { + switch result { + case .success(let answer): answers.append((host, answer)) + case .failure(let error): failures.append(OverlayHostFailure(host: host, error: error)) + } + } + for failure in failures { OverlayLog.hostFailure("LookupResolver.resolve", failure) } + let (answer, rejected) = try aggregate(answers) + for rejection in rejected { OverlayLog.rejectedOutput("LookupResolver.resolve", rejection) } + return LookupResolution( + answer: answer, + hostFailures: failures, + rejectedOutputs: rejected, + trackerFailures: selection.trackerFailures, + skippedHostCount: selection.skippedHostCount + ) } /// Returns the explicit or discovered hosts for one lookup service. public func competentHosts(for service: OverlayService) async throws -> [OverlayHost] { - let primary: [OverlayHost] + try await hostSelection(for: service).hosts + } + + private func hostSelection(for service: OverlayService) async throws -> LookupHostSelection { + let callerHosts = additionalHosts[service] ?? [] + var selection: LookupHostSelection if service.rawValue == "ls_slap" { - primary = slapTrackers + selection = LookupHostSelection(hosts: slapTrackers) } else if let override = hostOverrides[service] { - primary = override + selection = LookupHostSelection(hosts: override) } else { - primary = try await discoverHosts(for: service) + selection = try await discoverHosts(for: service, alongside: Set(callerHosts)) } - let combined = Self.uniqueSorted(primary + (additionalHosts[service] ?? [])) - try Self.validateHosts(combined, limits: limits) - return combined + selection.hosts = Self.uniqueSorted(selection.hosts + callerHosts) + try Self.validateHosts(selection.hosts, limits: limits) + return selection } - private func discoverHosts(for service: OverlayService) async throws -> [OverlayHost] { - guard !slapTrackers.isEmpty else { return [] } + /// Asks the SLAP trackers which hosts serve `service`. + /// + /// Caller hosts in `alongside` keep their places. The rest of the host + /// limit is shared between the trackers, as in @bsv/sdk: each tracker + /// may name at most an equal share (`LookupDiscovery.ts:107-110`), and + /// hosts are then taken from the trackers in turn + /// (`LookupHostQueue.ts:47-59`) until the limit is reached. One tracker, + /// or one flood of advertisements, therefore cannot fill every place, + /// and hosts past the limit are counted and left out rather than failing + /// the lookup. + private func discoverHosts( + for service: OverlayService, + alongside callerHosts: Set + ) async throws -> LookupHostSelection { + guard !slapTrackers.isEmpty else { return LookupHostSelection(hosts: []) } let slapService: OverlayService do { slapService = try OverlayService(rawValue: "ls_slap", limits: limits) @@ -94,48 +233,89 @@ public struct LookupResolver: OverlayLookupResolving, Sendable { query: queryBytes, limits: limits ) - let responses = try await query(question, at: slapTrackers) - var discovered: Set = [] - for response in responses { - guard case .outputList(let outputs) = response else { continue } + let results = try await query(question, at: slapTrackers) + var trackerFailures: [OverlayHostFailure] = [] + for case (let tracker, .failure(let error)) in results { + trackerFailures.append(OverlayHostFailure(host: tracker, error: error)) + } + for failure in trackerFailures { + OverlayLog.hostFailure("LookupResolver.discoverHosts", failure) + } + guard trackerFailures.count < results.count else { + throw OverlayPolicyError.noSuccessfulResponses + } + + let room = max(0, limits.maximumResolutionHostCount - callerHosts.count) + let share = max(1, room / slapTrackers.count) + var skipped = 0 + var perTracker: [[OverlayHost]] = [] + for case (_, .success(.outputList(let outputs))) in results { + var named: [OverlayHost] = [] + var seen: Set = [] for output in outputs { guard - let transaction = try? overlayLookupTransaction( - for: output, - beefLimits: beefLimits - ), - Int(output.outputIndex) < transaction.outputs.count, - let token = try? OverlayAdminTokenCodec.decode( - transaction.outputs[Int(output.outputIndex)].lockingScript, - limits: adminTokenLimits + let token = verifiedAdvertisement( + in: output, + beefLimits: beefLimits, + adminTokenLimits: adminTokenLimits, + operation: "LookupResolver.discoverHosts" ), - token.subject == .slap(service) + token.subject == .slap(service), + let host = advertisedHTTPSHost( + token, policy: discoveredHostPolicy, limits: limits) else { continue } - discovered.insert(token.host) - guard discovered.count <= limits.maximumResolutionHostCount else { - throw OverlayError.limitExceeded( - name: "resolvedHosts", - actual: discovered.count, - maximum: limits.maximumResolutionHostCount - ) + guard !callerHosts.contains(host), seen.insert(host).inserted else { continue } + if named.count < share { + named.append(host) + } else { + skipped += 1 + } + } + perTracker.append(named) + } + + var discovered: Set = [] + var position = 0 + while perTracker.contains(where: { position < $0.count }) { + for named in perTracker where position < named.count { + let host = named[position] + guard !discovered.contains(host) else { continue } + if discovered.count < room { + discovered.insert(host) + } else { + skipped += 1 } } + position += 1 } - return discovered.sorted() + if skipped > 0 { + OverlayLog.skippedHosts( + "LookupResolver.discoverHosts", count: skipped, + limit: limits.maximumResolutionHostCount) + } + return LookupHostSelection( + hosts: discovered.sorted(), + trackerFailures: trackerFailures, + skippedHostCount: skipped + ) } + /// Each host's answer or failure, in host order. Only cancellation and + /// host-count limits throw. private func query( _ question: LookupQuestion, at hosts: [OverlayHost] - ) async throws -> [LookupAnswer] { + ) async throws -> [(OverlayHost, Result)] { try Self.validateHosts(hosts, limits: limits) - var indexed: [(Int, LookupAnswer)] = [] + var indexed: [(Int, Result)] = [] let width = limits.maximumConcurrentRequestCount var start = 0 while start < hosts.count { try Task.checkCancellation() let end = min(hosts.count, start + width) - try await withThrowingTaskGroup(of: (Int, LookupAnswer?).self) { group in + try await withThrowingTaskGroup( + of: (Int, Result).self + ) { group in for index in start.. LookupAnswer { - let hasFreeform = responses.contains { if case .freeform = $0 { true } else { false } } - let hasOutputs = responses.contains { if case .outputList = $0 { true } else { false } } - guard !(hasFreeform && hasOutputs) else { - throw OverlayPolicyError.inconsistentAnswerTypes - } - if hasFreeform { - guard case .freeform(let bytes) = responses[0] else { - throw OverlayPolicyError.inconsistentAnswerTypes - } - return try LookupAnswer(freeform: bytes, limits: limits) + /// Merges the hosts' answers. + /// + /// When any host answers with an output list, the result is the merged + /// output lists and freeform answers are left out, as `@bsv/sdk` + /// `LookupResolver.query` does (`LookupResolver.ts:1508-1528`). When every + /// answering host answers freeform, the first freeform answer in sorted + /// host order is returned. + private func aggregate( + _ answers: [(OverlayHost, LookupAnswer)] + ) throws -> (LookupAnswer?, [LookupOutputRejection]) { + let hasOutputs = answers.contains { if case .outputList = $0.1 { true } else { false } } + if !hasOutputs { + guard case .freeform(let bytes)? = answers.first?.1 else { return (nil, []) } + return (try LookupAnswer(freeform: bytes, limits: limits), []) } var outputsByKey: [OverlayOutputKey: OutputListItem] = [:] - for response in responses { - guard case .outputList(let outputs) = response else { - throw OverlayPolicyError.inconsistentAnswerTypes - } + var rejected: [LookupOutputRejection] = [] + var outputCount = 0 + for case (let host, .outputList(let outputs)) in answers { + outputCount += outputs.count for output in outputs { - let key = try outputKey(for: output) + let key: OverlayOutputKey + do { + key = try outputKey(for: output) + } catch { + rejected.append(LookupOutputRejection(host: host, output: output, error: error)) + continue + } if outputsByKey[key] == nil { outputsByKey[key] = output } } } + if outputCount > 0, outputsByKey.isEmpty { return (nil, rejected) } let outputs = outputsByKey.keys.sorted().compactMap { outputsByKey[$0] } - return try LookupAnswer(outputList: outputs, limits: limits) + return (try LookupAnswer(outputList: outputs, limits: limits), rejected) } private func outputKey(for output: OutputListItem) throws -> OverlayOutputKey { - let transaction = try overlayLookupTransaction(for: output, beefLimits: beefLimits) + let transaction = try output.transaction(beefLimits: beefLimits) guard Int(output.outputIndex) < transaction.outputs.count else { throw OverlayPolicyError.invalidLookupOutput } @@ -205,6 +392,13 @@ public struct LookupResolver: OverlayLookupResolving, Sendable { return OverlayOutputKey(transactionID: transactionID, outputIndex: output.outputIndex) } + private static func normalized(_ hosts: [OverlayHost], limits: OverlayLimits) -> [OverlayHost] { + hosts.map { host in + OverlayAdvertisementURI.httpsOrigin(host.rawValue) + .flatMap { try? OverlayHost(rawValue: $0, limits: limits) } ?? host + } + } + private static func validateHosts( _ hosts: [OverlayHost], limits: OverlayLimits @@ -226,28 +420,39 @@ public struct LookupResolver: OverlayLookupResolving, Sendable { } } -package func overlayLookupTransaction( - for output: OutputListItem, - beefLimits: BEEFLimits -) throws -> Transaction { - do { - if output.beef.count >= 4, - output.beef[0] == 1, - output.beef[1] == 1, - output.beef[2] == 1, - output.beef[3] == 1 - { - let atomic = try AtomicBEEF( - bytes: output.beef, limits: beefLimits, transactionOrder: .any - ) +extension OutputListItem { + /// The transaction that holds this output. + /// + /// With a ``transactionID`` the output names its transaction, which is + /// taken from the BEEF; an Atomic BEEF must have it as its subject. + /// Without one, an Atomic BEEF gives its subject and a standard BEEF gives + /// its last transaction once reordered parents-first. + /// + /// Throws the BEEF decoding error when `beef` cannot be read, and + /// ``OverlayPolicyError/invalidLookupOutput`` when the BEEF lacks the + /// named transaction or names another subject. + public func transaction(beefLimits: BEEFLimits) throws -> Transaction { + if beef.count >= 4, beef[0] == 1, beef[1] == 1, beef[2] == 1, beef[3] == 1 { + let atomic = try AtomicBEEF(bytes: beef, limits: beefLimits, transactionOrder: .any) + if let named = transactionID, named != atomic.subjectTransactionID { + throw OverlayPolicyError.invalidLookupOutput + } guard let transaction = try atomic.beef.transaction( for: atomic.subjectTransactionID, limits: beefLimits.transactionLimits ) - else { - throw OverlayPolicyError.invalidLookupOutput - } + else { throw OverlayPolicyError.invalidLookupOutput } + return transaction + } + let standard = try BEEF(bytes: beef, limits: beefLimits, transactionOrder: .any) + if let named = transactionID { + guard + let transaction = try standard.transaction( + for: named, + limits: beefLimits.transactionLimits + ) + else { throw OverlayPolicyError.invalidLookupOutput } return transaction } // Lookup answers come from `@bsv/sdk` writers, which can list a child @@ -257,11 +462,21 @@ package func overlayLookupTransaction( // instead; the two differ only when the writer put a parent last. This // keeps the reordered choice: a transaction nothing else in the answer // spends. - let beef = try BEEF(bytes: output.beef, limits: beefLimits, transactionOrder: .any) - guard let transaction = beef.transactions.last?.transaction else { + guard let transaction = standard.transactions.last?.transaction else { throw OverlayPolicyError.invalidLookupOutput } return transaction + } +} + +/// ``OutputListItem/transaction(beefLimits:)`` with every failure reported as +/// ``OverlayPolicyError/invalidLookupOutput``. +package func overlayLookupTransaction( + for output: OutputListItem, + beefLimits: BEEFLimits +) throws -> Transaction { + do { + return try output.transaction(beefLimits: beefLimits) } catch let error as OverlayPolicyError { throw error } catch { @@ -269,6 +484,53 @@ package func overlayLookupTransaction( } } +/// The verified SHIP or SLAP advertisement a discovery output holds, or nil. +/// +/// As in `@bsv/sdk` (`LookupResolver.ts:2210-2232`, `SHIPBroadcaster.ts:755-777`), +/// the output must hold exactly one satoshi and a token that passes +/// ``OverlayAdminTokenCodec/decode(_:limits:)``. +package func verifiedAdvertisement( + in output: OutputListItem, + beefLimits: BEEFLimits, + adminTokenLimits: OverlayAdminTokenLimits, + operation: String +) -> OverlayAdminToken? { + do { + let transaction = try output.transaction(beefLimits: beefLimits) + guard Int(output.outputIndex) < transaction.outputs.count else { + throw OverlayPolicyError.invalidLookupOutput + } + let selected = transaction.outputs[Int(output.outputIndex)] + guard selected.satoshis == 1 else { + OverlayLog.skippedAdvertisement( + operation, output: output, reason: "holds \(selected.satoshis) satoshis, not 1") + return nil + } + return try OverlayAdminTokenCodec.decode(selected.lockingScript, limits: adminTokenLimits) + } catch { + OverlayLog.skippedAdvertisement( + operation, output: output, + reason: "\(type(of: error)): \(String(reflecting: error))") + return nil + } +} + +/// The `https://` origin an advertisement names, as a host the HTTPS +/// facilitators accept, or nil when it names another transport or a host +/// `policy` excludes. +package func advertisedHTTPSHost( + _ token: OverlayAdminToken, + policy: OverlayDiscoveredHostPolicy, + limits: OverlayLimits +) -> OverlayHost? { + let uri = token.host.rawValue + guard let origin = OverlayAdvertisementURI.httpsOrigin(uri) else { return nil } + if policy == .publicNetworkOnly, !OverlayAdvertisementURI.isPublicHTTPSOrigin(uri) { + return nil + } + return try? OverlayHost(rawValue: origin, limits: limits) +} + private struct OverlayOutputKey: Hashable, Comparable, Sendable { let transactionID: TransactionID let outputIndex: UInt32 diff --git a/Sources/BSVOverlay/OverlayAdminToken.swift b/Sources/BSVOverlay/OverlayAdminToken.swift index 83edc8d..a8b6bf7 100644 --- a/Sources/BSVOverlay/OverlayAdminToken.swift +++ b/Sources/BSVOverlay/OverlayAdminToken.swift @@ -23,7 +23,7 @@ public struct OverlayAdminTokenLimits: Hashable, Sendable { private init(standard: Void) { maximumScriptByteCount = 64 * 1_024 - maximumFieldByteCount = 8 * 1_024 + maximumFieldByteCount = OverlayAdminTokenCodec.maximumFieldByteCount overlayLimits = .standard } @@ -40,6 +40,9 @@ public enum OverlayAdminTokenError: Error, Equatable, Sendable { case invalidHost case invalidSubject case invalidSignature + /// The locking key is not the key `@bsv/sdk` derives from the identity key + /// for this protocol, so the identity key is not authenticated. + case unlinkedLockingKey } /// The typed subject advertised by an overlay administration token. @@ -58,9 +61,11 @@ public enum OverlayAdminSubject: Hashable, Sendable { /// A verified SHIP or SLAP administration advertisement. /// /// The token's signature commits to the protocol, identity key, host, and -/// subject. It is verified against the PushDrop locking public key while -/// decoding, so a decoded value is safe for a later, caller-selected discovery -/// policy to evaluate. +/// subject. While decoding, the locking key is checked to be the BRC-42 child +/// of the identity key for the protocol (counterparty "anyone", key ID `1`) +/// and the signature is verified under it, as `@bsv/sdk` +/// `decodeAndVerifyOverlayAdvertisement` does. `host` is the advertised URI as +/// written in the token, for example `https://overlay.example/`. public struct OverlayAdminToken: Hashable, Sendable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable { @@ -90,14 +95,19 @@ public struct OverlayAdminToken: Hashable, Sendable, CustomStringConvertible, } } -/// Strict decoder for the signed Go-compatible overlay administration token. +/// Strict decoder for a signed SHIP or SLAP advertisement, with the rules of +/// `@bsv/sdk` `overlay-tools/OverlayAdminTokenTemplate.ts`. /// -/// Wallet construction and spending are intentionally excluded. This codec -/// only verifies the immutable on-chain advertisement required by a future -/// resolver or broadcaster policy. +/// Wallet construction and spending are intentionally excluded. Legacy +/// advertisements (title-case protocol IDs, "self" counterparty) fail the +/// identity linkage check, as they do in `@bsv/sdk`. public enum OverlayAdminTokenCodec { private static let dataFieldCount = 4 private static let signedFieldCount = 5 + /// `MAX_DISCOVERY_FIELD_BYTES` in `@bsv/sdk`. + package static let maximumFieldByteCount = 4_096 + /// `MAX_DISCOVERY_PAYLOAD_BYTES` in `@bsv/sdk`: all five fields together. + package static let maximumPayloadByteCount = 8_192 public static func decode( _ script: Script, @@ -132,6 +142,13 @@ public enum OverlayAdminTokenCodec { } let fields = decoded.fields + var payloadByteCount = 0 + for field in fields { + payloadByteCount += field.count + guard field.count <= maximumFieldByteCount, + payloadByteCount <= maximumPayloadByteCount + else { throw OverlayAdminTokenError.invalidPushDrop } + } let subject = try decodeSubject( protocolBytes: fields[0], subjectBytes: fields[3], @@ -140,10 +157,17 @@ public enum OverlayAdminTokenCodec { let identityPublicKey = try decodeIdentityKey(fields[1]) let host = try decodeHost(fields[2], limits: limits.overlayLimits) let signature = try decodeSignature(fields[4]) + let derivedKey = try linkedLockingKey( + identityPublicKey: identityPublicKey, + overlayProtocol: subject.overlayProtocol + ) let digest = BSVHashing.sha256(try signingPayload(fields[0..-1`, derived with the + /// "anyone" private key (scalar 1). + private static func linkedLockingKey( + identityPublicKey: PublicKey, + overlayProtocol: OverlayProtocol + ) throws -> PublicKey { + do { + let anyone = try PrivateKey(Array(repeating: 0, count: 31) + [1]) + return try identityPublicKey.derivedChild( + with: anyone, + invoiceNumber: "2-\(overlayProtocol.identifier.rawValue)-1" + ) + } catch { + throw OverlayAdminTokenError.unlinkedLockingKey + } + } + + /// A compressed key whose canonical encoding is the field itself. private static func decodeIdentityKey(_ bytes: [UInt8]) throws -> PublicKey { - guard bytes.count == 33 else { throw OverlayAdminTokenError.invalidIdentityKey } + guard bytes.count == 33, bytes[0] == 0x02 || bytes[0] == 0x03 else { + throw OverlayAdminTokenError.invalidIdentityKey + } do { - return try PublicKey(bytes) + let key = try PublicKey(bytes) + guard key.compressedBytes == bytes else { + throw OverlayAdminTokenError.invalidIdentityKey + } + return key } catch { throw OverlayAdminTokenError.invalidIdentityKey } @@ -195,7 +244,9 @@ public enum OverlayAdminTokenCodec { _ bytes: [UInt8], limits: OverlayLimits ) throws -> OverlayHost { - guard let text = String(bytes: bytes, encoding: .utf8) else { + guard let text = String(bytes: bytes, encoding: .utf8), + OverlayAdvertisementURI.isValid(text) + else { throw OverlayAdminTokenError.invalidHost } do { @@ -206,6 +257,9 @@ public enum OverlayAdminTokenCodec { } private static func decodeSignature(_ bytes: [UInt8]) throws -> ECDSASignature { + guard (8...80).contains(bytes.count) else { + throw OverlayAdminTokenError.invalidSignature + } do { let signature = try ECDSASignature(derBytes: bytes) guard signature.derBytes == bytes else { diff --git a/Sources/BSVOverlay/OverlayAdvertisementURI.swift b/Sources/BSVOverlay/OverlayAdvertisementURI.swift new file mode 100644 index 0000000..9fa3958 --- /dev/null +++ b/Sources/BSVOverlay/OverlayAdvertisementURI.swift @@ -0,0 +1,612 @@ +/// The URI rules `@bsv/sdk` applies to the host field of a SHIP or SLAP +/// advertisement (`overlay-tools/OverlayAdminTokenTemplate.ts:30-158`). +/// +/// `@bsv/sdk` parses these URIs with the WHATWG URL parser. This port parses +/// hosts the same way: domains are lowercased, IPv4 hosts in any WHATWG form +/// (`2130706433`, `0x7f.1`, `1.2.3`) are read as numbers and written as a +/// dotted quad, IPv6 hosts are validated and written in canonical form, and a +/// host that ends in a number but is not a valid IPv4 address is rejected. The +/// default port is dropped. +/// +/// It accepts nothing `@bsv/sdk` rejects. It rejects a few forms that the +/// WHATWG parser accepts or repairs and no advertisement writer emits: +/// percent-encoded or non-ASCII host text, host characters outside letters, +/// digits, `-`, `.` and `_` (such as `! $ & ' ( ) * + , ; = ~`), any `@` in +/// the authority, a backslash, dot segments or other text in a path that must +/// be `/`, extra slashes after the scheme, and leading or trailing spaces. +enum OverlayAdvertisementURI { + static let maximumByteCount = 4_096 + + private static let httpsPrefixes = [ + "https://", + "https+bsvauth://", + "https+bsvauth+smf://", + "https+bsvauth+scrypt-offchain://", + "https+rtt://", + ] + private static let js8Prefix = "js8c+bsvauth+smf:" + + /// Whether `value` is an advertisement URI that `@bsv/sdk` accepts. + static func isValid(_ value: String) -> Bool { + guard !value.isEmpty, + value.utf8.count <= maximumByteCount, + !value.unicodeScalars.contains(where: isControl) + else { return false } + if let prefix = httpsPrefixes.first(where: { value.utf8.starts(with: $0.utf8) }) { + guard let url = AuthorityURL(afterScheme: suffix(of: value, after: prefix)) else { + return false + } + return url.isAllowedPublicHost && !url.hasFragment && url.path == "/" + } + if value.utf8.starts(with: "wss://".utf8) { + guard let url = AuthorityURL(afterScheme: suffix(of: value, after: "wss://")) else { + return false + } + return url.isAllowedPublicHost && !url.hasFragment + } + if value.utf8.starts(with: js8Prefix.utf8) { + return isValidJS8(value) + } + return false + } + + /// The `https://` origin an advertised URI names, as `@bsv/sdk` sends + /// requests to it (`SHIPBroadcaster.ts:102-125`, `LookupResolver.ts:518-549`): + /// canonical host, no default port, no trailing slash. Returns nil for a + /// URI that is not an `https://` origin with path `""` or `"/"`. + static func httpsOrigin(_ value: String) -> String? { + httpsAuthority(value)?.origin + } + + /// Whether `value` is an `https://` origin whose host may be a public + /// network endpoint, as `createPublicNetworkFetch` in `@bsv/sdk` decides + /// for an address literal (`storage/PublicHTTPSFetch.ts:61-158`). + /// + /// An IPv4 or IPv6 host must be a public unicast address. A domain may + /// not have an empty label other than one trailing dot, may not be only + /// digits and dots (`PublicHTTPSFetch.ts:201-204`), and, after its + /// trailing dot is removed, may not be `localhost` or end in + /// `.localhost`, `.local`, `.internal` or `.home.arpa`. + /// + /// Not checked: what a domain resolves to. On Node, `@bsv/sdk` resolves + /// each name, refuses one that resolves to a private address and connects + /// to the address it checked (`PublicHTTPSFetch.ts:262-271`). The + /// `URLSession` transport resolves names itself and cannot be pinned to a + /// checked address, so an advertised domain that resolves to a private + /// address is still contacted. TLS limits that to a connection attempt + /// whose certificate must match the advertised name. + static func isPublicHTTPSOrigin(_ value: String) -> Bool { + guard let url = httpsAuthority(value) else { return false } + switch url.hostKind { + case .ipv4(let address): + return isPublicIPv4(address) + case .ipv6(let pieces): + return isPublicIPv6(pieces) + case .domain: + var name = url.host + if name.hasSuffix(".") { name.removeLast() } + let labels = name.split(separator: ".", omittingEmptySubsequences: false) + guard !name.isEmpty, !labels.contains(where: \.isEmpty), + !name.allSatisfy({ $0 == "." || ("0"..."9").contains($0) }) + else { return false } + let privateSuffixes = [".localhost", ".local", ".internal", ".home.arpa"] + return name != "localhost" + && !privateSuffixes.contains(where: { name.hasSuffix($0) }) + } + } + + private static func httpsAuthority(_ value: String) -> AuthorityURL? { + guard isValid(value), + value.utf8.starts(with: "https://".utf8), + let url = AuthorityURL(afterScheme: suffix(of: value, after: "https://")), + !url.hasQuery, + !url.hasFragment, + url.path == "/" + else { return nil } + return url + } + + /// `isPublicNetworkAddress` for IPv4 (`PublicHTTPSFetch.ts:114-132`). + static func isPublicIPv4(_ address: UInt32) -> Bool { + let a = address >> 24 + let b = (address >> 16) & 0xff + return !(a == 0 || a == 10 || a == 127 + || (a == 100 && (64...127).contains(b)) + || (a == 169 && b == 254) + || (a == 172 && (16...31).contains(b)) + || (a == 192 && (b == 0 || b == 168)) + || (a == 198 && (b == 18 || b == 19 || b == 51)) + || (a == 203 && b == 0) + || a >= 224) + } + + /// `isPublicNetworkAddress` for IPv6, including the IPv4 address that a + /// mapped, compatible, NAT64 or 6to4 address embeds + /// (`PublicHTTPSFetch.ts:100-112,134-157`). + static func isPublicIPv6(_ pieces: [UInt16]) -> Bool { + guard pieces.count == 8 else { return false } + let p = pieces.map(UInt32.init) + let firstFiveZero = p[0..<5].allSatisfy { $0 == 0 } + let compatibleOrMapped = firstFiveZero && (p[5] == 0 || p[5] == 0xffff) + let nat64 = p[0] == 0x0064 && p[1] == 0xff9b && p[2..<6].allSatisfy { $0 == 0 } + let sixToFour = p[0] == 0x2002 + if compatibleOrMapped || nat64 || sixToFour { + let start = sixToFour ? 1 : 6 + if !isPublicIPv4(p[start] << 16 | p[start + 1]) { return false } + } + let allZero = p.allSatisfy { $0 == 0 } + let loopback = p[0..<7].allSatisfy { $0 == 0 } && p[7] == 1 + let globalUnicast = p[0] & 0xe000 == 0x2000 + let special2001 = p[0] == 0x2001 && p[1] < 0x0200 + let documentation = (p[0] == 0x2001 && p[1] == 0x0db8) || p[0] & 0xfff0 == 0x3ff0 + return !(allZero || loopback || !globalUnicast || special2001 || documentation + || p[0] & 0xfe00 == 0xfc00 + || p[0] & 0xffc0 == 0xfe80 + || p[0] & 0xffc0 == 0xfec0 + || p[0] & 0xff00 == 0xff00) + } + + private static func suffix(of value: String, after prefix: String) -> Substring { + let bytes = value.utf8 + let start = bytes.index(bytes.startIndex, offsetBy: prefix.utf8.count) + return value[start...] + } + + /// `\p{Cc}`: C0 controls, DEL, and C1 controls. + private static func isControl(_ scalar: Unicode.Scalar) -> Bool { + scalar.value < 0x20 || (0x7f...0x9f).contains(scalar.value) + } + + // MARK: js8c+bsvauth+smf + + private static let coordinateNames: Set = ["lat", "long", "freq", "radius"] + + /// `validateJs8URI` in `OverlayAdminTokenTemplate.ts:111-140`. + private static func isValidJS8(_ value: String) -> Bool { + guard let questionMark = value.firstIndex(of: "?"), + value[.. Bool { + var bytes = Array(text.utf8)[...] + if bytes.first == 0x2d { bytes = bytes.dropFirst() } + let integer = bytes.prefix(while: isDigit) + guard !integer.isEmpty, integer.count == 1 || integer.first != 0x30 else { return false } + let rest = bytes.dropFirst(integer.count) + if rest.isEmpty { return true } + guard rest.first == 0x2e else { return false } + let fraction = rest.dropFirst() + return !fraction.isEmpty && fraction.allSatisfy(isDigit) + } + + /// `parsePositiveMeasurement`: `^(\d+(?:\.\d+)?)(?:[a-zA-Z][a-zA-Z0-9/_-]*)?$` + /// after trimming, with a finite positive number. + private static func positiveMeasurement(_ text: String) -> Double? { + let bytes = Array(trimmedJS(text).utf8)[...] + let integer = bytes.prefix(while: isDigit) + guard !integer.isEmpty else { return nil } + var number = Array(integer) + var rest = bytes.dropFirst(integer.count) + if rest.first == 0x2e { + let fraction = rest.dropFirst().prefix(while: isDigit) + if !fraction.isEmpty { + number.append(0x2e) + number.append(contentsOf: fraction) + rest = rest.dropFirst(1 + fraction.count) + } + } + if let unitStart = rest.first { + guard isLetter(unitStart), + rest.dropFirst().allSatisfy({ + isLetter($0) || isDigit($0) || $0 == 0x2f || $0 == 0x5f || $0 == 0x2d + }) + else { return nil } + } + guard let value = Double(String(decoding: number, as: UTF8.self)), + value.isFinite, value > 0 + else { return nil } + return value + } + + /// `String.prototype.trim`, for the ASCII and Unicode space separators + /// that can reach it here (controls are already rejected). + private static func trimmedJS(_ text: String) -> String { + let scalars = text.unicodeScalars + let isSpace: (Unicode.Scalar) -> Bool = { $0.properties.isWhitespace || $0 == "\u{FEFF}" } + guard let first = scalars.firstIndex(where: { !isSpace($0) }), + let last = scalars.lastIndex(where: { !isSpace($0) }) + else { return "" } + return String(scalars[first...last]) + } + + /// `application/x-www-form-urlencoded` decoding, as `URLSearchParams` does it. + private static func formDecoded(_ text: Substring) -> String { + let input = Array(text.utf8) + var output: [UInt8] = [] + output.reserveCapacity(input.count) + var index = 0 + while index < input.count { + let byte = input[index] + if byte == 0x2b { + output.append(0x20) + } else if byte == 0x25, index + 2 < input.count, + let high = hexValue(input[index + 1]), + let low = hexValue(input[index + 2]) + { + output.append(high << 4 | low) + index += 2 + } else { + output.append(byte) + } + index += 1 + } + return String(decoding: output, as: UTF8.self) + } + + private static func hexValue(_ byte: UInt8) -> UInt8? { + switch byte { + case 0x30...0x39: byte - 0x30 + case 0x41...0x46: byte - 0x41 + 10 + case 0x61...0x66: byte - 0x61 + 10 + default: nil + } + } + + fileprivate static func isDigit(_ byte: UInt8) -> Bool { (0x30...0x39).contains(byte) } + + fileprivate static func isLetter(_ byte: UInt8) -> Bool { + (0x41...0x5a).contains(byte) || (0x61...0x7a).contains(byte) + } +} + +/// The parts of a `scheme://authority/path?query#fragment` URI that the +/// advertisement rules read. +private struct AuthorityURL { + enum HostKind { + case domain + case ipv4(UInt32) + case ipv6([UInt16]) + } + + /// The host as the WHATWG URL parser serializes it: a lowercased domain, + /// a dotted-quad IPv4 address, or a bracketed canonical IPv6 address. + let host: String + let hostKind: HostKind + let port: Int? + /// `"/"` when the URI has no path, as for WHATWG special schemes. + let path: Substring + /// True when a non-empty query follows `?`. + let hasQuery: Bool + /// True when a non-empty fragment follows `#`. WHATWG reports `#` alone + /// as an empty fragment, which `@bsv/sdk` accepts. + let hasFragment: Bool + + init?(afterScheme rest: Substring) { + guard !rest.contains("\\") else { return nil } + var remainder = rest + var fragment: Substring = "" + if let hash = remainder.firstIndex(of: "#") { + fragment = remainder[remainder.index(after: hash)...] + remainder = remainder[.. Bool { + var parts = host.split(separator: ".", omittingEmptySubsequences: false) + if parts.last == "" { + guard parts.count > 1 else { return false } + parts.removeLast() + } + guard let last = parts.last else { return false } + if !last.isEmpty, last.utf8.allSatisfy(OverlayAdvertisementURI.isDigit) { return true } + return ipv4Number(last) != nil + } + + /// The IPv4 parser: up to four numbers in decimal, octal (leading `0`) + /// or hexadecimal (`0x`); the last fills the remaining bytes. + static func ipv4(_ host: String) -> UInt32? { + var parts = host.split(separator: ".", omittingEmptySubsequences: false) + if parts.last == "", parts.count > 1 { parts.removeLast() } + guard (1...4).contains(parts.count) else { return nil } + var numbers: [UInt64] = [] + for part in parts { + guard let number = ipv4Number(part) else { return nil } + numbers.append(number) + } + guard numbers.dropLast().allSatisfy({ $0 <= 255 }) else { return nil } + let last = numbers[numbers.count - 1] + guard last < UInt64(1) << (8 * (5 - numbers.count)) else { return nil } + var address = last + for (index, number) in numbers.dropLast().enumerated() { + address += number << (8 * (3 - index)) + } + return UInt32(address) + } + + /// The IPv4 number parser. Values that cannot fit in 32 bits are capped + /// above `UInt32.max`, which the caller then rejects. + private static func ipv4Number(_ text: Substring) -> UInt64? { + guard !text.isEmpty else { return nil } + var digits = text.utf8[...] + var radix: UInt64 = 10 + if digits.count >= 2, digits.first == 0x30, + digits[digits.index(after: digits.startIndex)] | 0x20 == 0x78 + { + digits = digits.dropFirst(2) + radix = 16 + } else if digits.count >= 2, digits.first == 0x30 { + digits = digits.dropFirst() + radix = 8 + } + var value: UInt64 = 0 + for byte in digits { + let digit: UInt64 + switch byte { + case 0x30...0x39: digit = UInt64(byte - 0x30) + case 0x61...0x66: digit = UInt64(byte - 0x61 + 10) + case 0x41...0x46: digit = UInt64(byte - 0x41 + 10) + default: return nil + } + guard digit < radix else { return nil } + value = min(value * radix + digit, UInt64(UInt32.max) + 1) + } + return value + } + + static func serialize(ipv4 address: UInt32) -> String { + [24, 16, 8, 0].map { String((address >> $0) & 0xff) }.joined(separator: ".") + } + + /// The IPv6 parser, including a trailing embedded IPv4 address. + static func ipv6(_ text: Substring) -> [UInt16]? { + let input = Array(text.utf8) + var address = [UInt16](repeating: 0, count: 8) + var pieceIndex = 0 + var compress: Int? + var pointer = 0 + func at(_ index: Int) -> UInt8? { index < input.count ? input[index] : nil } + + if at(pointer) == 0x3a { + guard at(pointer + 1) == 0x3a else { return nil } + pointer += 2 + pieceIndex += 1 + compress = pieceIndex + } + while let current = at(pointer) { + guard pieceIndex < 8 else { return nil } + if current == 0x3a { + guard compress == nil else { return nil } + pointer += 1 + pieceIndex += 1 + compress = pieceIndex + continue + } + var value: UInt32 = 0 + var length = 0 + while length < 4, let byte = at(pointer), let digit = hexDigit(byte) { + value = value * 16 + UInt32(digit) + pointer += 1 + length += 1 + } + if at(pointer) == 0x2e { + guard length > 0, pieceIndex <= 6 else { return nil } + pointer -= length + var numbersSeen = 0 + while at(pointer) != nil { + var piece: UInt32? + if numbersSeen > 0 { + guard at(pointer) == 0x2e, numbersSeen < 4 else { return nil } + pointer += 1 + } + guard let first = at(pointer), OverlayAdvertisementURI.isDigit(first) else { + return nil + } + while let byte = at(pointer), OverlayAdvertisementURI.isDigit(byte) { + let number = UInt32(byte - 0x30) + if let existing = piece { + guard existing != 0 else { return nil } + piece = existing * 10 + number + } else { + piece = number + } + guard piece! <= 255 else { return nil } + pointer += 1 + } + address[pieceIndex] = address[pieceIndex] &* 0x100 &+ UInt16(piece!) + numbersSeen += 1 + if numbersSeen == 2 || numbersSeen == 4 { pieceIndex += 1 } + } + guard numbersSeen == 4 else { return nil } + break + } else if at(pointer) == 0x3a { + pointer += 1 + guard at(pointer) != nil else { return nil } + } else if at(pointer) != nil { + return nil + } + address[pieceIndex] = UInt16(value) + pieceIndex += 1 + } + if let compress { + var swaps = pieceIndex - compress + pieceIndex = 7 + while pieceIndex != 0, swaps > 0 { + address.swapAt(pieceIndex, compress + swaps - 1) + pieceIndex -= 1 + swaps -= 1 + } + } else if pieceIndex != 8 { + return nil + } + return address + } + + /// The IPv6 serializer: lowercase hex, the first longest run of two or + /// more zero pieces written as `::`. + static func serialize(ipv6 address: [UInt16]) -> String { + var compress: Int? + var bestLength = 1 + var index = 0 + while index < 8 { + guard address[index] == 0 else { + index += 1 + continue + } + var end = index + while end < 8, address[end] == 0 { end += 1 } + if end - index > bestLength { + bestLength = end - index + compress = index + } + index = end + } + var output = "" + var ignoreZero = false + for pieceIndex in 0..<8 { + if ignoreZero, address[pieceIndex] == 0 { continue } + ignoreZero = false + if compress == pieceIndex { + output += pieceIndex == 0 ? "::" : ":" + ignoreZero = true + continue + } + output += String(address[pieceIndex], radix: 16) + if pieceIndex != 7 { output += ":" } + } + return output + } + + private static func hexDigit(_ byte: UInt8) -> UInt8? { + switch byte { + case 0x30...0x39: byte - 0x30 + case 0x61...0x66: byte - 0x61 + 10 + case 0x41...0x46: byte - 0x41 + 10 + default: nil + } + } +} diff --git a/Sources/BSVOverlay/OverlayError+LocalizedError.swift b/Sources/BSVOverlay/OverlayError+LocalizedError.swift new file mode 100644 index 0000000..a692342 --- /dev/null +++ b/Sources/BSVOverlay/OverlayError+LocalizedError.swift @@ -0,0 +1,81 @@ +import Foundation + +/// Plain sentences a wallet can show when an overlay value is refused. +/// `String(reflecting:)` still gives the case with its names and sizes for a log. +extension OverlayError: LocalizedError { + public var errorDescription: String? { + switch self { + case .nonPositiveLimit: + "The overlay limits are not set up correctly." + case .invalidProtocolIdentifier: + "The overlay protocol is not SHIP or SLAP." + case .invalidTopic: + "The overlay topic name is not valid. It must start with tm_ and use lowercase letters, digits and single underscores." + case .invalidService: + "The overlay service name is not valid. It must start with ls_ and use lowercase letters, digits and single underscores." + case .invalidHost: + "The overlay address is not a valid HTTPS address." + case .emptyValue: + "A required overlay value is empty." + case .duplicateValue(let name): + name == "hosts" || name == "acknowledgmentHosts" + ? "The same overlay address is listed twice." + : "The same overlay value is listed twice." + case .limitExceeded: + "The overlay request is larger than the wallet accepts." + } + } +} + +/// Plain sentences for an overlay advertisement that is refused. +extension OverlayAdminTokenError: LocalizedError { + public var errorDescription: String? { + switch self { + case .invalidLimits: + "The overlay advertisement limits are not set up correctly." + case .invalidPushDrop, .unexpectedFieldCount: + "The overlay advertisement is not in the expected script format." + case .invalidProtocol: + "The overlay advertisement is not a SHIP or SLAP advertisement." + case .invalidIdentityKey: + "The overlay advertisement does not name a valid identity key." + case .invalidHost: + "The overlay advertisement does not name a valid public address." + case .invalidSubject: + "The overlay advertisement does not name a valid topic or service." + case .invalidSignature: + "The overlay advertisement is not signed correctly." + case .unlinkedLockingKey: + "The overlay advertisement was not made by the identity it names." + } + } +} + +/// Plain sentences for an overlay lookup or broadcast that did not succeed. +extension OverlayPolicyError: LocalizedError { + public var errorDescription: String? { + switch self { + case .noCompetentHosts: + "No overlay host was found for this lookup." + case .noSuccessfulResponses: + "No overlay host answered. Check your connection and try again." + case .inconsistentAnswerTypes: + "The overlay hosts gave answers that do not match." + case .invalidLookupOutput: + "The overlay hosts answered, but none of their results could be read." + case .discoveryResponseNotOutputList: + "The overlay directory sent an answer the wallet could not read." + case .noInterestedHosts: + "No overlay host accepts this kind of transaction." + case .invalidAtomicBEEF: + "The transaction could not be prepared for the overlay." + case .uncertainDelivery: + "The transaction may have reached an overlay host, but not every host answered. " + + "Check its status before sending it again." + case .acknowledgmentFailed: + "The overlay hosts did not accept the transaction." + case .invalidSteak: + "An overlay host sent an answer that does not match the transaction it was sent." + } + } +} diff --git a/Sources/BSVOverlay/OverlayLog.swift b/Sources/BSVOverlay/OverlayLog.swift new file mode 100644 index 0000000..e2f4c0c --- /dev/null +++ b/Sources/BSVOverlay/OverlayLog.swift @@ -0,0 +1,66 @@ +import Foundation + +#if canImport(os) +import os +#endif + +/// The overlay policy log: subsystem `dev.opl.swift-sdk`, category `BSVOverlay`. +/// +/// The HTTPS facilitators log each failed request through `NetworkLog`. This +/// log records what the resolver and broadcaster then leave out: a host or +/// tracker that failed, a STEAK that was empty or acknowledged a topic that +/// was not sent, an output whose transaction could not be read, an +/// advertisement that could not be used, and advertised hosts past the host +/// limit. Errors are logged in full. Hosts are written as scheme, host and +/// port only, so a caller host carrying a user name, password, path or query +/// does not put it in the log; no payload bytes are written. +/// +/// Like `NetworkLog`, it writes through `os.Logger`, so it records nothing on +/// platforms without `os` (Linux). +enum OverlayLog { + static let subsystem = "dev.opl.swift-sdk" + static let category = "BSVOverlay" + + static func hostFailure(_ operation: String, _ failure: OverlayHostFailure) { + error( + "\(operation): host \(location(failure.host)) failed: " + + "\(type(of: failure.error)): \(String(reflecting: failure.error))" + ) + } + + static func rejectedOutput(_ operation: String, _ rejection: LookupOutputRejection) { + error( + "\(operation): output \(rejection.output.outputIndex) from host " + + "\(location(rejection.host)) left out: " + + "\(type(of: rejection.error)): \(String(reflecting: rejection.error))" + ) + } + + static func skippedAdvertisement(_ operation: String, output: OutputListItem, reason: String) { + let transaction = output.transactionID.map { " of \($0.displayHex)" } ?? "" + error( + "\(operation): advertisement output \(output.outputIndex)\(transaction) " + + "left out: \(reason)" + ) + } + + static func skippedHosts(_ operation: String, count: Int, limit: Int) { + error("\(operation): \(count) advertised host(s) left out past the limit of \(limit)") + } + + /// Scheme, host and port of `host`, as `NetworkLog.location` keeps only + /// what identifies the endpoint. + static func location(_ host: OverlayHost) -> String { + guard let components = URLComponents(string: host.rawValue), + let scheme = components.scheme, let name = components.host, !name.isEmpty + else { return "(unparsed host)" } + let port = components.port.map { ":\($0)" } ?? "" + return "\(scheme)://\(name)\(port)" + } + + private static func error(_ message: String) { + #if canImport(os) + Logger(subsystem: subsystem, category: category).error("\(message, privacy: .public)") + #endif + } +} diff --git a/Sources/BSVOverlay/OverlayModels.swift b/Sources/BSVOverlay/OverlayModels.swift index ec36360..9c1a60f 100644 --- a/Sources/BSVOverlay/OverlayModels.swift +++ b/Sources/BSVOverlay/OverlayModels.swift @@ -21,6 +21,8 @@ public struct OverlayLimits: Hashable, Sendable { public let maximumSteakTopicCount: Int public let maximumResolutionHostCount: Int public let maximumConcurrentRequestCount: Int + /// The largest `context` one lookup output may carry. `@bsv/sdk` caps it at 1 MiB. + public let maximumLookupContextByteCount: Int public init( maximumTaggedBEEFByteCount: Int, @@ -40,7 +42,8 @@ public struct OverlayLimits: Hashable, Sendable { maximumAncillaryTransactionCount: Int = 10_000, maximumSteakTopicCount: Int = 256, maximumResolutionHostCount: Int = 64, - maximumConcurrentRequestCount: Int = 8 + maximumConcurrentRequestCount: Int = 8, + maximumLookupContextByteCount: Int = 1 * 1_024 * 1_024 ) throws { let values = [ ("maximumTaggedBEEFByteCount", maximumTaggedBEEFByteCount), @@ -61,6 +64,7 @@ public struct OverlayLimits: Hashable, Sendable { ("maximumSteakTopicCount", maximumSteakTopicCount), ("maximumResolutionHostCount", maximumResolutionHostCount), ("maximumConcurrentRequestCount", maximumConcurrentRequestCount), + ("maximumLookupContextByteCount", maximumLookupContextByteCount), ] if let invalid = values.first(where: { $0.1 <= 0 }) { throw OverlayError.nonPositiveLimit(name: invalid.0, value: invalid.1) @@ -83,6 +87,7 @@ public struct OverlayLimits: Hashable, Sendable { self.maximumSteakTopicCount = maximumSteakTopicCount self.maximumResolutionHostCount = maximumResolutionHostCount self.maximumConcurrentRequestCount = maximumConcurrentRequestCount + self.maximumLookupContextByteCount = maximumLookupContextByteCount } private init(standard: Void) { @@ -104,6 +109,7 @@ public struct OverlayLimits: Hashable, Sendable { maximumSteakTopicCount = 256 maximumResolutionHostCount = 64 maximumConcurrentRequestCount = 8 + maximumLookupContextByteCount = 1 * 1_024 * 1_024 } public static let standard = Self(standard: ()) @@ -145,13 +151,18 @@ public enum OverlayNetwork: String, CaseIterable, Hashable, Sendable { } /// A BRC-87 topic-manager name. +/// +/// The grammar is the one `@bsv/sdk` and the overlay engine enforce +/// (`overlay-tools/OverlayNames.ts`): `tm_`, then one or more segments of +/// lowercase ASCII letters and digits joined by single underscores, at most +/// 256 bytes in all. public struct OverlayTopic: Hashable, Sendable, Comparable { public let rawValue: String public init(rawValue: String, limits: OverlayLimits = .standard) throws { try enforceOverlayUTF8Limit( rawValue, name: "topic", maximum: limits.maximumTopicUTF8ByteCount) - guard rawValue.hasPrefix("tm_"), validOverlayIdentifier(rawValue) else { + guard validOverlayName(rawValue, prefix: "tm_") else { throw OverlayError.invalidTopic } self.rawValue = rawValue @@ -160,14 +171,15 @@ public struct OverlayTopic: Hashable, Sendable, Comparable { public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } } -/// A BRC-87 lookup-service name. +/// A BRC-87 lookup-service name, with the same grammar as ``OverlayTopic`` +/// under the `ls_` prefix. public struct OverlayService: Hashable, Sendable, Comparable { public let rawValue: String public init(rawValue: String, limits: OverlayLimits = .standard) throws { try enforceOverlayUTF8Limit( rawValue, name: "service", maximum: limits.maximumServiceUTF8ByteCount) - guard rawValue.hasPrefix("ls_"), validOverlayIdentifier(rawValue) else { + guard validOverlayName(rawValue, prefix: "ls_") else { throw OverlayError.invalidService } self.rawValue = rawValue @@ -376,14 +388,32 @@ public struct OverlayMetadata: Hashable, Sendable { } } -package func validOverlayIdentifier(_ value: String) -> Bool { - value.utf8.count > 3 - && value.utf8.allSatisfy { byte in - (0x30...0x39).contains(byte) || (0x41...0x5a).contains(byte) - || (0x61...0x7a).contains(byte) || byte == 0x5f || byte == 0x2d +/// The `@bsv/sdk` topic and service name pattern +/// `^(?=.{1,256}$)[a-z0-9]+(?:_[a-z0-9]+)*$`. +package func validOverlayName(_ value: String, prefix: String) -> Bool { + let bytes = Array(value.utf8) + let prefixBytes = Array(prefix.utf8) + guard bytes.count <= maximumOverlayNameByteCount, + bytes.count > prefixBytes.count, + bytes.starts(with: prefixBytes) + else { return false } + var previousWasSeparator = true + for byte in bytes[prefixBytes.count...] { + if byte == 0x5f { + guard !previousWasSeparator else { return false } + previousWasSeparator = true + } else if (0x30...0x39).contains(byte) || (0x61...0x7a).contains(byte) { + previousWasSeparator = false + } else { + return false } + } + return !previousWasSeparator } +/// `MAX_OVERLAY_NAME_BYTES` in `@bsv/sdk`, which matches the overlay engine's topic limit. +package let maximumOverlayNameByteCount = 256 + package func enforceOverlayUTF8Limit(_ value: String, name: String, maximum: Int) throws { try enforceOverlayByteLimit(Array(value.utf8), name: name, maximum: maximum) } diff --git a/Sources/BSVOverlay/TopicBroadcaster.swift b/Sources/BSVOverlay/TopicBroadcaster.swift index e4a4b1c..9a05422 100644 --- a/Sources/BSVOverlay/TopicBroadcaster.swift +++ b/Sources/BSVOverlay/TopicBroadcaster.swift @@ -1,11 +1,39 @@ import BSVCore import BSVTransaction +/// What one broadcast did at each host. +public struct OverlayBroadcastReport: Sendable { + public let transactionID: TransactionID + /// The topics each host acknowledged, for every host that answered with + /// a usable STEAK. + public let acknowledgedTopics: [OverlayHost: Set] + /// Hosts whose submission failed, with the reason, in sorted host order. + /// Their delivery is uncertain: a host may have admitted the transaction + /// before its answer was lost. + public let hostFailures: [OverlayHostFailure] + /// Why the broadcast did not meet its acknowledgment requirements, or nil + /// when it did. + public let failure: OverlayPolicyError? + /// Advertised hosts left out because the host limit was reached. Hosts + /// named in the acknowledgment requirements always keep their places, so + /// a caller that must reach every advertised host can treat a nonzero + /// count as a partial broadcast. + public let skippedHostCount: Int +} + /// A deterministic, one-shot SHIP broadcaster for caller-supplied Atomic BEEF. /// /// This broadcaster has no default resolver, tracker, transport, or retry. It /// discovers signed SHIP advertisements through the injected resolver and -/// submits to each interested host at most once. +/// submits to each interested host at most once, naming only the topics that +/// host advertised. +/// +/// Acknowledgment requirements follow `@bsv/sdk` `SHIPBroadcaster` +/// (`SHIPBroadcaster.ts:466-545`). By default some host must acknowledge every +/// topic, and other hosts may fail: one bogus advertisement does not fail every +/// broadcast. A failed host counts as acknowledging nothing, so a requirement +/// on every host or on a named host fails when that host fails. Requirements +/// are checked against all of the broadcast's topics. public struct OverlayTopicBroadcaster: Sendable { private let topics: [OverlayTopic] private let facilitator: any TopicFacilitator @@ -15,8 +43,11 @@ public struct OverlayTopicBroadcaster: Sendable { private let acknowledgmentByHost: [OverlayHost: AckFrom] private let beefLimits: BEEFLimits private let adminTokenLimits: OverlayAdminTokenLimits + private let discoveredHostPolicy: OverlayDiscoveredHostPolicy private let limits: OverlayLimits + /// `acknowledgmentByHost` keys must be `https://` origins, the only hosts + /// discovery yields; `https://host/` and `https://host` name one host. public init( topics: [OverlayTopic], facilitator: any TopicFacilitator, @@ -26,6 +57,7 @@ public struct OverlayTopicBroadcaster: Sendable { acknowledgmentByHost: [OverlayHost: AckFrom] = [:], beefLimits: BEEFLimits, adminTokenLimits: OverlayAdminTokenLimits = .standard, + discoveredHostPolicy: OverlayDiscoveredHostPolicy = .publicNetworkOnly, limits: OverlayLimits = .standard ) throws { guard !topics.isEmpty else { throw OverlayError.emptyValue(name: "topics") } @@ -56,8 +88,20 @@ public struct OverlayTopicBroadcaster: Sendable { ?? AckFrom(requirement: .all, limits: limits) try Self.validate(every, against: orderedTopics) try Self.validate(any, against: orderedTopics) - for requirement in acknowledgmentByHost.values { + // Discovered hosts are `https://` origins, so a requirement keyed by + // `https://host/` names the same host as `https://host`, and a key + // that is not an origin could never match: `@bsv/sdk` rejects it + // (`snapshotSpecificHostRequirements`). + var requirementsByHost: [OverlayHost: AckFrom] = [:] + for (host, requirement) in acknowledgmentByHost { try Self.validate(requirement, against: orderedTopics) + guard let origin = OverlayAdvertisementURI.httpsOrigin(host.rawValue) else { + throw OverlayError.invalidHost + } + let key = try OverlayHost(rawValue: origin, limits: limits) + guard requirementsByHost.updateValue(requirement, forKey: key) == nil else { + throw OverlayError.duplicateValue(name: "acknowledgmentHosts") + } } self.topics = orderedTopics @@ -65,16 +109,43 @@ public struct OverlayTopicBroadcaster: Sendable { self.resolver = resolver self.acknowledgmentFromEveryHost = every self.acknowledgmentFromAnyHost = any - self.acknowledgmentByHost = acknowledgmentByHost + self.acknowledgmentByHost = requirementsByHost self.beefLimits = beefLimits self.adminTokenLimits = adminTokenLimits + self.discoveredHostPolicy = discoveredHostPolicy self.limits = limits } + /// Broadcasts and throws when the acknowledgment requirements are not met. + /// + /// Throws ``OverlayPolicyError/acknowledgmentFailed`` when every host + /// answered and the requirements are not met, and + /// ``OverlayPolicyError/uncertainDelivery`` when they are not met and a + /// host failed, since that host may have admitted the transaction. Use + /// ``broadcastDetailed(_:offChainValues:)`` to see each host's outcome. public func broadcast( _ atomicBEEF: AtomicBEEF, offChainValues: [UInt8] = [] ) async throws -> BroadcastResult { + let report = try await broadcastDetailed(atomicBEEF, offChainValues: offChainValues) + if let failure = report.failure { throw failure } + let failed = report.hostFailures.count + return BroadcastResult( + transactionID: report.transactionID, + message: failed == 0 + ? "Submitted to \(report.acknowledgedTopics.count) overlay host(s)." + : "Submitted to \(report.acknowledgedTopics.count) overlay host(s); " + + "\(failed) failed." + ) + } + + /// Broadcasts and reports each host's outcome. Throws only before any + /// submission (invalid input, discovery failure, no interested host) or on + /// cancellation; requirement failures are in ``OverlayBroadcastReport/failure``. + public func broadcastDetailed( + _ atomicBEEF: AtomicBEEF, + offChainValues: [UInt8] = [] + ) async throws -> OverlayBroadcastReport { try Task.checkCancellation() let bytes: [UInt8] do { @@ -82,23 +153,67 @@ public struct OverlayTopicBroadcaster: Sendable { } catch { throw OverlayPolicyError.invalidAtomicBEEF } - let tagged = try TaggedBEEF( + // Check the payload against the limits before any network request. + _ = try TaggedBEEF( beef: bytes, topics: topics, offChainValues: offChainValues, limits: limits ) - let hosts = try await interestedHosts() + let (hosts, skippedHostCount) = try await interestedHosts() guard !hosts.isEmpty else { throw OverlayPolicyError.noInterestedHosts } - let results = try await submit(tagged, to: hosts) - try validateAcknowledgments(results) - return BroadcastResult( + var submissions: [(OverlayHost, TaggedBEEF)] = [] + submissions.reserveCapacity(hosts.count) + for (host, hostTopics) in hosts.sorted(by: { $0.key < $1.key }) { + submissions.append( + ( + host, + try TaggedBEEF( + beef: bytes, + topics: hostTopics.sorted(), + offChainValues: offChainValues, + limits: limits + ) + ) + ) + } + let outcomes = try await submit(submissions) + var acknowledged: [OverlayHost: Set] = [:] + var failures: [OverlayHostFailure] = [] + for (host, outcome) in outcomes { + switch outcome { + case .success(let steak): acknowledged[host] = Self.acknowledgedTopics(in: steak) + case .failure(let error): failures.append(OverlayHostFailure(host: host, error: error)) + } + } + for hostFailure in failures { + OverlayLog.hostFailure("OverlayTopicBroadcaster.broadcast", hostFailure) + } + var failure: OverlayPolicyError? + if !requirementsMet(acknowledged, hosts: hosts.keys) { + failure = failures.isEmpty ? .acknowledgmentFailed : .uncertainDelivery + } + return OverlayBroadcastReport( transactionID: atomicBEEF.subjectTransactionID, - message: "Submitted to \(results.count) overlay host(s)." + acknowledgedTopics: acknowledged, + hostFailures: failures, + failure: failure, + skippedHostCount: skippedHostCount ) } - private func interestedHosts() async throws -> [OverlayHost] { + /// Each interested host and the broadcast topics it advertised. + /// + /// Like `@bsv/sdk` `SHIPBroadcaster` (`SHIPBroadcaster.ts:476-482,738-783`), + /// each host is later sent only the topics it advertised, because the + /// overlay engine refuses a submission that names a topic it does not host. + /// As there, hosts past the host limit are left out and counted rather + /// than failing the broadcast. Hosts named in `acknowledgmentByHost` keep + /// their places, so advertisements cannot crowd out a host the caller + /// requires; other hosts fill the rest in the resolver's output order. + private func interestedHosts() async throws -> ( + hosts: [OverlayHost: Set], skipped: Int + ) { let service: OverlayService do { service = try OverlayService(rawValue: "ls_ship", limits: limits) @@ -117,111 +232,110 @@ public struct OverlayTopicBroadcaster: Sendable { } let requested = Set(topics) - var hosts: Set = [] + var hosts: [OverlayHost: Set] = [:] + let unnamedRoom = limits.maximumResolutionHostCount - acknowledgmentByHost.count + var unnamedCount = 0 + var skipped = 0 for output in outputs { guard - let transaction = try? overlayLookupTransaction( - for: output, - beefLimits: beefLimits - ), - Int(output.outputIndex) < transaction.outputs.count, - let token = try? OverlayAdminTokenCodec.decode( - transaction.outputs[Int(output.outputIndex)].lockingScript, - limits: adminTokenLimits + let token = verifiedAdvertisement( + in: output, + beefLimits: beefLimits, + adminTokenLimits: adminTokenLimits, + operation: "OverlayTopicBroadcaster.broadcast" ), case .ship(let topic) = token.subject, - requested.contains(topic) + requested.contains(topic), + let host = advertisedHTTPSHost( + token, policy: discoveredHostPolicy, limits: limits) else { continue } - hosts.insert(token.host) - guard hosts.count <= limits.maximumResolutionHostCount else { - throw OverlayError.limitExceeded( - name: "interestedHosts", - actual: hosts.count, - maximum: limits.maximumResolutionHostCount - ) + if hosts[host] == nil, acknowledgmentByHost[host] == nil { + guard unnamedCount < unnamedRoom else { + skipped += 1 + continue + } + unnamedCount += 1 } + hosts[host, default: []].insert(topic) + } + if skipped > 0 { + OverlayLog.skippedHosts( + "OverlayTopicBroadcaster.broadcast", count: skipped, + limit: limits.maximumResolutionHostCount) } - return hosts.sorted() + return (hosts, skipped) } + /// Each host's STEAK or failure, in host order. A host that answers with + /// an empty STEAK, or acknowledges a topic it was not sent, has failed, as + /// in `@bsv/sdk` (`SHIPBroadcaster.ts:476-496`). private func submit( - _ taggedBEEF: TaggedBEEF, - to hosts: [OverlayHost] - ) async throws -> [OverlayHost: Steak] { - var indexed: [(Int, OverlayHost, Steak)] = [] - var uncertain = false + _ submissions: [(OverlayHost, TaggedBEEF)] + ) async throws -> [(OverlayHost, Result)] { + var indexed: [(Int, Result)] = [] let width = limits.maximumConcurrentRequestCount var start = 0 - while start < hosts.count { - try Task.checkCancellation() - let end = min(hosts.count, start + width) - await withTaskGroup(of: OverlaySubmissionOutcome.self) { group in + while start < submissions.count { + if Task.isCancelled { + if start == 0 { throw CancellationError() } + throw OverlayPolicyError.uncertainDelivery + } + let end = min(submissions.count, start + width) + await withTaskGroup(of: (Int, Result).self) { group in for index in start..], + hosts: Dictionary>.Keys + ) -> Bool { + let none: Set = [] + guard !acknowledged.isEmpty else { return false } + guard + hosts.allSatisfy({ + Self.satisfies(acknowledgmentFromEveryHost, acknowledged[$0] ?? none, topics) + }) + else { return false } + guard + acknowledged.values.contains(where: { + Self.satisfies(acknowledgmentFromAnyHost, $0, topics) + }) + else { return false } + // A named host that discovery did not return fails even a `.none` + // requirement, as in `@bsv/sdk` (`SHIPBroadcaster.ts:659-662`). for (host, requirement) in acknowledgmentByHost { - guard let steak = results[host], - Self.satisfies(requirement, steak: steak, allTopics: topics) + guard hosts.contains(host), + Self.satisfies(requirement, acknowledged[host] ?? none, topics) else { - throw OverlayPolicyError.acknowledgmentFailed + return false } } + return true } private static func validate( @@ -235,16 +349,19 @@ public struct OverlayTopicBroadcaster: Sendable { } } - private static func satisfies( - _ requirement: AckFrom, - steak: Steak, - allTopics: [OverlayTopic] - ) -> Bool { - let acknowledged = Set( + private static func acknowledgedTopics(in steak: Steak) -> Set { + Set( steak.instructions.compactMap { topic, instruction in instruction.acknowledgesTopic ? topic : nil } ) + } + + private static func satisfies( + _ requirement: AckFrom, + _ acknowledged: Set, + _ allTopics: [OverlayTopic] + ) -> Bool { switch requirement.requirement { case .none: return true @@ -257,8 +374,3 @@ public struct OverlayTopicBroadcaster: Sendable { } } } - -private enum OverlaySubmissionOutcome: Sendable { - case success(Int, OverlayHost, Steak) - case uncertain -} diff --git a/Sources/BSVTransaction/BEEF/BEEFGraphOperations.swift b/Sources/BSVTransaction/BEEF/BEEFGraphOperations.swift index 6b053bd..b16e8a3 100644 --- a/Sources/BSVTransaction/BEEF/BEEFGraphOperations.swift +++ b/Sources/BSVTransaction/BEEF/BEEFGraphOperations.swift @@ -334,3 +334,111 @@ private struct BEEFReadyHeap { rank[left, default: .max] < rank[right, default: .max] } } + +extension BEEF { + /// The subject transaction and the records it depends on, as one BRC-95 + /// envelope: the selection `Beef.toBinaryAtomic` makes in `@bsv/sdk` + /// (`transaction/Beef.ts:385-475`). + /// + /// Ancestors are followed through inputs until a record is proven by its + /// own Merkle path or is transaction-ID-only. As in `@bsv/sdk`, a raw record + /// whose transaction ID merely appears in another record's Merkle path is + /// not treated as proven, so its inputs are still followed. The Merkle + /// paths kept are those the selected records reference, in the order this + /// envelope's records (parents first) first reference them. `@bsv/sdk` + /// uses the order the records arrived in, so when a sender lists a child + /// before its parents the two can write the same paths in another order. + /// Throws ``BEEFError/missingSubjectTransaction(_:)`` + /// when the subject is absent and ``BEEFError/missingAncestor(transaction:ancestor:)`` + /// when an unproven selected record spends a transaction this envelope lacks. + package func atomicBEEF( + for subject: TransactionID, + limits: BEEFLimits + ) throws -> AtomicBEEF { + let identifiers = try transactions.map { + try $0.transactionID(limits: limits.transactionLimits) + } + return try atomicBEEF(for: subject, identifiers: identifiers, limits: limits) + } + + /// ``atomicBEEF(for:limits:)`` with each record's transaction ID already + /// computed, in record order, so that a caller building many envelopes + /// from one BEEF hashes each record once. + package func atomicBEEF( + for subject: TransactionID, + identifiers: [TransactionID], + limits: BEEFLimits + ) throws -> AtomicBEEF { + guard identifiers.count == transactions.count else { + return try atomicBEEF(for: subject, limits: limits) + } + var entries: [TransactionID: BEEFTransaction] = [:] + for (transactionID, entry) in zip(identifiers, transactions) { + entries[transactionID] = entry + } + guard entries[subject] != nil else { + throw BEEFError.missingSubjectTransaction(subject) + } + + var included: Set = [] + var pending = [subject] + while let transactionID = pending.popLast() { + guard !included.contains(transactionID), let entry = entries[transactionID] else { + continue + } + included.insert(transactionID) + guard entry.format != .transactionIDOnly, + !hasOwnMerklePath(transactionID, entry: entry), + let transaction = entry.transaction + else { continue } + for input in transaction.inputs { + pending.append(input.previousOutput.transactionID) + } + } + + var pathMap: [Int: Int] = [:] + var paths: [MerklePath] = [] + var selected: [BEEFTransaction] = [] + for (transactionID, entry) in zip(identifiers, transactions) + where included.contains(transactionID) { + if case .rawWithMerklePath(let transaction, let oldIndex) = entry { + let newIndex: Int + if let mapped = pathMap[oldIndex] { + newIndex = mapped + } else { + guard merklePaths.indices.contains(oldIndex) else { + throw BEEFError.merklePathIndexOutOfRange( + transaction: selected.count, + index: UInt64(oldIndex), + count: merklePaths.count + ) + } + newIndex = paths.count + pathMap[oldIndex] = newIndex + paths.append(merklePaths[oldIndex]) + } + selected.append( + .rawWithMerklePath(transaction: transaction, merklePathIndex: newIndex) + ) + } else { + selected.append(entry) + } + } + + let beef = try BEEF( + version: version, + merklePaths: paths, + transactions: selected, + limits: limits + ) + return try AtomicBEEF(subjectTransactionID: subject, beef: beef, limits: limits) + } + + /// `#hasMatchingBump` in `@bsv/sdk`: the record's own Merkle path proves it. + private func hasOwnMerklePath(_ transactionID: TransactionID, entry: BEEFTransaction) -> Bool { + guard let index = entry.merklePathIndex, merklePaths.indices.contains(index) else { + return false + } + return Self.path(merklePaths[index], contains: transactionID) + } +} diff --git a/Tests/BSVNetworkTests/Overlay/OverlayHTTPFacilitatorTests.swift b/Tests/BSVNetworkTests/Overlay/OverlayHTTPFacilitatorTests.swift index 4656057..3153a4d 100644 --- a/Tests/BSVNetworkTests/Overlay/OverlayHTTPFacilitatorTests.swift +++ b/Tests/BSVNetworkTests/Overlay/OverlayHTTPFacilitatorTests.swift @@ -49,7 +49,6 @@ struct OverlayHTTPFacilitatorTests { func strictLookupJSON() async throws { let bodies = [ #"{"type":"freeform","type":"freeform","result":1}"#, - #"{"type":"freeform","result":1,"extra":2}"#, #"{"type":"output-list","outputs":[{"beef":"AQ==","outputIndex":true}]}"#, #"{"type":"formula","result":{}}"#, ] @@ -122,7 +121,9 @@ struct OverlayHTTPFacilitatorTests { } #expect(outputs.count == 1) #expect(outputs[0].outputIndex == 0) - #expect(outputs[0].beef == fixture.beef) + // Each output carries its own transaction as Atomic BEEF. + #expect(outputs[0].beef == [1, 1, 1, 1] + fixture.transactionID.wireBytes + fixture.beef) + #expect(outputs[0].transactionID == fixture.transactionID) var noncanonical = fixture.response noncanonical.replaceSubrange(0...0, with: [0xfd, 0x01, 0x00]) @@ -166,7 +167,7 @@ struct OverlayHTTPFacilitatorTests { let request = try #require(await transport.lastRequest()) #expect(request.url.absoluteString == "https://overlay.example/submit") #expect(request.body == Data([1, 2, 3])) - #expect(request.headers["X-Topics"] == #"["tm_test"]"#) + #expect(request.headers["X-Topics"] == "tm_test") #expect(await transport.requestCount() == 1) } @@ -183,7 +184,7 @@ struct OverlayHTTPFacilitatorTests { ) for value in [ "http://overlay.example", "https://user@overlay.example", - "https://overlay.example/path", "https://overlay.example/", + "https://overlay.example/path", "https://overlay.example?x=1", ] { await #expect(throws: OverlayHTTPError.invalidHost) { try await lookup.lookup( @@ -269,6 +270,7 @@ struct OverlayHTTPFacilitatorTests { private func binaryFixture() throws -> ( configuration: OverlayHTTPConfiguration, beef: [UInt8], + transactionID: TransactionID, response: [UInt8] ) { let limits = try beefLimits() @@ -295,6 +297,7 @@ struct OverlayHTTPFacilitatorTests { return ( try OverlayHTTPConfiguration(beefLimits: limits), beef, + transactionID, response ) } diff --git a/Tests/BSVNetworkTests/Overlay/OverlayTSWireTests.swift b/Tests/BSVNetworkTests/Overlay/OverlayTSWireTests.swift new file mode 100644 index 0000000..cf8a315 --- /dev/null +++ b/Tests/BSVNetworkTests/Overlay/OverlayTSWireTests.swift @@ -0,0 +1,621 @@ +import BSVCore +import BSVOverlay +import BSVScript +import BSVTransaction +import Foundation +import Testing + +@testable import BSVNetwork + +/// Wire vectors produced by `@bsv/sdk` 4.1.1 (ts-stack `3b1abc569`) running its +/// own code: the Overlay Express aggregation writer +/// (`packages/overlays/overlay-express/src/OverlayExpress.ts:3063-3093`), the +/// SDK's `HTTPSOverlayLookupFacilitator.lookup` +/// (`packages/sdk/src/overlay-tools/LookupResolver.ts:746-950`) and +/// `HTTPSOverlayBroadcastFacilitator.send` +/// (`packages/sdk/src/overlay-tools/SHIPBroadcaster.ts:323-383`). +@Suite("Overlay HTTP matches the @bsv/sdk wire") +struct OverlayTSWireTests { + // Transactions: P (no inputs, one 5-sat OP_1 output), A spends P:0 (one + // OP_2 output), B (no inputs, outputs OP_3, OP_4, OP_5). The answer lists + // A:0 with no context and B:1 with context [1, 2, 3] over one BEEF + // holding P, B, A. + static let transactionA = "3269c6da874a2e369c06c2329a8da3ab2946e09783362ab7d11adc9e2723f109" + static let transactionB = "2353d778130b8437b4dd336eb5448a68ce53e0fbdf5e1b38b7b472f6cb804344" + static let aggregatedAnswer = + "023269c6da874a2e369c06c2329a8da3ab2946e09783362ab7d11adc9e2723f10900002353d778130b84" + + "37b4dd336eb5448a68ce53e0fbdf5e1b38b7b472f6cb80434401030102030200beef0003000100000000" + + "01050000000000000001510000000000010000000003010000000000000001530200000000000000015403" + + "000000000000000155000000000001000000017465e7c7ce5f8ca7b7bc9e66daa2d47295beb8b1404835" + + "6dee48f4838428ce77000000000151ffffffff010400000000000000015200000000" + // `extractAtomicOutputs` output: `beefObj.toBinaryAtomic(txid)` per output. + static let atomicA = + "0101010109f123279edc1ad1b72a368397e04629aba38d9a32c2069c362e4a87dac669320200beef0002" + + "0001000000000105000000000000000151000000000001000000017465e7c7ce5f8ca7b7bc9e66daa2d4" + + "7295beb8b14048356dee48f4838428ce77000000000151ffffffff010400000000000000015200000000" + static let atomicB = + "01010101444380cbf672b4b7381b5edffbe053ce688a44b56e33ddb437840b1378d753230200beef0001" + + "0001000000000301000000000000000153020000000000000001540300000000000000015500000000" + + @Test("O1: an aggregated answer gives each output its own transaction as Atomic BEEF") + func aggregatedAnswerKeepsEachTransaction() async throws { + let answer = try await lookup( + body: try bytes(Self.aggregatedAnswer), + contentType: "application/octet-stream" + ) + guard case .outputList(let outputs) = answer else { + Issue.record("Expected an output list") + return + } + #expect(outputs.count == 2) + #expect(outputs[0].beef == (try bytes(Self.atomicA))) + #expect(outputs[0].outputIndex == 0) + #expect(outputs[0].context == nil) + #expect(outputs[0].transactionID == (try TransactionID(displayHex: Self.transactionA))) + #expect(outputs[1].beef == (try bytes(Self.atomicB))) + #expect(outputs[1].outputIndex == 1) + #expect(outputs[1].context == [1, 2, 3]) + #expect(outputs[1].transactionID == (try TransactionID(displayHex: Self.transactionB))) + + let limits = try beefLimits() + let first = try overlayLookupTransaction(for: outputs[0], beefLimits: limits) + let second = try overlayLookupTransaction(for: outputs[1], beefLimits: limits) + #expect(try first.transactionID(limits: limits.transactionLimits).displayHex == Self.transactionA) + #expect(try second.transactionID(limits: limits.transactionLimits).displayHex == Self.transactionB) + #expect(second.outputs[1].satoshis == 2) + } + + @Test("O1: the resolver keeps every outpoint of an aggregated answer") + func resolverKeepsAggregatedOutpoints() async throws { + let transport = OverlayTSRecordingTransport( + response: HTTPResponse( + statusCode: 200, + headers: ["Content-Type": "application/octet-stream"], + body: Data(try bytes(Self.aggregatedAnswer)) + ) + ) + let service = try OverlayService(rawValue: "ls_test") + let limits = try beefLimits() + let resolver = try LookupResolver( + facilitator: HTTPSOverlayLookupFacilitator( + configuration: try OverlayHTTPConfiguration(beefLimits: limits), + transport: transport + ), + slapTrackers: [], + hostOverrides: [service: [OverlayHost(rawValue: "https://overlay.example")]], + beefLimits: limits + ) + let answer = try await resolver.resolve(LookupQuestion(service: service, query: [0x7b, 0x7d])) + guard case .outputList(let outputs) = answer else { + Issue.record("Expected an output list") + return + } + let keys = try outputs.map { output in + let transaction = try overlayLookupTransaction(for: output, beefLimits: limits) + return "\(try transaction.transactionID(limits: limits.transactionLimits).displayHex):\(output.outputIndex)" + } + #expect(keys == ["\(Self.transactionB):1", "\(Self.transactionA):0"]) + } + + @Test("O1: an output whose ancestry is incomplete still names its own transaction") + func aggregatedAnswerWithMissingAncestor() async throws { + // The same answer with P removed from the BEEF: A spends a transaction + // the envelope lacks, so no Atomic BEEF exists for A. + let limits = try beefLimits() + var cursor = try bytes(Self.aggregatedAnswer) + let shared = Array(cursor[(cursor.count - 131)...]) + let beef = try BEEF(bytes: shared, limits: limits, transactionOrder: .any) + let trimmed = try BEEF( + version: .v2, + merklePaths: [], + transactions: beef.transactions.filter { $0.transaction?.outputs.first?.satoshis != 5 }, + limits: limits + ).serialized(limits: limits) + #expect(trimmed.count < shared.count) + cursor.removeLast(131) + cursor.append(contentsOf: trimmed) + + let answer = try await lookup(body: cursor, contentType: "application/octet-stream") + guard case .outputList(let outputs) = answer else { + Issue.record("Expected an output list") + return + } + #expect(outputs[0].beef == trimmed) + let first = try overlayLookupTransaction(for: outputs[0], beefLimits: limits) + #expect(try first.transactionID(limits: limits.transactionLimits).displayHex == Self.transactionA) + #expect(outputs[1].beef == (try bytes(Self.atomicB))) + } + + @Test("O1: per-output context up to 1 MiB is accepted, as in @bsv/sdk") + func largeContext() async throws { + var body = CompactSize.encode(1) + body.append(contentsOf: try TransactionID(displayHex: Self.transactionB).displayBytes) + body.append(contentsOf: CompactSize.encode(0)) + let context = [UInt8](repeating: 7, count: 1_024 * 1_024) + body.append(contentsOf: CompactSize.encode(UInt64(context.count))) + body.append(contentsOf: context) + body.append(contentsOf: Array(try bytes(Self.atomicB).dropFirst(36))) + let answer = try await lookup(body: body, contentType: "application/octet-stream") + guard case .outputList(let outputs) = answer else { + Issue.record("Expected an output list") + return + } + #expect(outputs[0].context?.count == context.count) + + body = CompactSize.encode(1) + body.append(contentsOf: try TransactionID(displayHex: Self.transactionB).displayBytes) + body.append(contentsOf: CompactSize.encode(0)) + body.append(contentsOf: CompactSize.encode(UInt64(context.count + 1))) + body.append(contentsOf: context + [7]) + body.append(contentsOf: Array(try bytes(Self.atomicB).dropFirst(36))) + await #expect(throws: OverlayHTTPError.resourceLimit) { + _ = try await lookup(body: body, contentType: "application/octet-stream") + } + } + + @Test("O6: a JSON output list with byte arrays, context, and txid decodes") + func jsonOutputList() async throws { + // `res.json(result)` from Overlay Express with an engine result, as + // `HTTPSOverlayLookupFacilitator` reads it (`LookupResolver.ts:327-358`). + let json = #"{"type":"output-list","outputs":[{"beef":[1,0,190,239,0,1,1,0,0,0,0,3,1,0,0,0,0,0,0,0,1,83,2,0,0,0,0,0,0,0,1,84,3,0,0,0,0,0,0,0,1,85,0,0,0,0,0],"outputIndex":2,"context":[9,8],"txid":"2353d778130b8437b4dd336eb5448a68ce53e0fbdf5e1b38b7b472f6cb804344"}]}"# + let answer = try await lookup(body: Array(json.utf8), contentType: "application/json; charset=utf-8") + guard case .outputList(let outputs) = answer else { + Issue.record("Expected an output list") + return + } + #expect(outputs.count == 1) + #expect(outputs[0].outputIndex == 2) + #expect(outputs[0].context == [9, 8]) + #expect(outputs[0].transactionID == (try TransactionID(displayHex: Self.transactionB))) + #expect(Array(outputs[0].beef.prefix(4)) == [1, 0, 190, 239]) + let limits = try beefLimits() + let transaction = try overlayLookupTransaction(for: outputs[0], beefLimits: limits) + #expect(transaction.outputs[2].satoshis == 3) + + let accepted = [ + #"{"type":"output-list","outputs":[]}"#, + // Unknown keys are kept by `normalizeLookupOutput`; uppercase txid hex is valid. + #"{"type":"output-list","outputs":[],"extra":1}"#, + #"{"type":"output-list","outputs":[{"beef":{"0":1,"1":2},"outputIndex":0,"note":"x","txid":"2353D778130B8437B4DD336EB5448A68CE53E0FBDF5E1B38B7B472F6CB804344"}]}"#, + // Go hosts write `[]byte` as base64. + #"{"type":"output-list","outputs":[{"beef":"AQI=","outputIndex":0}]}"#, + #"{"type":"freeform","result":{"ok":true},"extra":2}"#, + ] + for body in accepted { + _ = try await lookup(body: Array(body.utf8), contentType: "application/json") + } + + let rejected = [ + #"{"type":"output-list","outputs":[{"beef":[],"outputIndex":0}]}"#, + #"{"type":"output-list","outputs":[{"beef":[256],"outputIndex":0}]}"#, + #"{"type":"output-list","outputs":[{"beef":[1],"outputIndex":-1}]}"#, + #"{"type":"output-list","outputs":[{"beef":[1],"outputIndex":0,"context":null}]}"#, + #"{"type":"output-list","outputs":[{"beef":[1],"outputIndex":0,"txid":"00"}]}"#, + #"{"type":"output-list","outputs":[{"beef":{"1":1},"outputIndex":0}]}"#, + ] + for body in rejected { + await #expect(throws: OverlayHTTPError.self) { + _ = try await lookup(body: Array(body.utf8), contentType: "application/json") + } + } + } + + @Test("O6: a JSON output's txid selects its transaction in a multi-transaction BEEF") + func jsonTransactionIDSelects() async throws { + let shared = Array(try bytes(Self.aggregatedAnswer).suffix(131)) + let json = """ + {"type":"output-list","outputs":[{"beef":\(shared),"outputIndex":0,"txid":"\(Self.transactionA)"}]} + """ + let answer = try await lookup(body: Array(json.utf8), contentType: "application/json") + guard case .outputList(let outputs) = answer else { + Issue.record("Expected an output list") + return + } + let limits = try beefLimits() + let transaction = try overlayLookupTransaction(for: outputs[0], beefLimits: limits) + #expect(try transaction.transactionID(limits: limits.transactionLimits).displayHex == Self.transactionA) + } + + @Test("O2: camelCase STEAK from a TS host is an acknowledgment") + func camelCaseSteak() async throws { + // `validateSTEAK` (`SHIPBroadcaster.ts:237-262`) and the engine's + // `{ outputsToAdmit, coinsToRetain }` shape. + let topic = try OverlayTopic(rawValue: "tm_test") + for body in [ + #"{"tm_test":{"outputsToAdmit":[0],"coinsToRetain":[],"coinsRemoved":[]}}"#, + #"{"tm_test":{"outputsToAdmit":[0],"coinsToRetain":[]}}"#, + #"{"tm_test":{"OutputsToAdmit":[0],"CoinsToRetain":null}}"#, + ] { + let steak = try await submit(responseBody: body, topics: [topic]).steak + #expect(steak.acknowledges(topic)) + } + for body in [ + #"{"tm_test":{"outputsToAdmit":[0]}}"#, + #"{"tm_test":{"outputsToAdmit":[0],"coinsToRetain":null}}"#, + #"{"tm_test":{"outputsToAdmit":[0],"coinsToRetain":[],"extra":[]}}"#, + #"{"tm_test":{"outputsToAdmit":[0],"CoinsToRetain":[]}}"#, + #"{"tm_other":{"outputsToAdmit":[0],"coinsToRetain":[]}}"#, + ] { + await #expect(throws: OverlayHTTPError.malformedResponse) { + _ = try await submit(responseBody: body, topics: [topic]) + } + } + } + + @Test("O8 and O12: submit sends comma-separated topics and length-prefixed off-chain values") + func submitRequestShape() async throws { + let a = try OverlayTopic(rawValue: "tm_a") + let b = try OverlayTopic(rawValue: "tm_b") + let response = #"{"tm_a":{"outputsToAdmit":[0],"coinsToRetain":[]}}"# + let withValues = try await submit( + responseBody: response, + topics: [a, b], + beef: [0xaa, 0xbb, 0xcc], + offChainValues: [1, 2], + host: "https://overlay.example/" + ).request + #expect(withValues.url.absoluteString == "https://overlay.example/submit") + #expect(withValues.headers["X-Topics"] == "tm_a,tm_b") + #expect(withValues.headers["x-includes-off-chain-values"] == "true") + #expect(withValues.headers["Content-Type"] == "application/octet-stream") + #expect(withValues.body == Data([0x03, 0xaa, 0xbb, 0xcc, 0x01, 0x02])) + + let plain = try await submit( + responseBody: response, + topics: [a], + beef: [0xaa, 0xbb, 0xcc] + ).request + #expect(plain.headers["X-Topics"] == "tm_a") + #expect(plain.headers["x-includes-off-chain-values"] == nil) + #expect(plain.body == Data([0xaa, 0xbb, 0xcc])) + } + + @Test("O14 and O18: an origin with one trailing slash, any 2xx, and any JSON content type work") + func hostAndStatusRules() async throws { + let transport = OverlayTSRecordingTransport( + response: HTTPResponse( + statusCode: 201, + headers: ["Content-Type": "text/plain"], + body: Data(#"{"type":"freeform","result":1}"#.utf8) + ) + ) + let facilitator = HTTPSOverlayLookupFacilitator( + configuration: try OverlayHTTPConfiguration(beefLimits: beefLimits()), + transport: transport + ) + let answer = try await facilitator.lookup( + question: LookupQuestion(service: OverlayService(rawValue: "ls_test"), query: [0x7b, 0x7d]), + at: OverlayHost(rawValue: "https://overlay.example/") + ) + #expect(answer == .freeform(Array("1".utf8))) + #expect(await transport.lastRequest()?.url.absoluteString == "https://overlay.example/lookup") + } + + // A 4-transaction, 2-BUMP BEEF from `@bsv/sdk` `Beef.toBinary`, and + // `toBinaryAtomic` of B (`transaction/Beef.ts:385-475`). M1 is proven by + // BUMP 0 and M2 by BUMP 1; A spends M1:0 and B spends M2:0; the records are + // written M1, M2, B, A. Atomic B keeps only BUMP 1, renumbered 0. The + // records arrive parents first, so the bytes match TS; when a child comes + // before its parents, Swift may write the kept BUMPs in another order. + static let bumpedShared = + "0200beef02640102000243c78955a7a87a2d73710d5f5708974577bbb50254cc172bee459f74345368ab" + + "0100aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa6501020000aaaaaa" + + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0102de3b6fbd6a1b017db43276" + + "5e31d2136d875f36d3583641d36bf794139b72bbdf0401000100000000010b0000000000000001530000" + + "000001010100000000010c00000000000000015400000000000100000001de3b6fbd6a1b017db432765e" + + "31d2136d875f36d3583641d36bf794139b72bbdf000000000151ffffffff02060000000000000001570700" + + "00000000000001580000000000010000000143c78955a7a87a2d73710d5f5708974577bbb50254cc172b" + + "ee459f74345368ab000000000151ffffffff010500000000000000015600000000" + static let bumpedTransactionB = "72a7517cdd5eaab0a408c353151deb54740dee851816c940dc83938c3d0b3d0e" + static let bumpedAtomicB = + "010101010e3d0b3d8c9383dc40c9161885ee0d7454eb1d1553c308a4b0aa5edd7c51a7720200beef0165" + + "01020000aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0102de3b6fbd" + + "6a1b017db432765e31d2136d875f36d3583641d36bf794139b72bbdf0201000100000000010c00000000" + + "000000015400000000000100000001de3b6fbd6a1b017db432765e31d2136d875f36d3583641d36bf794" + + "139b72bbdf000000000151ffffffff02060000000000000001570700000000000000015800000000" + + @Test("S4: Atomic BEEF keeps and renumbers only the Merkle paths its records use") + func aggregatedAnswerWithMerklePaths() async throws { + var body = CompactSize.encode(1) + body.append(contentsOf: try TransactionID(displayHex: Self.bumpedTransactionB).displayBytes) + body.append(contentsOf: CompactSize.encode(1)) + body.append(contentsOf: CompactSize.encode(0)) + body.append(contentsOf: try bytes(Self.bumpedShared)) + let answer = try await lookup(body: body, contentType: "application/octet-stream") + guard case .outputList(let outputs) = answer else { + Issue.record("Expected an output list") + return + } + #expect(outputs.count == 1) + #expect(outputs[0].beef == (try bytes(Self.bumpedAtomicB))) + let limits = try beefLimits() + let transaction = try outputs[0].transaction(beefLimits: limits) + #expect( + try transaction.transactionID(limits: limits.transactionLimits).displayHex + == Self.bumpedTransactionB) + } + + @Test("S1: only a missing ancestor falls back to the shared BEEF") + func atomicFailureIsNotSwallowed() async throws { + // B alone: its Atomic BEEF is 36 bytes longer than the shared BEEF, so + // a BEEF limit equal to the shared size admits the answer but not the + // Atomic BEEF. That must fail the answer, not quietly hand back the + // shared BEEF. + let shared = Array(try bytes(Self.atomicB).dropFirst(36)) + var body = CompactSize.encode(1) + body.append(contentsOf: try TransactionID(displayHex: Self.transactionB).displayBytes) + body.append(contentsOf: CompactSize.encode(0)) + body.append(contentsOf: CompactSize.encode(0)) + body.append(contentsOf: shared) + let tight = try beefLimits(maximumByteCount: shared.count) + await #expect(throws: OverlayHTTPError.resourceLimit) { + _ = try await lookup(body: body, contentType: "application/octet-stream", beefLimits: tight) + } + } + + @Test("S2: an output's transaction is public API") + func publicOutputTransaction() throws { + let limits = try beefLimits() + let shared = Array(try bytes(Self.aggregatedAnswer).suffix(131)) + for (id, satoshis) in [(Self.transactionA, UInt64(4)), (Self.transactionB, UInt64(1))] { + let item = try OutputListItem( + beef: shared, outputIndex: 0, transactionID: try TransactionID(displayHex: id)) + #expect(try item.transaction(beefLimits: limits).outputs[0].satoshis == satoshis) + } + let missing = try OutputListItem( + beef: Array(try bytes(Self.atomicB).dropFirst(36)), outputIndex: 0, + transactionID: try TransactionID(displayHex: Self.transactionA)) + #expect(throws: OverlayPolicyError.invalidLookupOutput) { + _ = try missing.transaction(beefLimits: limits) + } + } + + @Test("S8: JSON answers are read without building every value") + func jsonReaderShapes() async throws { + let beef = Array(try bytes(Self.atomicB).dropFirst(36)) + let numbers = beef.map(String.init).joined(separator: ",") + let keyed = beef.enumerated().reversed().map { "\"\($0.offset)\":\($0.element)" } + .joined(separator: ",") + let bodies = [ + // `outputs` before `type`, unknown nested values, whitespace. + "{ \"outputs\" : [ {\"skip\":[[1,2],{\"a\":\"]}\\\"\"}],\"beef\": [\(numbers)] ,\"outputIndex\":1.0} ], \"type\":\"output-list\" }", + // Numeric-key object in any key order. + "{\"type\":\"output-list\",\"outputs\":[{\"outputIndex\":1,\"beef\":{\(keyed)}}]}", + ] + for body in bodies { + let answer = try await lookup(body: Array(body.utf8), contentType: "application/json") + guard case .outputList(let outputs) = answer else { + Issue.record("Expected an output list") + return + } + #expect(outputs.count == 1) + #expect(outputs[0].beef == beef) + #expect(outputs[0].outputIndex == 1) + } + + // A freeform answer ignores `outputs`, whatever it holds. + #expect( + try await lookup( + body: Array(#"{"outputs":7,"type":"freeform","result":[1,"a"]}"#.utf8), + contentType: "application/json") == .freeform(Array(#"[1,"a"]"#.utf8))) + + // Repeated or out-of-range numeric keys, and non-byte elements, are malformed. + for body in [ + #"{"type":"output-list","outputs":[{"beef":{"0":1,"2":1},"outputIndex":0}]}"#, + #"{"type":"output-list","outputs":[{"beef":[1,true],"outputIndex":0}]}"#, + #"{"type":"output-list","outputs":[{"beef":[1,1.5],"outputIndex":0}]}"#, + #"{"type":"output-list","outputs":[{"beef":[1],"outputIndex":"0"}]}"#, + #"{"type":"output-list","outputs":{}}"#, + #"{"type":1,"outputs":[]}"#, + #"[{"type":"output-list"}]"#, + ] { + await #expect(throws: OverlayHTTPError.malformedResponse, "\(body)") { + _ = try await lookup(body: Array(body.utf8), contentType: "application/json") + } + } + } + + @Test("S8: a freeform result's text is bounded before it is parsed") + func freeformTextBound() async throws { + let limits = try OverlayLimits( + maximumTaggedBEEFByteCount: 1_024, + maximumOffChainValueByteCount: 1_024, + maximumTopicCount: 16, + maximumTopicUTF8ByteCount: 256, + maximumServiceUTF8ByteCount: 256, + maximumHostUTF8ByteCount: 2_048, + maximumMetadataUTF8ByteCount: 1_024, + maximumLookupQueryByteCount: 1_024, + maximumLookupOutputCount: 16, + maximumLookupOutputBEEFByteCount: 1_024, + maximumFreeformByteCount: 64 + ) + let padded = "{\"type\":\"freeform\",\"result\":[1" + String(repeating: " ", count: 200) + "]}" + let facilitator = HTTPSOverlayLookupFacilitator( + configuration: try OverlayHTTPConfiguration(overlayLimits: limits, beefLimits: beefLimits()), + transport: OverlayTSRecordingTransport( + response: HTTPResponse( + statusCode: 200, headers: ["Content-Type": "application/json"], + body: Data(padded.utf8)) + ) + ) + await #expect(throws: OverlayHTTPError.resourceLimit) { + _ = try await facilitator.lookup( + question: LookupQuestion( + service: OverlayService(rawValue: "ls_test"), query: [0x7b, 0x7d]), + at: OverlayHost(rawValue: "https://overlay.example")) + } + } + + @Test("N5: an instruction object with no keys is malformed, as validateSTEAK finds") + func emptyInstructionObject() async throws { + let topic = try OverlayTopic(rawValue: "tm_test") + await #expect(throws: OverlayHTTPError.malformedResponse) { + _ = try await submit(responseBody: #"{"tm_test":{}}"#, topics: [topic]) + } + } + + @Test("N6: a JSON answer over the answer limit is a resource limit") + func oversizedJSONAnswer() throws { + let configuration = try OverlayHTTPConfiguration(beefLimits: beefLimits()) + let limit = configuration.overlayLimits.maximumLookupAnswerByteCount + let body = [UInt8]("{\"type\":\"freeform\",\"result\":\"".utf8) + + [UInt8](repeating: 0x61, count: limit) + [UInt8]("\"}".utf8) + #expect(throws: OverlayHTTPError.resourceLimit) { + _ = try OverlayHTTPCodec.lookupJSONResponse(body, configuration: configuration) + } + } + + @Test("M1: Atomic BEEF built for an aggregated chain stops at the answer limit") + func aggregatedChainIsBounded() throws { + // 900 unproven transactions, each spending the one before and each + // listed as an output: about 1 MB on the wire, but Atomic BEEF i holds + // i transactions, so building all of them would take about 400 MB. + // The build must stop once the answer limit is passed. Before the + // fix this took about 40 seconds and 900 MB. + let beefLimits = try beefLimits() + let pad = [UInt8](repeating: 0, count: 1_000) + let script = try Script(bytes: [0x00, 0x6a, 0x4d, 0xe8, 0x03] + pad, maximumByteCount: 2_000) + let unlocking = try Script(bytes: [0x51], maximumByteCount: 1) + var transactions: [BEEFTransaction] = [] + var identifiers: [TransactionID] = [] + for _ in 0..<900 { + let inputs = identifiers.last.map { + [ + TransactionInput( + previousOutput: Outpoint(transactionID: $0, outputIndex: 0), + unlockingScript: unlocking) + ] + } ?? [] + let transaction = Transaction( + inputs: inputs, outputs: [TransactionOutput(satoshis: 1, lockingScript: script)]) + identifiers.append(try transaction.transactionID(limits: beefLimits.transactionLimits)) + transactions.append(.raw(transaction)) + } + let shared = try BEEF( + version: .v2, merklePaths: [], transactions: transactions, limits: beefLimits + ).serialized(limits: beefLimits) + var body = CompactSize.encode(UInt64(identifiers.count)) + for identifier in identifiers { + body.append(contentsOf: identifier.displayBytes) + body.append(contentsOf: CompactSize.encode(0)) + body.append(contentsOf: CompactSize.encode(0)) + } + body.append(contentsOf: shared) + + let configuration = try OverlayHTTPConfiguration( + overlayLimits: try OverlayLimits( + maximumTaggedBEEFByteCount: 1_024, + maximumOffChainValueByteCount: 1_024, + maximumTopicCount: 16, + maximumTopicUTF8ByteCount: 256, + maximumServiceUTF8ByteCount: 256, + maximumHostUTF8ByteCount: 2_048, + maximumMetadataUTF8ByteCount: 1_024, + maximumLookupQueryByteCount: 1_024, + maximumLookupOutputCount: 1_000, + maximumLookupOutputBEEFByteCount: 32 * 1_024 * 1_024, + maximumLookupAnswerByteCount: 4 * 1_024 * 1_024, + maximumFreeformByteCount: 1_024 + ), + beefLimits: beefLimits + ) + let clock = ContinuousClock() + let elapsed = clock.measure { + #expect(throws: OverlayHTTPError.resourceLimit) { + _ = try OverlayHTTPCodec.lookupBinaryResponse(body, configuration: configuration) + } + } + #expect(elapsed < .seconds(10)) + } + + // MARK: Helpers + + private func lookup( + body: [UInt8], + contentType: String, + beefLimits: BEEFLimits? = nil + ) async throws -> LookupAnswer { + let facilitator = HTTPSOverlayLookupFacilitator( + configuration: try OverlayHTTPConfiguration(beefLimits: beefLimits ?? self.beefLimits()), + transport: OverlayTSRecordingTransport( + response: HTTPResponse( + statusCode: 200, + headers: ["Content-Type": contentType], + body: Data(body) + ) + ) + ) + return try await facilitator.lookup( + question: LookupQuestion(service: OverlayService(rawValue: "ls_test"), query: [0x7b, 0x7d]), + at: OverlayHost(rawValue: "https://overlay.example") + ) + } + + private func submit( + responseBody: String, + topics: [OverlayTopic], + beef: [UInt8] = [1, 2, 3], + offChainValues: [UInt8] = [], + host: String = "https://overlay.example" + ) async throws -> (steak: Steak, request: HTTPRequest) { + let transport = OverlayTSRecordingTransport( + response: HTTPResponse( + statusCode: 200, + headers: ["Content-Type": "application/json"], + body: Data(responseBody.utf8) + ) + ) + let facilitator = HTTPSOverlayTopicFacilitator( + configuration: try OverlayHTTPConfiguration(beefLimits: beefLimits()), + transport: transport + ) + let steak = try await facilitator.submit( + TaggedBEEF(beef: beef, topics: topics, offChainValues: offChainValues), + to: OverlayHost(rawValue: host) + ) + return (steak, try #require(await transport.lastRequest())) + } + + private func bytes(_ hex: String) throws -> [UInt8] { + try Hex.decode(hex, maximumDecodedByteCount: hex.utf8.count / 2) + } + + private func beefLimits(maximumByteCount: Int = 32 * 1_024 * 1_024) throws -> BEEFLimits { + try BEEFLimits( + maximumByteCount: maximumByteCount, + maximumMerklePathCount: 1_000, + maximumTransactionCount: 1_000, + transactionLimits: try TransactionLimits( + maximumTransactionByteCount: 1_000_000, + maximumInputCount: 1_000, + maximumOutputCount: 1_000, + maximumScriptByteCount: 100_000 + ), + merklePathLimits: try MerklePathLimits( + maximumByteCount: 1_000_000, + maximumLeavesPerLevel: 1_000, + maximumTotalLeaves: 1_000 + ) + ) + } +} + +private actor OverlayTSRecordingTransport: HTTPTransport { + private let response: HTTPResponse + private var requests: [HTTPRequest] = [] + + init(response: HTTPResponse) { + self.response = response + } + + func send( + _ request: HTTPRequest, + maximumResponseBodyByteCount: Int + ) async throws -> HTTPResponse { + requests.append(request) + return response + } + + func lastRequest() -> HTTPRequest? { requests.last } +} diff --git a/Tests/BSVOverlayTests/OverlayAdminTokenTests.swift b/Tests/BSVOverlayTests/OverlayAdminTokenTests.swift index 88dab0e..5c402df 100644 --- a/Tests/BSVOverlayTests/OverlayAdminTokenTests.swift +++ b/Tests/BSVOverlayTests/OverlayAdminTokenTests.swift @@ -9,11 +9,11 @@ struct OverlayAdminTokenTests { @Test("verifies a signed SHIP administration token") func verifiesSHIPToken() throws { let identityKey = try privateKey(2) - let lockingKey = try privateKey(3) + let lockingKey = try linkedKey(identityKey, protocolText: "SHIP") let script = try signedScript( protocolText: "SHIP", identityKey: identityKey.publicKey, - host: "overlay.example", + host: "https://overlay.example", subject: "tm_payments", lockingKey: lockingKey ) @@ -22,18 +22,18 @@ struct OverlayAdminTokenTests { #expect(token.overlayProtocol == .ship) #expect(token.identityPublicKey == identityKey.publicKey) #expect(token.lockingPublicKey == lockingKey.publicKey) - #expect(token.host.rawValue == "overlay.example") + #expect(token.host.rawValue == "https://overlay.example") #expect(token.subject == .ship(try OverlayTopic(rawValue: "tm_payments"))) } @Test("verifies a signed SLAP administration token") func verifiesSLAPToken() throws { let identityKey = try privateKey(4) - let lockingKey = try privateKey(5) + let lockingKey = try linkedKey(identityKey, protocolText: "SLAP") let script = try signedScript( protocolText: "SLAP", identityKey: identityKey.publicKey, - host: "lookup.example", + host: "https://lookup.example", subject: "ls_ship", lockingKey: lockingKey ) @@ -46,11 +46,11 @@ struct OverlayAdminTokenTests { @Test("rejects malformed token structure and fields") func rejectsMalformedFields() throws { let identityKey = try privateKey(6) - let lockingKey = try privateKey(7) + let lockingKey = try linkedKey(identityKey, protocolText: "SHIP") let fields = baseFields( protocolText: "SHIP", identityKey: identityKey.publicKey, - host: "overlay.example", + host: "https://overlay.example", subject: "tm_test" ) let unsigned = try PushDrop.lockingScript( @@ -78,7 +78,7 @@ struct OverlayAdminTokenTests { try signedScript( protocolText: "OTHER", identityKey: identityKey.publicKey, - host: "overlay.example", + host: "https://overlay.example", subject: "tm_test", lockingKey: lockingKey )) @@ -96,7 +96,7 @@ struct OverlayAdminTokenTests { try signedScript( protocolText: "SHIP", identityKey: identityKey.publicKey, - host: "overlay.example", + host: "https://overlay.example", subject: "ls_ship", lockingKey: lockingKey )) @@ -109,7 +109,7 @@ struct OverlayAdminTokenTests { identityKey: identityKey.publicKey, host: "bad host", subject: "ls_ship", - lockingKey: lockingKey + lockingKey: try linkedKey(identityKey, protocolText: "SLAP") )) } } @@ -117,11 +117,11 @@ struct OverlayAdminTokenTests { @Test("rejects invalid and mismatched signatures") func rejectsInvalidSignatures() throws { let identityKey = try privateKey(8) - let lockingKey = try privateKey(9) + let lockingKey = try linkedKey(identityKey, protocolText: "SHIP") let fields = baseFields( protocolText: "SHIP", identityKey: identityKey.publicKey, - host: "overlay.example", + host: "https://overlay.example", subject: "tm_test" ) @@ -148,11 +148,11 @@ struct OverlayAdminTokenTests { @Test("limits are applied by PushDrop before administration fields are indexed") func appliesLimitsBeforeFieldIndexing() throws { let identityKey = try privateKey(11) - let lockingKey = try privateKey(12) + let lockingKey = try linkedKey(identityKey, protocolText: "SHIP") let script = try signedScript( protocolText: "SHIP", identityKey: identityKey.publicKey, - host: "overlay.example", + host: "https://overlay.example", subject: "tm_test", lockingKey: lockingKey ) @@ -168,12 +168,12 @@ struct OverlayAdminTokenTests { @Test("diagnostics and reflection redact token values") func redactsDiagnostics() throws { let identityKey = try privateKey(13) - let lockingKey = try privateKey(14) + let lockingKey = try linkedKey(identityKey, protocolText: "SHIP") let token = try OverlayAdminTokenCodec.decode( try signedScript( protocolText: "SHIP", identityKey: identityKey.publicKey, - host: "private-overlay-173.example", + host: "https://private-overlay-173.example", subject: "tm_test", lockingKey: lockingKey )) @@ -188,6 +188,17 @@ struct OverlayAdminTokenTests { try PrivateKey(Array(repeating: 0, count: 31) + [value]) } + /// The key a `@bsv/sdk` wallet locks an advertisement to: the identity's + /// BRC-42 child for counterparty "anyone" (`OverlayAdminTokenTemplate.ts:291-301`). + private func linkedKey(_ identity: PrivateKey, protocolText: String) throws -> PrivateKey { + let protocolID = protocolText == "SLAP" + ? "service lookup availability" : "service host interconnect" + return try identity.derivedChild( + with: try privateKey(1).publicKey, + invoiceNumber: "2-\(protocolID)-1" + ) + } + private func baseFields( protocolText: String, identityKey: PublicKey, diff --git a/Tests/BSVOverlayTests/OverlayErrorDescriptionTests.swift b/Tests/BSVOverlayTests/OverlayErrorDescriptionTests.swift new file mode 100644 index 0000000..031b26b --- /dev/null +++ b/Tests/BSVOverlayTests/OverlayErrorDescriptionTests.swift @@ -0,0 +1,34 @@ +import BSVOverlay +import Foundation +import Testing + +@Suite("Overlay error descriptions") +struct OverlayErrorDescriptionTests { + @Test("overlay errors have plain sentences and keep detail for logs") + func plainSentences() { + #expect( + OverlayAdminTokenError.unlinkedLockingKey.localizedDescription + == "The overlay advertisement was not made by the identity it names." + ) + #expect( + OverlayPolicyError.invalidSteak.localizedDescription + == "An overlay host sent an answer that does not match the transaction it was sent." + ) + #expect( + OverlayPolicyError.invalidLookupOutput.localizedDescription + == "The overlay hosts answered, but none of their results could be read." + ) + #expect( + OverlayPolicyError.uncertainDelivery.localizedDescription.hasPrefix( + "The transaction may have reached an overlay host") + ) + #expect( + OverlayError.duplicateValue(name: "hosts").localizedDescription + == "The same overlay address is listed twice." + ) + let limit = OverlayError.limitExceeded(name: "resolvedHosts", actual: 65, maximum: 64) + #expect(limit.localizedDescription == "The overlay request is larger than the wallet accepts.") + #expect(String(reflecting: limit).contains("resolvedHosts")) + #expect(String(reflecting: limit).contains("65")) + } +} diff --git a/Tests/BSVOverlayTests/OverlayPolicyTests.swift b/Tests/BSVOverlayTests/OverlayPolicyTests.swift index ba3cb46..c3fcece 100644 --- a/Tests/BSVOverlayTests/OverlayPolicyTests.swift +++ b/Tests/BSVOverlayTests/OverlayPolicyTests.swift @@ -62,8 +62,8 @@ struct OverlayPolicyTests { ) } - @Test("resolver rejects mixed answer representations") - func rejectsMixedAnswers() async throws { + @Test("resolver returns output lists over freeform answers") + func outputListsWinOverFreeform() async throws { let service = try OverlayService(rawValue: "ls_records") let a = try OverlayHost(rawValue: "https://a.example") let b = try OverlayHost(rawValue: "https://b.example") @@ -77,9 +77,10 @@ struct OverlayPolicyTests { hostOverrides: [service: [a, b]], beefLimits: try beefLimits() ) - await #expect(throws: OverlayPolicyError.inconsistentAnswerTypes) { - _ = try await resolver.resolve(LookupQuestion(service: service, query: [])) - } + #expect( + try await resolver.resolve(LookupQuestion(service: service, query: [])) + == .outputList([]) + ) } @Test("resolver deduplicates and sorts output-list answers") @@ -184,7 +185,11 @@ struct OverlayPolicyTests { let limits = try beefLimits() let atomic = try atomicBEEF(limits: limits) - let noAck = OverlayTopicMock(steaks: [host: try Steak()]) + // The host answers for the topic but admits nothing. An empty STEAK + // would be a failed host, as in `@bsv/sdk` (`SHIPBroadcaster.ts:483-485`). + let noAck = OverlayTopicMock( + steaks: [host: try Steak(instructions: [topic: try AdmittanceInstructions()])] + ) let noAckBroadcaster = try OverlayTopicBroadcaster( topics: [topic], facilitator: noAck, @@ -239,7 +244,13 @@ struct OverlayPolicyTests { keyByte: UInt8 ) throws -> OutputListItem { let identityKey = try PrivateKey(Array(repeating: 0, count: 31) + [keyByte]) - let lockingKey = try PrivateKey(Array(repeating: 0, count: 31) + [keyByte + 20]) + // The locking key is the BRC-42 child `@bsv/sdk` derives for the + // identity (`OverlayAdminTokenTemplate.ts:200-222`). + let lockingKey = try identityKey.derivedChild( + with: try PrivateKey(Array(repeating: 0, count: 31) + [1]).publicKey, + invoiceNumber: protocolText == "SLAP" + ? "2-service lookup availability-1" : "2-service host interconnect-1" + ) let fields = [ Array(protocolText.utf8), identityKey.publicKey.compressedBytes, diff --git a/Tests/BSVOverlayTests/OverlayTSParityTests.swift b/Tests/BSVOverlayTests/OverlayTSParityTests.swift new file mode 100644 index 0000000..c8274cc --- /dev/null +++ b/Tests/BSVOverlayTests/OverlayTSParityTests.swift @@ -0,0 +1,954 @@ +import BSVCore +import BSVCrypto +import BSVKeys +import BSVScript +import BSVTransaction +import Testing + +@testable import BSVOverlay + +/// Overlay names, advertisements, discovery, and broadcast policy checked +/// against `@bsv/sdk` 4.1.1 (ts-stack `3b1abc569`, `packages/sdk/src/overlay-tools`). +@Suite("Overlay policy matches @bsv/sdk") +struct OverlayTSParityTests { + // MARK: O11 names + + static let assetID = String(repeating: "0123456789abcdef", count: 4) + "_0" + + @Test("O11: topic and service names follow the @bsv/sdk grammar") + func nameGrammar() throws { + // `__tests/OverlayNames.test.ts:20-60`. + let acceptedTopics = [ + "tm_uhrp_files", "tm_a", "tm_2", "tm_color_\(Self.assetID)", + "tm_color_" + String(repeating: "ff", count: 32) + "_4294967295", + "tm_" + String(repeating: "a", count: 253), + ] + for name in acceptedTopics { + #expect(try OverlayTopic(rawValue: name).rawValue == name) + #expect(throws: (any Error).self) { _ = try OverlayService(rawValue: name) } + } + let acceptedServices = [ + "ls_uhrp_files", "ls_a", "ls_color_\(Self.assetID)", + "ls_" + String(repeating: "a", count: 253), + ] + for name in acceptedServices { + #expect(try OverlayService(rawValue: name).rawValue == name) + #expect(throws: (any Error).self) { _ = try OverlayTopic(rawValue: name) } + } + let rejected: [(String, String)] = [ + ("tm_", "ls_"), + ("tm__x", "ls__x"), + ("tm_x_", "ls_x_"), + ("tm_x__y", "ls_x__y"), + ("tm_Color", "ls_Color"), + ("tm_color_\(Self.assetID.uppercased())", "ls_color_\(Self.assetID.uppercased())"), + ("tm_" + String(repeating: "a", count: 254), "ls_" + String(repeating: "a", count: 254)), + ("tm_" + String(repeating: "a", count: 297), "ls_" + String(repeating: "a", count: 297)), + ("color_\(Self.assetID)", "color_\(Self.assetID)"), + ("tm-x", "ls-x"), + ("tm_x-y", "ls_x-y"), + ("tm_x\n", "ls_x\n"), + ("tm_é", "ls_é"), + ("", ""), + ] + for (topic, service) in rejected { + #expect(throws: (any Error).self) { _ = try OverlayTopic(rawValue: topic) } + #expect(throws: (any Error).self) { _ = try OverlayService(rawValue: service) } + } + // The 256-byte cap is part of the grammar, whatever the caller's limit. + let roomy = try overlayLimits(maximumNameBytes: 1_024) + #expect(throws: OverlayError.invalidTopic) { + _ = try OverlayTopic(rawValue: "tm_" + String(repeating: "a", count: 254), limits: roomy) + } + } + + // MARK: O10 advertisements + + // `OverlayAdminTokenTemplate.lock` output (`OverlayAdminTokenTemplate.ts:271-311`), + // as in `__tests/OverlayAdminTokenTemplate.test.ts:50-84`: wallet key 1, + // SHIP, `https://test.com`, `tm_tests`. + static let tsSHIP = + "2102d7245996c0abb8323c4780f4e7c5f7938e5498e35daa5325641df6fa5129f86bac0453484950210279" + + "be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817981068747470733a2f2f746573" + + "742e636f6d08746d5f7465737473473045022100dcc586bd746d81c0df35ad821673c7575b7e79a031bc6e" + + "0320781244b372588f0220633d47d958badcddb81589eb45558822586e9f8091eeb83b98355fe728174573" + + "6d6d75" + // Wallet key 2, SLAP, `https://lookup.example/`, `ls_records`. + static let tsSLAP = + "2102b67adb75684410fd113d58fe263bcc9f14123330ccea191bbb565c258c6d7452ac04534c41502102c6" + + "047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee51768747470733a2f2f6c6f6f" + + "6b75702e6578616d706c652f0a6c735f7265636f726473473045022100c4b361ad7c52ad91803a51db51dc" + + "08041c29d0be83d056854f034e6ee96a6e6702206678c37d871e7793054c24605453c57c372d08a44d91d5" + + "fc108cef76ad9056896d6d75" + // A legacy SDK advertisement: protocol `[2, "Service Host Interconnect"]`, + // counterparty "self", wallet key 3 (`__tests/OverlayAdminTokenTemplate.test.ts:143-160`). + static let tsLegacy = + "2102c7219533e42d5406f71551bf7256b94bd4237c75d52a35542ad455925c162a86ac04534849502102f9" + + "308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f91668747470733a2f2f6c6567" + + "6163792e6578616d706c6509746d5f6c65676163794630440220447a527e4fca3f8f8556d1565ec2f06e3e" + + "cbff940f9eb69e4bc92e8bdb92b9280220155ad4a39dd7bdc05569d32e2a8c4d029386649226020a936082" + + "061818330e286d6d75" + + @Test("O10: advertisements written by @bsv/sdk decode and verify") + func tsAdvertisements() throws { + let ship = try OverlayAdminTokenCodec.decode(try script(Self.tsSHIP)) + #expect(ship.identityPublicKey == (try privateKey(1)).publicKey) + #expect(ship.host.rawValue == "https://test.com") + #expect(ship.subject == .ship(try OverlayTopic(rawValue: "tm_tests"))) + + let slap = try OverlayAdminTokenCodec.decode(try script(Self.tsSLAP)) + #expect(slap.identityPublicKey == (try privateKey(2)).publicKey) + #expect(slap.host.rawValue == "https://lookup.example/") + #expect(slap.subject == .slap(try OverlayService(rawValue: "ls_records"))) + } + + @Test("O10: legacy advertisements are not authenticated") + func legacyAdvertisement() throws { + #expect(throws: OverlayAdminTokenError.invalidSignature) { + _ = try OverlayAdminTokenCodec.decode(try script(Self.tsLegacy)) + } + } + + @Test("O10: the locking key must be derived from the stated identity key") + func identityLinkage() throws { + let identity = try privateKey(24) + // Signed by its own locking key, which is not the identity's child. + // The decoder used to accept this and report an unauthenticated identity. + let unrelated = try privateKey(99) + let forged = try advertisementScript( + protocolText: "SHIP", identity: identity, host: "https://ship.example", + subject: "tm_security", lockingKey: unrelated + ) + #expect(throws: OverlayAdminTokenError.invalidSignature) { + _ = try OverlayAdminTokenCodec.decode(forged) + } + + // `OverlayAdminTokenTemplate.boundaries.test.ts:73-88`: a correct + // signature, but the locking key belongs to another identity. + let canonical = try advertisementScript( + protocolText: "SHIP", identity: identity, host: "https://ship.example", + subject: "tm_security" + ) + let decoded = try PushDrop.decode(canonical, lockPosition: .beforeCompatibility) + let swapped = try PushDrop.lockingScript( + fields: decoded.fields, + publicKey: try linkedKey(try privateKey(25), protocolText: "SHIP").publicKey, + lockPosition: .beforeCompatibility + ) + #expect(throws: OverlayAdminTokenError.unlinkedLockingKey) { + _ = try OverlayAdminTokenCodec.decode(swapped) + } + + // A SLAP-derived key does not authenticate a SHIP advertisement. + let crossProtocol = try advertisementScript( + protocolText: "SHIP", identity: identity, host: "https://ship.example", + subject: "tm_security", lockingKey: try linkedKey(identity, protocolText: "SLAP") + ) + #expect(throws: OverlayAdminTokenError.invalidSignature) { + _ = try OverlayAdminTokenCodec.decode(crossProtocol) + } + } + + @Test("O10: advertised URIs follow the @bsv/sdk rules") + func advertisementURIs() throws { + let identity = try privateKey(21) + // `OverlayAdminTokenTemplate.boundaries.test.ts:7-29,40-52`. + let invalid = [ + "overlay.example", + "http://test.com", + "https://localhost", + "https://xn--bcher-kva.example", + "https://user:secret@example.com", + "https://example.com/path", + "https://example.com/#fragment", + "https://[", + "wss://localhost/socket", + "wss://user:secret@example.com/socket", + "wss://example.com/socket#fragment", + "wss://[", + "js8c+bsvauth+smf:", + "js8c+bsvauth+smf:?lat=1&long=2&freq=7MHz&radius=10km&extra=1", + "js8c+bsvauth+smf:?lat=1&lat=2&long=2&freq=7MHz&radius=10km", + "js8c+bsvauth+smf:?lat=1e1&long=2&freq=7MHz&radius=10km", + "js8c+bsvauth+smf:?lat=91&long=2&freq=7MHz&radius=10km", + "js8c+bsvauth+smf:?lat=1&long=-181&freq=7MHz&radius=10km", + "js8c+bsvauth+smf:?lat=1&long=2&freq=0MHz&radius=10km", + "js8c+bsvauth+smf:?lat=1&long=2&freq=\(String(repeating: "9", count: 400))MHz&radius=10km", + "js8c+bsvauth+smf:?lat=1&long=2&freq=7MHz&radius=none", + "https://example.com/\u{0000}", + "https://example.com/\u{0085}", + ] + for uri in invalid { + #expect(throws: OverlayAdminTokenError.invalidHost, "\(uri)") { + _ = try OverlayAdminTokenCodec.decode( + try advertisementScript( + protocolText: "SHIP", identity: identity, host: uri, subject: "tm_security" + )) + } + } + // `OverlayAdminTokenTemplate.boundaries.test.ts:54-71`, plus forms the + // WHATWG parser normalizes to the same origin. + let valid = [ + "https://example.com", + "https+bsvauth://example.com", + "https+bsvauth+smf://example.com", + "https+bsvauth+scrypt-offchain://example.com", + "https+rtt://example.com", + "wss://example.com/socket", + "js8c+bsvauth+smf:?lat=41.88&long=-87.63&freq=7.078MHz&radius=10km", + "https://example.com/", + "https://Example.COM:443/", + "https://example.com:8443", + "https://example.com/?", + "https://example.com/#", + ] + for uri in valid { + let token = try OverlayAdminTokenCodec.decode( + try advertisementScript( + protocolText: "SHIP", identity: identity, host: uri, subject: "tm_security" + )) + #expect(token.host.rawValue == uri) + } + } + + @Test("O10: field and signature sizes follow @bsv/sdk") + func fieldBounds() throws { + #expect(OverlayAdminTokenLimits.standard.maximumFieldByteCount == 4_096) + let identity = try privateKey(26) + let canonical = try advertisementScript( + protocolText: "SLAP", identity: identity, host: "https://lookup.example", + subject: "ls_security" + ) + // `OverlayAdminTokenTemplate.boundaries.test.ts:90-100`: a 1-byte signature field. + let decoded = try PushDrop.decode(canonical, lockPosition: .beforeCompatibility) + let truncated = try PushDrop.lockingScript( + fields: Array(decoded.fields.dropLast()) + [[1]], + publicKey: decoded.publicKey, + lockPosition: .beforeCompatibility + ) + #expect(throws: OverlayAdminTokenError.invalidSignature) { + _ = try OverlayAdminTokenCodec.decode(truncated) + } + // A 4097-byte host field exceeds `MAX_DISCOVERY_FIELD_BYTES` even with roomier limits. + let roomy = try OverlayAdminTokenLimits( + maximumScriptByteCount: 64 * 1_024, + maximumFieldByteCount: 16 * 1_024, + overlayLimits: try overlayLimits(maximumNameBytes: 256, maximumHostBytes: 8_192) + ) + let longHost = "https://" + String(repeating: "a", count: 4_085) + ".com" + #expect(longHost.utf8.count == 4_097) + #expect(throws: OverlayAdminTokenError.invalidPushDrop) { + _ = try OverlayAdminTokenCodec.decode( + try advertisementScript( + protocolText: "SLAP", identity: identity, host: longHost, + subject: "ls_security" + ), + limits: roomy + ) + } + } + + // MARK: Discovery (O10 one satoshi, O14 origins) + + @Test("O10 and O14: SLAP discovery needs one satoshi and normalizes advertised origins") + func slapDiscovery() async throws { + let tracker = try OverlayHost(rawValue: "https://tracker.example") + let service = try OverlayService(rawValue: "ls_records") + let outputs = [ + // Two advertisements for the same origin, one with a trailing slash. + try advertisementItem("SLAP", host: "https://service.example/", subject: service.rawValue, key: 30), + try advertisementItem("SLAP", host: "https://SERVICE.example:443", subject: service.rawValue, key: 31), + // Two satoshis: skipped, as `LookupResolver.ts:2219` does. + try advertisementItem("SLAP", host: "https://rich.example", subject: service.rawValue, key: 32, satoshis: 2), + // Not an HTTPS origin: nothing the HTTPS facilitators can call. + try advertisementItem("SLAP", host: "wss://socket.example/feed", subject: service.rawValue, key: 33), + // Signed by an unlinked key. + try advertisementItem("SLAP", host: "https://forged.example", subject: service.rawValue, key: 34, linked: false), + ] + let resolver = try LookupResolver( + facilitator: ParityLookupMock(responses: [tracker: try LookupAnswer(outputList: outputs)]), + slapTrackers: [tracker], + beefLimits: try beefLimits() + ) + #expect( + try await resolver.competentHosts(for: service) + == [try OverlayHost(rawValue: "https://service.example")] + ) + } + + // MARK: O15 answers + + @Test("O15: output lists win over freeform answers; all failures still throw") + func mixedAnswers() async throws { + let service = try OverlayService(rawValue: "ls_records") + let a = try OverlayHost(rawValue: "https://a.example") + let b = try OverlayHost(rawValue: "https://b.example") + let c = try OverlayHost(rawValue: "https://c.example") + let item = try advertisementItem("SLAP", host: "https://x.example", subject: service.rawValue, key: 40) + let mixed = try LookupResolver( + facilitator: ParityLookupMock(responses: [ + a: try LookupAnswer(freeform: [1]), + b: try LookupAnswer(outputList: [item]), + ]), + slapTrackers: [], + hostOverrides: [service: [a, b, c]], + beefLimits: try beefLimits() + ) + // `LookupResolver.ts:1508-1528`: the freeform answer is counted and left out. + #expect(try await mixed.resolve(LookupQuestion(service: service, query: [])) == .outputList([item])) + + let failing = try LookupResolver( + facilitator: ParityLookupMock(responses: [:]), + slapTrackers: [], + hostOverrides: [service: [a, b]], + beefLimits: try beefLimits() + ) + await #expect(throws: OverlayPolicyError.noSuccessfulResponses) { + _ = try await failing.resolve(LookupQuestion(service: service, query: [])) + } + } + + // MARK: O7 per-host topics + + @Test("O7: each host is sent only the topics it advertised") + func perHostTopics() async throws { + let topicA = try OverlayTopic(rawValue: "tm_a") + let topicB = try OverlayTopic(rawValue: "tm_b") + let h1 = try OverlayHost(rawValue: "https://h1.example") + let h2 = try OverlayHost(rawValue: "https://h2.example") + let discovery = try LookupAnswer(outputList: [ + advertisementItem("SHIP", host: "https://h1.example/", subject: "tm_a", key: 50), + advertisementItem("SHIP", host: "https://h2.example", subject: "tm_a", key: 51), + advertisementItem("SHIP", host: "https://h2.example", subject: "tm_b", key: 52), + ]) + let both = try AdmittanceInstructions(outputsToAdmit: [0]) + let facilitator = ParityTopicMock(steaks: [ + h1: try Steak(instructions: [topicA: both]), + h2: try Steak(instructions: [topicA: both, topicB: both]), + ]) + let limits = try beefLimits() + let broadcaster = try OverlayTopicBroadcaster( + topics: [topicB, topicA], + facilitator: facilitator, + resolver: ParityResolverMock(answer: discovery), + acknowledgmentByHost: [ + try OverlayHost(rawValue: "https://h1.example/"): try AckFrom( + requirement: .some, topics: [topicA]) + ], + beefLimits: limits + ) + _ = try await broadcaster.broadcast(try atomicBEEF(limits: limits)) + #expect(await facilitator.topics(for: h1) == [topicA]) + #expect(await facilitator.topics(for: h2) == [topicA, topicB]) + } + + @Test("O7: a host that acknowledges a topic it was not sent fails the broadcast") + func unexpectedTopicAcknowledgment() async throws { + let topicA = try OverlayTopic(rawValue: "tm_a") + let topicB = try OverlayTopic(rawValue: "tm_b") + let h1 = try OverlayHost(rawValue: "https://h1.example") + let discovery = try LookupAnswer(outputList: [ + advertisementItem("SHIP", host: h1.rawValue, subject: "tm_a", key: 60) + ]) + let instructions = try AdmittanceInstructions(outputsToAdmit: [0]) + let facilitator = ParityTopicMock(steaks: [ + h1: try Steak(instructions: [topicA: instructions, topicB: instructions]) + ]) + let limits = try beefLimits() + let broadcaster = try OverlayTopicBroadcaster( + topics: [topicA, topicB], + facilitator: facilitator, + resolver: ParityResolverMock(answer: discovery), + acknowledgmentFromAnyHost: try AckFrom(requirement: .any), + beefLimits: limits + ) + await #expect(throws: OverlayPolicyError.uncertainDelivery) { + _ = try await broadcaster.broadcast(try atomicBEEF(limits: limits)) + } + } + + // MARK: S5 URI hosts + + @Test("S5: advertised IP hosts are parsed and written as WHATWG URL does") + func whatwgHosts() throws { + // `new URL(uri).origin` in Node 22, the parser `@bsv/sdk` uses + // (`OverlayAdminTokenTemplate.ts:81-95`, `SHIPBroadcaster.ts:102-125`). + // Bun's parser refuses some valid IPv6 forms, such as the last row. + let origins: [(String, String?)] = [ + ("https://1.2.3.4.5/", nil), + ("https://256.1.1.1/", nil), + ("https://a.b.c.1/", nil), + ("https://09.1.1.1/", nil), + ("https://1.2.3.08/", nil), + ("https://example.0x10/", nil), + ("https://4294967296/", nil), + ("https://[1::2::3]/", nil), + ("https://[1:2:3:4:5:6:7:8:9]/", nil), + ("https://2130706433/", "https://127.0.0.1"), + ("https://0x7f.1/", "https://127.0.0.1"), + ("https://0x/", "https://0.0.0.0"), + ("https://1.2.3/", "https://1.2.0.3"), + ("https://010.0.0.1/", "https://8.0.0.1"), + ("https://0300.0250.1.1/", "https://192.168.1.1"), + ("https://8.8.8.8./", "https://8.8.8.8"), + ("https://4294967295/", "https://255.255.255.255"), + ("https://[0:0:0:0:0:0:0:1]/", "https://[::1]"), + ("https://[::FFFF:1.2.3.4]/", "https://[::ffff:102:304]"), + ("https://[2001:db8:0:0:1:0:0:1]/", "https://[2001:db8::1:0:0:1]"), + ("https://[1:0:0:2:0:0:0:3]/", "https://[1:0:0:2::3]"), + ("https://[::]/", "https://[::]"), + ("https://[::1.2.3.4]/", "https://[::102:304]"), + ("https://[1:0::2002:64:1.2.3.4]/", "https://[1::2002:64:102:304]"), + ] + for (uri, origin) in origins { + #expect(OverlayAdvertisementURI.httpsOrigin(uri) == origin, "\(uri)") + #expect(OverlayAdvertisementURI.isValid(uri) == (origin != nil), "\(uri)") + } + // The same rules hold for every scheme with a host. + #expect(!OverlayAdvertisementURI.isValid("wss://256.1.1.1/socket")) + #expect(!OverlayAdvertisementURI.isValid("https+bsvauth://[1::2::3]")) + } + + // MARK: S6 public hosts + + @Test("S6: only public network addresses pass the discovered-host filter") + func publicAddresses() throws { + // `isPublicNetworkAddress` in `@bsv/sdk`, run in Bun + // (`storage/PublicHTTPSFetch.ts:114-158`). + let verdicts: [(String, Bool)] = [ + ("127.0.0.1", false), ("192.168.1.1", false), ("10.1.2.3", false), + ("100.64.0.1", false), ("169.254.1.1", false), ("172.16.0.1", false), + ("224.0.0.1", false), ("198.18.0.1", false), ("203.0.113.1", false), + ("0.0.0.0", false), ("8.8.8.8", true), ("1.1.1.1", true), + ("[::1]", false), ("[::]", false), ("[fe80::1]", false), ("[fd00::1]", false), + ("[::ffff:7f00:1]", false), ("[64:ff9b::a00:1]", false), + ("[2002:c0a8:101::]", false), ("[2001:db8::1]", false), ("[ff02::1]", false), + ("[3ff0::1]", false), ("[2001:100::1]", false), ("[::102:304]", false), + ("[2606:4700::1111]", true), ("[2001:4860:4860::8888]", true), + ] + for (host, isPublic) in verdicts { + #expect( + OverlayAdvertisementURI.isPublicHTTPSOrigin("https://\(host)") == isPublic, + "\(host)") + } + for name in [ + "printer.local", "db.internal", "box.home.arpa", "a.localhost", "localhost.", + // Empty labels: digits and dots, as `PublicHTTPSFetch.ts:201-204` + // refuses them, and names whose trailing dots hide a private suffix. + "127.0.0.1..", "9..", "..", "localhost..", "printer.local..", "a..example", + ] { + #expect(!OverlayAdvertisementURI.isPublicHTTPSOrigin("https://\(name)"), "\(name)") + } + #expect(OverlayAdvertisementURI.isPublicHTTPSOrigin("https://overlay.example")) + #expect(OverlayAdvertisementURI.isPublicHTTPSOrigin("https://overlay.example.")) + // A numeric alias of a private address is caught after canonicalization. + #expect(!OverlayAdvertisementURI.isPublicHTTPSOrigin("https://2130706433/")) + } + + @Test("S6 and S7: discovery skips private hosts and merges with caller hosts") + func discoveryHostPolicy() async throws { + let tracker = try OverlayHost(rawValue: "https://tracker.example") + let service = try OverlayService(rawValue: "ls_records") + var key: UInt8 = 70 + func ad(_ host: String) throws -> OutputListItem { + key += 1 + return try advertisementItem("SLAP", host: host, subject: service.rawValue, key: key) + } + let outputs = try [ + ad("https://127.0.0.1"), ad("https://2130706433/"), ad("https://192.168.1.1"), + ad("https://[::1]"), ad("https://printer.local"), ad("https://8.8.8.8"), + ad("https://service.example/"), + ] + let facilitator = ParityLookupMock(responses: [ + tracker: try LookupAnswer(outputList: outputs) + ]) + let publicOnly = try LookupResolver( + facilitator: facilitator, + slapTrackers: [tracker], + additionalHosts: [service: [try OverlayHost(rawValue: "https://Service.example:443/")]], + beefLimits: try beefLimits() + ) + #expect( + try await publicOnly.competentHosts(for: service) == [ + try OverlayHost(rawValue: "https://8.8.8.8"), + try OverlayHost(rawValue: "https://service.example"), + ]) + + let any = try LookupResolver( + facilitator: facilitator, + slapTrackers: [tracker], + beefLimits: try beefLimits(), + discoveredHostPolicy: .anyHTTPSOrigin + ) + #expect( + try await any.competentHosts(for: service).map(\.rawValue) == [ + "https://127.0.0.1", "https://192.168.1.1", "https://8.8.8.8", + "https://[::1]", "https://printer.local", "https://service.example", + ]) + } + + @Test("S7: caller hosts are normalized, and one origin twice in a list is a duplicate") + func callerHostNormalization() async throws { + let service = try OverlayService(rawValue: "ls_records") + let item = try advertisementItem("SLAP", host: "https://x.example", subject: service.rawValue, key: 80) + let host = try OverlayHost(rawValue: "https://a.example") + let facilitator = ParityLookupMock(responses: [host: try LookupAnswer(outputList: [item])]) + let resolver = try LookupResolver( + facilitator: facilitator, + slapTrackers: [], + hostOverrides: [service: [try OverlayHost(rawValue: "https://A.example/")]], + additionalHosts: [service: [host]], + beefLimits: try beefLimits() + ) + #expect(try await resolver.competentHosts(for: service) == [host]) + _ = try await resolver.resolve(LookupQuestion(service: service, query: [])) + #expect(await facilitator.requestCount() == 1) + + // `configuredHosts` in `@bsv/sdk` (`LookupResolver.ts:551-568`). + #expect(throws: OverlayError.duplicateValue(name: "hosts")) { + _ = try LookupResolver( + facilitator: facilitator, + slapTrackers: [], + hostOverrides: [ + service: [try OverlayHost(rawValue: "https://a.example/"), host] + ], + beefLimits: try beefLimits() + ) + } + } + + // MARK: S3 bad outputs + + @Test("S3: one host's unreadable output is left out, with its reason") + func badOutputIsSkipped() async throws { + let service = try OverlayService(rawValue: "ls_records") + let a = try OverlayHost(rawValue: "https://a.example") + let b = try OverlayHost(rawValue: "https://b.example") + let good = try advertisementItem("SLAP", host: "https://x.example", subject: service.rawValue, key: 90) + // Its `txid` names a transaction its BEEF does not hold, which + // `resolveTxIdForOutput` in `@bsv/sdk` skips. + let wrongID = try OutputListItem( + beef: good.beef, outputIndex: 0, + transactionID: try TransactionID(displayHex: String(repeating: "ab", count: 32))) + let outOfRange = try OutputListItem(beef: good.beef, outputIndex: 9) + let unreadable = try OutputListItem(beef: [1, 2, 3], outputIndex: 0) + let resolver = try LookupResolver( + facilitator: ParityLookupMock(responses: [ + a: try LookupAnswer(outputList: [wrongID, outOfRange, unreadable]), + b: try LookupAnswer(outputList: [good]), + ]), + slapTrackers: [], + hostOverrides: [service: [a, b, try OverlayHost(rawValue: "https://c.example")]], + beefLimits: try beefLimits() + ) + let question = try LookupQuestion(service: service, query: []) + #expect(try await resolver.resolve(question) == .outputList([good])) + + let detailed = try await resolver.resolveDetailed(question) + #expect(detailed.answer == .outputList([good])) + #expect(detailed.rejectedOutputs.map(\.host) == [a, a, a]) + #expect(detailed.rejectedOutputs.map(\.output) == [wrongID, outOfRange, unreadable]) + #expect(detailed.rejectedOutputs[0].error as? OverlayPolicyError == .invalidLookupOutput) + #expect(detailed.rejectedOutputs[2].error is BEEFError) + #expect(detailed.hostFailures.map(\.host.rawValue) == ["https://c.example"]) + + // When every output is unreadable there is no answer. + let allBad = try LookupResolver( + facilitator: ParityLookupMock(responses: [a: try LookupAnswer(outputList: [unreadable])]), + slapTrackers: [], + hostOverrides: [service: [a]], + beefLimits: try beefLimits() + ) + await #expect(throws: OverlayPolicyError.invalidLookupOutput) { + _ = try await allBad.resolve(question) + } + #expect(try await allBad.resolveDetailed(question).answer == nil) + } + + // MARK: Broadcast acknowledgment + + @Test("A failed host does not fail a broadcast another host acknowledged") + func failedHostIsTolerated() async throws { + let topic = try OverlayTopic(rawValue: "tm_a") + let good = try OverlayHost(rawValue: "https://good.example") + let down = try OverlayHost(rawValue: "https://down.example") + let empty = try OverlayHost(rawValue: "https://empty.example") + let discovery = try LookupAnswer(outputList: [ + advertisementItem("SHIP", host: good.rawValue, subject: "tm_a", key: 100), + advertisementItem("SHIP", host: down.rawValue, subject: "tm_a", key: 101), + advertisementItem("SHIP", host: empty.rawValue, subject: "tm_a", key: 102), + ]) + let facilitator = ParityTopicMock(steaks: [ + good: try Steak(instructions: [topic: try AdmittanceInstructions(outputsToAdmit: [0])]), + empty: try Steak(), + ]) + let limits = try beefLimits() + let atomic = try atomicBEEF(limits: limits) + func broadcaster( + every: AckFrom? = nil, byHost: [OverlayHost: AckFrom] = [:] + ) throws -> OverlayTopicBroadcaster { + try OverlayTopicBroadcaster( + topics: [topic], facilitator: facilitator, + resolver: ParityResolverMock(answer: discovery), + acknowledgmentFromEveryHost: every, acknowledgmentByHost: byHost, + beefLimits: limits) + } + + // `SHIPBroadcaster` defaults: some host must acknowledge every topic. + let result = try await broadcaster().broadcast(atomic) + #expect(result.transactionID == atomic.subjectTransactionID) + let report = try await broadcaster().broadcastDetailed(atomic) + #expect(report.failure == nil) + #expect(report.acknowledgedTopics == [good: [topic]]) + #expect(report.hostFailures.map(\.host) == [down, empty]) + #expect(report.hostFailures[1].error as? OverlayPolicyError == .invalidSteak) + + // A requirement on every host, or on the failed host, is not met, and + // the failed host's delivery is uncertain. + await #expect(throws: OverlayPolicyError.uncertainDelivery) { + _ = try await broadcaster(every: try AckFrom(requirement: .all)).broadcast(atomic) + } + await #expect(throws: OverlayPolicyError.uncertainDelivery) { + _ = try await broadcaster(byHost: [down: try AckFrom(requirement: .any)]) + .broadcast(atomic) + } + } + + @Test("Discovered lookup hosts past the host limit are left out, not an error") + func discoveredHostLimitTruncates() async throws { + let limits = try overlayLimits(maximumNameBytes: 256, maximumHosts: 2) + let tracker = try OverlayHost(rawValue: "https://tracker.example") + let service = try OverlayService(rawValue: "ls_records") + let caller = try OverlayHost(rawValue: "https://caller.example") + let outputs = try [ + advertisementItem("SLAP", host: "https://a.example", subject: service.rawValue, key: 120), + advertisementItem("SLAP", host: "https://caller.example", subject: service.rawValue, key: 121), + advertisementItem("SLAP", host: "https://b.example", subject: service.rawValue, key: 122), + advertisementItem("SLAP", host: "https://c.example", subject: service.rawValue, key: 123), + ] + let resolver = try LookupResolver( + facilitator: ParityLookupMock(responses: [tracker: try LookupAnswer(outputList: outputs)]), + slapTrackers: [tracker], + additionalHosts: [service: [caller]], + beefLimits: try beefLimits(), + limits: limits + ) + #expect( + try await resolver.competentHosts(for: service).map(\.rawValue) == [ + "https://a.example", "https://caller.example", + ]) + } + + @Test("Hosts past the host limit are left out, not an error") + func hostLimitTruncates() async throws { + let topic = try OverlayTopic(rawValue: "tm_a") + let first = try OverlayHost(rawValue: "https://first.example") + let discovery = try LookupAnswer(outputList: [ + advertisementItem("SHIP", host: first.rawValue, subject: "tm_a", key: 110), + advertisementItem("SHIP", host: "https://second.example", subject: "tm_a", key: 111), + ]) + let acknowledged = try Steak( + instructions: [topic: try AdmittanceInstructions(outputsToAdmit: [0])]) + let facilitator = ParityTopicMock(steaks: [ + first: acknowledged, try OverlayHost(rawValue: "https://second.example"): acknowledged, + ]) + let limits = try beefLimits() + let broadcaster = try OverlayTopicBroadcaster( + topics: [topic], facilitator: facilitator, + resolver: ParityResolverMock(answer: discovery), + beefLimits: limits, + limits: try overlayLimits(maximumNameBytes: 256, maximumHosts: 1) + ) + let report = try await broadcaster.broadcastDetailed(try atomicBEEF(limits: limits)) + #expect(report.acknowledgedTopics.keys.map(\.rawValue) == [first.rawValue]) + } + + @Test("S1: each tracker gets a share of the host limit, and skips are reported") + func trackersShareTheHostLimit() async throws { + let limits = try overlayLimits(maximumNameBytes: 256, maximumHosts: 4) + let service = try OverlayService(rawValue: "ls_records") + let flooding = try OverlayHost(rawValue: "https://a-tracker.example") + let honest = try OverlayHost(rawValue: "https://b-tracker.example") + var key: UInt8 = 130 + func ads(_ hosts: [String]) throws -> LookupAnswer { + try LookupAnswer(outputList: hosts.map { + key += 1 + return try advertisementItem("SLAP", host: $0, subject: service.rawValue, key: key) + }) + } + let flood = try ads((1...6).map { "https://flood\($0).example" }) + let named = try ads(["https://honest1.example", "https://honest2.example"]) + let resolver = try LookupResolver( + facilitator: ParityLookupMock(responses: [flooding: flood, honest: named]), + slapTrackers: [flooding, honest], + beefLimits: try beefLimits(), + limits: limits + ) + // A share is 4 / 2 = 2 hosts, so the first tracker's flood cannot + // take the second tracker's places. + #expect( + try await resolver.competentHosts(for: service).map(\.rawValue) == [ + "https://flood1.example", "https://flood2.example", + "https://honest1.example", "https://honest2.example", + ]) + let resolution = try await resolver.resolveDetailed( + try LookupQuestion(service: service, query: [0x7b, 0x7d], limits: limits)) + #expect(resolution.skippedHostCount == 4) + #expect(resolution.trackerFailures.isEmpty) + } + + @Test("S2: a tracker that fails while another answers is reported") + func trackerFailureIsReported() async throws { + let service = try OverlayService(rawValue: "ls_records") + let down = try OverlayHost(rawValue: "https://down-tracker.example") + let up = try OverlayHost(rawValue: "https://up-tracker.example") + let answer = try LookupAnswer(outputList: [ + advertisementItem("SLAP", host: "https://records.example", subject: service.rawValue, key: 140) + ]) + let resolver = try LookupResolver( + facilitator: ParityLookupMock(responses: [up: answer]), + slapTrackers: [down, up], + beefLimits: try beefLimits() + ) + let resolution = try await resolver.resolveDetailed( + try LookupQuestion(service: service, query: [0x7b, 0x7d])) + #expect(resolution.trackerFailures.map(\.host) == [down]) + #expect(resolution.hostFailures.map(\.host.rawValue) == ["https://records.example"]) + #expect(resolution.skippedHostCount == 0) + } + + @Test("S1 and N1: hosts named in requirements keep their places and must be discovered") + func namedHostsKeepTheirPlaces() async throws { + let topic = try OverlayTopic(rawValue: "tm_a") + let first = try OverlayHost(rawValue: "https://first.example") + let second = try OverlayHost(rawValue: "https://second.example") + let discovery = try LookupAnswer(outputList: [ + advertisementItem("SHIP", host: first.rawValue, subject: "tm_a", key: 150), + advertisementItem("SHIP", host: second.rawValue, subject: "tm_a", key: 151), + ]) + let acknowledged = try Steak( + instructions: [topic: try AdmittanceInstructions(outputsToAdmit: [0])]) + let facilitator = ParityTopicMock(steaks: [first: acknowledged, second: acknowledged]) + let limits = try beefLimits() + let atomic = try atomicBEEF(limits: limits) + + // With room for one host, the named second host is kept and the + // first, which arrived earlier, is left out and counted. + let reserved = try OverlayTopicBroadcaster( + topics: [topic], facilitator: facilitator, + resolver: ParityResolverMock(answer: discovery), + acknowledgmentByHost: [second: try AckFrom(requirement: .all)], + beefLimits: limits, + limits: try overlayLimits(maximumNameBytes: 256, maximumHosts: 1) + ) + let report = try await reserved.broadcastDetailed(atomic) + #expect(report.acknowledgedTopics.keys.map(\.rawValue) == [second.rawValue]) + #expect(report.skippedHostCount == 1) + #expect(report.failure == nil) + + // A named host that discovery did not return fails even a `.none` + // requirement, as in `SHIPBroadcaster.ts:659-662`. + let missing = try OverlayTopicBroadcaster( + topics: [topic], facilitator: facilitator, + resolver: ParityResolverMock(answer: discovery), + acknowledgmentByHost: [ + try OverlayHost(rawValue: "https://absent.example"): try AckFrom(requirement: .none) + ], + beefLimits: limits + ) + let missingReport = try await missing.broadcastDetailed(atomic) + #expect(missingReport.failure == .acknowledgmentFailed) + #expect(missingReport.skippedHostCount == 0) + } + + @Test("S5: the overlay log writes a host as scheme, host and port only") + func logLocationDropsCredentialsAndQuery() throws { + let host = try OverlayHost(rawValue: "https://user:secret@overlay.example:8443/path?key=1") + #expect(OverlayLog.location(host) == "https://overlay.example:8443") + #expect(OverlayLog.location(try OverlayHost(rawValue: "https://overlay.example")) == "https://overlay.example") + } + + @Test("N3: an acknowledgment host that is not an https origin is rejected up front") + func acknowledgmentHostMustBeOrigin() throws { + let topic = try OverlayTopic(rawValue: "tm_a") + for raw in ["overlay.example", "https://overlay.example/path", "http://overlay.example"] { + #expect(throws: OverlayError.invalidHost, "\(raw)") { + _ = try OverlayTopicBroadcaster( + topics: [topic], + facilitator: ParityTopicMock(steaks: [:]), + resolver: ParityResolverMock(answer: try LookupAnswer(outputList: [])), + acknowledgmentByHost: [try OverlayHost(rawValue: raw): try AckFrom(requirement: .any)], + beefLimits: try beefLimits() + ) + } + } + } + + // MARK: Helpers + + private func privateKey(_ value: UInt8) throws -> PrivateKey { + try PrivateKey(Array(repeating: 0, count: 31) + [value]) + } + + private func linkedKey(_ identity: PrivateKey, protocolText: String) throws -> PrivateKey { + let protocolID = protocolText == "SLAP" + ? "service lookup availability" : "service host interconnect" + return try identity.derivedChild( + with: try privateKey(1).publicKey, + invoiceNumber: "2-\(protocolID)-1" + ) + } + + private func script(_ hex: String) throws -> Script { + try Script(hex: hex, maximumByteCount: 64 * 1_024) + } + + private func advertisementScript( + protocolText: String, + identity: PrivateKey, + host: String, + subject: String, + lockingKey: PrivateKey? = nil + ) throws -> Script { + let key = try lockingKey ?? linkedKey(identity, protocolText: protocolText) + let fields = [ + Array(protocolText.utf8), + identity.publicKey.compressedBytes, + Array(host.utf8), + Array(subject.utf8), + ] + let signature = try key.sign(digest: BSVHashing.sha256(fields.flatMap { $0 })) + return try PushDrop.lockingScript( + fields: fields + [signature.derBytes], + publicKey: key.publicKey, + lockPosition: .beforeCompatibility + ) + } + + private func advertisementItem( + _ protocolText: String, + host: String, + subject: String, + key: UInt8, + satoshis: UInt64 = 1, + linked: Bool = true + ) throws -> OutputListItem { + let identity = try privateKey(key) + let script = try advertisementScript( + protocolText: protocolText, + identity: identity, + host: host, + subject: subject, + lockingKey: linked ? nil : try privateKey(key &+ 100) + ) + let transaction = Transaction( + outputs: [TransactionOutput(satoshis: satoshis, lockingScript: script)] + ) + let limits = try beefLimits() + let beef = try BEEF( + version: .v2, merklePaths: [], transactions: [.raw(transaction)], limits: limits + ) + return try OutputListItem(beef: beef.serialized(limits: limits), outputIndex: 0) + } + + private func atomicBEEF(limits: BEEFLimits) throws -> AtomicBEEF { + let transaction = Transaction( + outputs: [ + TransactionOutput( + satoshis: 1, lockingScript: try Script(bytes: [0x51], maximumByteCount: 1)) + ] + ) + return try AtomicBEEF( + subjectTransactionID: try transaction.transactionID(limits: limits.transactionLimits), + beef: try BEEF( + version: .v2, merklePaths: [], transactions: [.raw(transaction)], limits: limits + ), + limits: limits + ) + } + + private func beefLimits() throws -> BEEFLimits { + try BEEFLimits( + maximumByteCount: 32 * 1_024 * 1_024, + maximumMerklePathCount: 1_000, + maximumTransactionCount: 1_000, + transactionLimits: try TransactionLimits( + maximumTransactionByteCount: 1_000_000, + maximumInputCount: 1_000, + maximumOutputCount: 1_000, + maximumScriptByteCount: 100_000 + ), + merklePathLimits: try MerklePathLimits( + maximumByteCount: 1_000_000, + maximumLeavesPerLevel: 1_000, + maximumTotalLeaves: 1_000 + ) + ) + } + + private func overlayLimits( + maximumNameBytes: Int, + maximumHostBytes: Int = 2_048, + maximumHosts: Int = 64 + ) throws -> OverlayLimits { + try OverlayLimits( + maximumTaggedBEEFByteCount: 1_024, + maximumOffChainValueByteCount: 1_024, + maximumTopicCount: 16, + maximumTopicUTF8ByteCount: maximumNameBytes, + maximumServiceUTF8ByteCount: maximumNameBytes, + maximumHostUTF8ByteCount: maximumHostBytes, + maximumMetadataUTF8ByteCount: 1_024, + maximumLookupQueryByteCount: 1_024, + maximumLookupOutputCount: 16, + maximumLookupOutputBEEFByteCount: 1_024, + maximumFreeformByteCount: 1_024, + maximumResolutionHostCount: maximumHosts + ) + } +} + +private enum ParityMockError: Error { + case failed +} + +private actor ParityLookupMock: LookupFacilitator { + private let responses: [OverlayHost: LookupAnswer] + + init(responses: [OverlayHost: LookupAnswer]) { + self.responses = responses + } + + private var count = 0 + + func lookup(question: LookupQuestion, at host: OverlayHost) async throws -> LookupAnswer { + count += 1 + guard let answer = responses[host] else { throw ParityMockError.failed } + return answer + } + + func requestCount() -> Int { count } +} + +private struct ParityResolverMock: OverlayLookupResolving { + let answer: LookupAnswer + + func resolve(_ question: LookupQuestion) async throws -> LookupAnswer { answer } +} + +private actor ParityTopicMock: TopicFacilitator { + private let steaks: [OverlayHost: Steak] + private var sent: [OverlayHost: [OverlayTopic]] = [:] + + init(steaks: [OverlayHost: Steak]) { + self.steaks = steaks + } + + func submit(_ taggedBEEF: TaggedBEEF, to host: OverlayHost) async throws -> Steak { + sent[host] = taggedBEEF.topics + guard let steak = steaks[host] else { throw ParityMockError.failed } + return steak + } + + func topics(for host: OverlayHost) -> [OverlayTopic]? { sent[host] } +}