diff --git a/Documentation/Compatibility/FixtureSources.md b/Documentation/Compatibility/FixtureSources.md index abae042..4ce6a5f 100644 --- a/Documentation/Compatibility/FixtureSources.md +++ b/Documentation/Compatibility/FixtureSources.md @@ -79,7 +79,7 @@ manifest fragment. Their provenance: | Source | `ts-stack` repository, `packages/sdk`, `@bsv/sdk` 4.1.1 | | Revision | `3b1abc5691c0848eb00eaf5e8f018e8a7a26d5f1` | | License | Apache-2.0, from relicensing commit `4760b26d0` (2026-11-11), an ancestor of the revision; NOTICE "Copyright 2020-2026 BSV Association" | -| Generator | `gen.ts`, `det.ts`, `toswift.py` and `collate-vec.ts` in [TypeScriptAuthVectors.md](TypeScriptAuthVectors.md), run with Bun 1.4.4; the collation output was also checked with Node 22.23.4 | +| Generator | `gen.ts`, `det.ts`, `toswift.py`, `collate-vec.ts`, `certorder-vec.ts` and `certwire-vec.ts` in [TypeScriptAuthVectors.md](TypeScriptAuthVectors.md), run with Bun 1.4.4; the collation output was also checked with Node 22.23.4 | | Inputs | Chosen in this repository: private keys 3, 7 and 11, a SHA-256 counter random stream, certificate fields and request targets | | Transformation | Program output written verbatim into Swift string literals by `toswift.py`; no TypeScript source text is copied | diff --git a/Documentation/Compatibility/GoSDK-v1.3.3.md b/Documentation/Compatibility/GoSDK-v1.3.3.md index 5ca46e6..2c3be5b 100644 --- a/Documentation/Compatibility/GoSDK-v1.3.3.md +++ b/Documentation/Compatibility/GoSDK-v1.3.3.md @@ -480,8 +480,8 @@ maps that Swift writes UTF-8-byte-sorted and reads in any order (as `@bsv/sdk` 4.1.1 writes them), and exact keyring presence. `nil` keyring emits `00`; a nonempty keyring emits `01` and its map. An empty keyring is stored as `nil` and emits `00`, as `@bsv/sdk` 4.1.1 writes it. Certificate binary fields are -read in any order (TypeScript writes `localeCompare` order) and written in -byte order. +read in any order and written in `localeCompare` order, as `@bsv/sdk` 4.1.1 +writes and signs them; the pinned Go SDK writes byte order (COMP-041). The Swift codec supports bounded multi-certificate discovery through the intended nested grammar. Live-Go parity uses zero or one item, and the safe Go adapter rejects multiple items before the pinned identity-certificate reader diff --git a/Documentation/Compatibility/Rulings.md b/Documentation/Compatibility/Rulings.md index 85dae89..1af17bd 100644 --- a/Documentation/Compatibility/Rulings.md +++ b/Documentation/Compatibility/Rulings.md @@ -48,7 +48,7 @@ behind the general rule. | COMP-038 | Go wallet request structs encode zero-value artifacts: an omitted or JSON `null` counterparty means an operation-specific default, and an identity-key request may carry `protocolID: [0, ""]`. Treating every `null` as absence would also hide malformed known fields. | Swift accepts missing or `null` counterparty only at the flattened request field and maps it to that operation's `.self` or `.anyone` default. It accepts the exact zero protocol tuple only with `identityKey: true` and no contradictory fields. Canonical output emits the explicit counterparty or only `identityKey: true`; `null` for other known fields is rejected. | This imports Go-generated requests without making the typed JSON model broadly nullable or preserving meaningless zero fields. Tests cover each operation's default, canonical re-encoding, the exact identity artifact, contradictions, and rejected known-field nulls. | | COMP-039 | Go auto-detects Extended Format from the bytes following a transaction version, which makes a valid raw zero-input transaction whose locktime begins with the marker byte sequence ambiguous. BRC-128 prose also shows one extra zero while its table and Go use the six-byte `00 00 00 00 00 EF` marker. | Swift requires callers to select `.raw` or `.extended`, emits and accepts the six-byte marker, and never auto-detects. Extended source amounts remain the eight-byte values selected by COMP-003. | Explicit selection preserves every raw transaction byte string and transaction ID while retaining canonical Go-compatible Extended Format. Tests cover the raw collision, literal marker mismatch/truncation, eight-byte amounts, canonical and permissive CompactSize policies, and bidirectional pinned-Go encoding. | | COMP-040 | An ARC POST can reach the provider before the client receives or validates its response. Official ARC submission success requires `status`, `title`, `timestamp`, `txid`, and `txStatus`. Status lookup success requires `timestamp`, `txid`, and `txStatus`, but it does not require `status` or `title`. A redirect, oversized response, malformed semantic field, or wrong transaction ID does not prove rejection. | Swift never retries an ARC POST. It validates operation-specific fields without removing control or format characters from semantic values. It returns explicit rejection only for a valid matching ARC rejection or a documented ARC validation status. Every other response failure after POST begins returns `uncertainDelivery` with the local transaction ID and a typed cause. | This prevents unsafe automatic resubmission and prevents malformed text from becoming a valid status or proof field. Tests cover preflight failure with zero POSTs, cancellation, timeout, transport loss, redirects, response limits, malformed responses, wrong transaction IDs, official response shapes, semantic-field injection, and explicit rejection. | -| COMP-041 | BRC-52 and Go use display-order revocation transaction IDs. Go also accepts or produces some values that do not satisfy one strict bounded certificate policy. JSON object keys use Unicode string equality. The Go SDK orders binary certificate fields by raw UTF-8 bytes; `@bsv/sdk` 4.1.1 signs and verifies them in JavaScript `localeCompare` order (`Certificate.ts:290`), so a certificate with field names such as `Zip` and `age` signed by one fails to verify in the other. | Swift uses display-order revocation transaction IDs, canonical Base64, canonical CompactSize, strict complete DER, low-S verification, and explicit size limits. `CertificateEngine.issue` signs the fields in `localeCompare` order, using the ICU root collation that Node and Bun use, which `LocaleCompareOrder` reproduces exactly for printable ASCII. `CertificateEngine.issue` refuses field names outside printable ASCII with `CertificateFieldNameError.nonASCII`, because ICU orders accented letters among ASCII ones and ignores control characters, so the order TypeScript verifies could not be predicted. BRC-103 exchange and `CertificateEngine` accept a signature over either the `localeCompare` order or the UTF-8 byte order. The `BSVWallet` binary codec writes raw UTF-8 field-name order and reads fields in any order with no repeated name (COMP-048); `Certificate.verifySignature` still uses byte order. It rejects byte-distinct field names that are canonically equivalent in Unicode so JSON output cannot silently replace a signed field. Certificate verification is cryptographic only. The caller must check the revocation output before it trusts a certificate. | Canonical values stay interoperable with both SDKs; certificates Swift issues verify in TypeScript, and Go and earlier Swift certificates still verify. Strict parsing prevents ambiguous fields, trailing data, hidden signature bytes, and lossy JSON conversion. Tests cover binary and JSON boundaries, Unicode-equivalent names, the order against Bun for all printable ASCII pairs, a TypeScript-signed mixed-case certificate, both signature orders, signature binding, field encryption, verifier projection, all-or-nothing failure, secret redaction, and refusal of non-ASCII names. Certificates with non-ASCII names signed elsewhere are still verified in both orders, and TypeScript hosts with a non-English default locale may order names differently. | +| COMP-041 | BRC-52 and Go use display-order revocation transaction IDs. Go also accepts or produces some values that do not satisfy one strict bounded certificate policy. JSON object keys use Unicode string equality. The Go SDK orders binary certificate fields by raw UTF-8 bytes; `@bsv/sdk` 4.1.1 writes, signs and verifies them in JavaScript `localeCompare` order (`auth/certificates/Certificate.ts:290`, `:437-458`, `:473`), so a certificate with field names such as `Zip` and `age`, `a_1` and `a1`, or `émile` and `zip` signed by one fails to verify in the other. | Swift uses display-order revocation transaction IDs, canonical Base64, canonical CompactSize, strict complete DER, low-S verification, and explicit size limits. `Certificate.binary` writes the fields in `localeCompare` order on an `en-US` host, the untailored ICU root collation, and `Certificate.signed` and `CertificateEngine.issue` sign that binary. TypeScript takes the order from the host's default locale (`Certificate.ts:287-290` calls it host-locale order): Bun always resolves `en-US`, but Node reads `LC_ALL` or `LANG`, so under `LC_ALL=da_DK.UTF-8` Node 22 sorts `email Email id ID aa z` as `Email email ID id z aa`, and under `cs_CZ` `ch` sorts after `h`. Danish, Norwegian, Czech, Slovak, Lithuanian, Estonian, Welsh and Azerbaijani hosts reorder plain ASCII names; Swedish, Polish, Spanish, Turkish, Hungarian and Canadian French hosts also reorder accented ones. Swift targets `en-US`. `LocaleCompareOrder` (BSVCore) reproduces the collation exactly for printable ASCII and for the 488 precomposed Latin letters in U+00C0-U+024F and U+1E00-U+1EFF that decompose to an ASCII letter and combining diacritics, such as `é`, `Å` and `ǖ`. When a certificate has two fields or more, `Certificate.signed` and `CertificateEngine.issue` refuse any other field name with `CertificateFieldNameError.unsupportedCharacter`, because ICU orders other scripts, letters such as `ø` and `ß`, and decomposed accents in ways this SDK does not reproduce, and ignores control characters, so the order TypeScript verifies could not be predicted. A certificate with no field or one has only one order and is signed whatever the name, as TypeScript signs it. `Certificate.verifySignature`, BRC-103 exchange, `CertificateEngine` and `IdentityClient.publiclyRevealAttributes` accept a signature over the `localeCompare` order, over the UTF-8 byte order, or, for a certificate read with `Certificate(binary:)`, over the order its fields arrived in, which is the order its signer signed. The preimage is length-prefixed, so every order commits to the same names and values. A match by byte or received order, and a failure where a name is outside the reproduced characters, are written to the `BSVWallet` log without names or values. `Certificate(binary:)` reads fields in any order with no repeated name (COMP-048). It rejects byte-distinct field names that are canonically equivalent in Unicode so JSON output cannot silently replace a signed field. Certificate verification is cryptographic only. The caller must check the revocation output before it trusts a certificate. | Canonical values stay interoperable with both SDKs; certificates Swift issues verify in TypeScript, TypeScript certificate binary re-encodes byte for byte, and Go and earlier Swift certificates still verify. Go verifies Swift certificates only when `localeCompare` and byte order agree on their names. Strict parsing prevents ambiguous fields, trailing data, hidden signature bytes, and lossy JSON conversion. Tests cover binary and JSON boundaries, Unicode-equivalent names, the order against Bun and Node for all printable ASCII pairs and for the accented Latin letters, TypeScript-signed certificates with mixed-case, accented, underscored and numbered names, both signature orders, signature binding, field encryption, verifier projection, all-or-nothing failure, secret redaction, and refusal of unsupported names. TypeScript certificates with `ß`, Cyrillic and CJK names, and ASCII names signed under a Danish host collation, verify when read from binary. Read from JSON, a certificate whose names are outside the reproduced characters, or that was signed on a host with a tailored collation, has no received order and can fail to verify; such a certificate can also fail in TypeScript on an `en-US` host. | | COMP-042 | Go BIP-276 accepts a broader prefix domain and re-encodes parsed values before checksum comparison. Its BRC-307 enriched-inscription path omits the enriched suffix, and its specific-ordinal helper has unsafe range artifacts. | Swift emits and requires canonical lowercase BIP-276 text with a restricted lowercase prefix. Swift emits the BRC-307 enriched `OP_RETURN` suffix and rejects invalid input indexes, satoshi ranges, missing source data, and arithmetic overflow before transaction mutation. | The Swift rules preserve canonical protocol output and prevent ambiguous text or partial transaction changes. Tests cover every size boundary, checksum, prefix deviation, push boundary, ordinal boundary, atomic failure, and pinned-Go canonical BIP-276 behavior. | | COMP-043 | Go and TypeScript place Bitcoin Signed Message, ECIES, BIP-32, and BIP-39 in explicit compatibility packages, while they differ on raw Base58 placement. | Swift exposes the four common families only through the opt-in `BSVCompat` product, outside the modern `BSV` umbrella. Raw Base58 remains a bounded primitive in `BSVCore`; Address, WIF, Base58Check, BRC-42, BRC-94, and BRC-140 remain in `BSVKeys`. | This preserves the common package boundary without declaring a primitive utility obsolete where the reference SDKs disagree. Structure and compile tests verify module ownership and prevent accidental umbrella re-export. | | COMP-044 | Go places wallet-independent PushDrop construction, decoding, and transaction signing in one package. The Swift target graph cannot place transaction signing in `BSVScript` without a dependency cycle. | Swift keeps wallet-independent PushDrop construction and decoding in `BSVScript`. It keeps transaction signing in `BSVTransaction`. | The split prevents dependency cycles and preserves Go and BRC behavior. Unit and pinned-Go tests cover construction, decoding, and transaction signing across the module boundary. | diff --git a/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md b/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md index 06a3196..4fdeee7 100644 --- a/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md +++ b/Documentation/Compatibility/Rulings/COMP-045-Wallet-Wire-Strictness.md @@ -45,11 +45,23 @@ Encoding follows the TypeScript writers in - A processor never sends an error's type or value to the peer. An error the codecs do not describe gets a fixed text (`Invalid Wallet Wire request`, `Invalid result`). The full error goes to the local log: - subsystem `dev.opl.swift-sdk`, category `BSVWallet` (`WalletLog`). + `BSVLog` category `BSVWallet` (`WalletLog`), which is `os.Logger` subsystem + `dev.opl.swift-sdk` on Apple platforms and the caller's `BSVLog` handler on + every platform. Swift keeps these bounds: canonical CompactSize, explicit frame, payload, text, originator and error limits, checked UInt32 values, low-S DER -signatures, exact SEC1 keys and full payload consumption. +signatures, exact SEC1 keys and full payload consumption. The default frame +bound, `WalletWireLimits.defaultFrameByteCount`, is +`WalletCryptoLimits.defaultPayloadByteCount` (16 MiB plus 512 KiB) plus 64 KiB +of framing (`frameOverheadByteCount`); the call parameters or result payload +of a frame default to the same bound, and `WalletABILimits` bounds an ABI +value's payloads in total by the same amount, so a wallet reached over the +wire signs, verifies, HMACs, encrypts and decrypts every payload BSVAuth and +the wallet's own cryptography accept. TypeScript sets no frame bound. The +JSON form keeps its 8 MiB bounds (`WalletABILimits.maximumBytePayloadCount` +and `WalletCryptoLimits.maximumJSONByteCount`), so a payload over 8 MiB +crosses the binary wire but not a JSON substrate. ## Divergence from pinned Go v1.3.3 diff --git a/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md b/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md index 835911a..6c2671d 100644 --- a/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md +++ b/Documentation/Compatibility/Rulings/COMP-046-Wallet-Wire-Actions.md @@ -38,7 +38,13 @@ balances must cross the wire between Swift and TypeScript in both directions. (`wallet/validationHelpers.ts:680`, `WalletWireProcessor.ts:539-556`). - **BRC-112 balance.** For a basket matching `^(?:balance |p [^ ]+ balance )`, `totalOutputs` is a UInt64 balance with no outputs and no BEEF - (`walletIsBalanceBasket`). Other totals stay within UInt32. + (`walletIsBalanceBasket`). Other totals stay within UInt32. The basket is + matched after `validateIdentifier`'s trim and lowercasing + (`wallet/validationHelpers.ts:376-418`), as the wallet toolbox decides a + balance query, so `" Balance Tickets"` is one. The TypeScript wire codecs + match the raw basket (`WalletWireProcessor.ts:1296`, + `WalletWireTransceiver.ts:726`) and read such an answer as an output + count. - **Spendable listOutputs extension.** A request may end with one `01` byte. The answer then starts with a `-1` marker and each record carries a spendable byte after its locking script. Without the extension a diff --git a/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md b/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md index 1dc333a..36968a4 100644 --- a/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md +++ b/Documentation/Compatibility/Rulings/COMP-048-Wallet-Wire-Certificates.md @@ -18,9 +18,9 @@ certificate frames must be read and answered without rejection. which differs from byte order when names differ in case, digits or punctuation (`cardholder` comes before `cardNumber`). Swift reads certificate fields in any order and rejects only a repeated name, so acquireCertificate, - listCertificates and discovery read TypeScript answers. Swift still writes - byte order; signing and writing in `localeCompare` order follows once that - comparator is available below BSVAuth. + listCertificates and discovery read TypeScript answers. Swift writes and + signs certificate binary in `localeCompare` order too (COMP-041), so a + certificate TypeScript sent re-encodes byte for byte. - **List and discovery totals.** `totalCertificates` counts every match. The records follow with no count and end at the end of the frame. A page may be shorter than its total but never longer. A processor refuses a page longer diff --git a/Documentation/Compatibility/Rulings/COMP-052-BRC-103-104-Core.md b/Documentation/Compatibility/Rulings/COMP-052-BRC-103-104-Core.md index 1228f1a..9c6e204 100644 --- a/Documentation/Compatibility/Rulings/COMP-052-BRC-103-104-Core.md +++ b/Documentation/Compatibility/Rulings/COMP-052-BRC-103-104-Core.md @@ -96,7 +96,8 @@ SDK disagreed on the wire, Swift now follows the SDK: each general payload through the wallet, so `WalletCryptoLimits` defaults to the same 16 MiB plus 512 KiB (`WalletCryptoLimits.defaultPayloadByteCount`, which `AuthLimits.defaultPayloadBytes` is); the TypeScript `ProtoWallet` has - no bound. + no bound. Wallet-wire frames default to that payload plus 64 KiB of framing + (COMP-045), so a wallet reached over the wire signs the same payloads. `Tests/BSVAuthTests/BRC103/TypeScriptInteropTests.swift` replays TypeScript messages from `TypeScriptAuthVectors.md` and checks Swift messages against a diff --git a/Documentation/Compatibility/Rulings/COMP-054-Identity-Core.md b/Documentation/Compatibility/Rulings/COMP-054-Identity-Core.md index 012722c..b431034 100644 --- a/Documentation/Compatibility/Rulings/COMP-054-Identity-Core.md +++ b/Documentation/Compatibility/Rulings/COMP-054-Identity-Core.md @@ -22,7 +22,10 @@ append and writes large Base64 values directly under the limit. Swift requires a wallet. It does not create a random fallback wallet. Swift proves the disclosure keyring to the fixed "anyone" verifier and checks that the wallet returns exactly the requested proved-keyring fields. It verifies the certificate -signature before any disclosure wallet call. +signature before any disclosure wallet call, over the fields in `localeCompare` +order as TypeScript `IdentityClient.publiclyRevealAttributes` does +(`identity/IdentityClient.ts:461`), or over the UTF-8 byte order Go signs +(COMP-041). Swift uses canonical lowercase compressed-key hex for display identity keys. It treats every unrecognized certificate type as unknown. It accepts only diff --git a/Documentation/Compatibility/Rulings/COMP-060-BRC-103-Certificate-Exchange.md b/Documentation/Compatibility/Rulings/COMP-060-BRC-103-Certificate-Exchange.md index 0707a9f..6b95808 100644 --- a/Documentation/Compatibility/Rulings/COMP-060-BRC-103-Certificate-Exchange.md +++ b/Documentation/Compatibility/Rulings/COMP-060-BRC-103-Certificate-Exchange.md @@ -105,12 +105,14 @@ requested certificate type. Errors stay short and name no side, so the same text fits Swift as client or server. The detailed cause of a refused message or certificate, such as the underlying `BRC104Error`, JSON or certificate decoding error, or which -certificate failed which check, is written to the system log on Apple -platforms through `os.Logger` with subsystem `dev.opl.swift-sdk` and category -`BSVAuth`. The reasons `BSVAuth` writes hold no certificate field value, +certificate failed which check, is written to `BSVLog` with category +`BSVAuth`: the system log on Apple platforms through `os.Logger` with +subsystem `dev.opl.swift-sdk`, and the caller's `BSVLog` handler on every +platform. The reasons `BSVAuth` writes hold no certificate field value, keyring, nonce or signature. An underlying error defined by this SDK is logged in full; any other, such as one from a caller's wallet, is public by type only -and its description is marked private. +and its description is marked private. The handler receives that description +as `` unless it was installed with `revealingPrivateDetails`. ## Compatibility diff --git a/Documentation/Compatibility/TypeScriptAuthVectors.md b/Documentation/Compatibility/TypeScriptAuthVectors.md index d725edc..649105f 100644 --- a/Documentation/Compatibility/TypeScriptAuthVectors.md +++ b/Documentation/Compatibility/TypeScriptAuthVectors.md @@ -20,9 +20,21 @@ generator below, under the fixture policy in [FixtureSources.md](FixtureSources.md#recorded-typescript-auth-vectors) and [VectorInventory.md](VectorInventory.md#recorded-typescript-auth-vectors). -`LocaleCompareOrderTests` holds SHA-256 digests and sorted lists printed by -`collate-vec.ts` under Bun 1.4.4 and Node 22.23.4 (ICU, locale `en-US`). Both -runtimes printed the same output. +`LocaleCompareOrderTests` (BSVCoreTests) holds SHA-256 digests and sorted +lists printed by `collate-vec.ts` and `certorder-vec.ts` under Bun 1.4.4 and +Node 22.23.4 (ICU, locale `en-US`). Both runtimes printed the same output. +`certorder-vec.ts` also prints the table of accented Latin letters in +`LocaleCompareOrder` and the certificates in +`CertificateFieldOrderVectorTests` (BSVWalletTests) and +`IdentityClientTests.revealsTypeScriptCertificate`: one signed by +`Certificate.sign` with 30 field names that `localeCompare` and byte order +sort differently by case, accents, underscores and digits, and one with +ASCII names only. `certwire-vec.ts` prints two more certificates signed by +`Certificate.sign` whose order Swift does not compute and verifies only by the +order the fields arrive in: one with `ß`, Cyrillic and CJK names, and one with +ASCII names signed under the collation Node 22 resolves for +`LC_ALL=da_DK.UTF-8` (`da-DK`, capitals first), installed as the host default +because Bun always resolves `en-US`. The vectors cover: @@ -63,10 +75,14 @@ python3 toswift.py vectors.json Tests/BSVAuthTests/BRC103/TypeScriptAuthVectors. `collate-vec.ts` needs no SDK. Its output is compared by hand with the values in `LocaleCompareOrderTests`; under Node it runs as -`node --experimental-strip-types` on a `.mts` copy. +`node --experimental-strip-types` on a `.mts` copy. `certorder-vec.ts` needs +the SDK for its last section; the sections before it ran under Node the same +way, with the SDK import removed. ```sh bun run collate-vec.ts +bun run certorder-vec.ts > certorder.json +bun run certwire-vec.ts > certwire.json ``` ## Checking Swift messages with TypeScript @@ -617,3 +633,198 @@ console.log('names', JSON.stringify(['Zip', 'age', 'a_b', 'a-b', 'ab', 'a b', 'A console.log('headers', JSON.stringify(['x-bsv-zeta', 'x-bsv-a-b', 'x-bsv-a_b', 'x-bsv-ab', 'x-bsv-a.b', 'x-bsv-a1', 'authorization', 'content-type'].sort(cmp))) console.log(process.versions.bun, Intl.Collator().resolvedOptions().locale) ``` + +## `certorder-vec.ts` + +```ts +// Vectors for BRC-52 field order: ICU localeCompare over Latin letters with +// diacritics, and certificates signed by the live @bsv/sdk 4.1.1 source. +import { createHash } from 'node:crypto' +const { PrivateKey, ProtoWallet, Certificate, Utils } = await import(`${process.env.TS_SDK}/mod.ts`) + +const cmp = (a: string, b: string) => a.localeCompare(b) +const hash = (xs: string[]) => createHash('sha256').update(xs.join('\n'), 'utf8').digest('hex') +const base = new Intl.Collator(undefined, { sensitivity: 'base' }) +const out: Record = {} + +// 1. Precomposed Latin letters whose canonical decomposition is an ASCII +// letter followed by combining diacritics (U+0300-U+036F). +const ranges = [[0x00c0, 0x024f], [0x1e00, 0x1eff]] +const table: [number, string, number[]][] = [] +const marks = new Set() +for (const [lo, hi] of ranges) { + for (let cp = lo; cp <= hi; cp++) { + const ch = String.fromCodePoint(cp) + const nfd = ch.normalize('NFD') + const scalars = [...nfd].map(c => c.codePointAt(0)!) + if (scalars.length < 2) continue + const [first, ...rest] = scalars + if (!/^[A-Za-z]$/.test(String.fromCodePoint(first))) continue + if (!rest.every(m => m >= 0x300 && m <= 0x36f)) continue + if (cmp(ch, nfd) !== 0) throw new Error(`not equal to its NFD: ${cp.toString(16)}`) + if (base.compare(ch, String.fromCodePoint(first)) !== 0) throw new Error(`primary differs: ${cp.toString(16)}`) + rest.forEach(m => marks.add(m)) + table.push([cp, String.fromCodePoint(first), rest]) + } +} +// 2. The secondary order of those marks: each has no primary weight. +const markList = [...marks].sort((a, b) => a - b) +for (const m of markList) { + if (base.compare('x' + String.fromCodePoint(m), 'x') !== 0) throw new Error(`mark has primary: ${m.toString(16)}`) +} +const ranked = [...markList].sort((a, b) => cmp('x' + String.fromCodePoint(a), 'x' + String.fromCodePoint(b))) +const ranks: [number, number][] = [] +let rank = 0 +for (let i = 0; i < ranked.length; i++) { + if (i > 0 && cmp('x' + String.fromCodePoint(ranked[i - 1]), 'x' + String.fromCodePoint(ranked[i])) !== 0) rank++ + ranks.push([ranked[i], rank + 1]) +} +out.markOrder = ranks.map(([m, r]) => [m.toString(16), r]) +out.letterCount = table.length +out.table = table.map(([cp, b, ms]) => [cp.toString(16), b, ms.map(m => m.toString(16))]) + +// 3. Ordering checks over ASCII and accented letters. +const letters = table.map(([cp]) => String.fromCodePoint(cp)) +const ascii: string[] = [] +for (let c = 0x20; c <= 0x7e; c++) ascii.push(String.fromCharCode(c)) +const singles = [...ascii, ...letters] +out.singles = hash([...singles].sort(cmp)) +const alphabet = [...'aAeEzZ_-1 .', 'á', 'Á', 'à', 'â', 'ä', 'å', 'é', 'É', 'è', 'ê', 'ë', 'ǖ', 'ü', 'ű', 'ñ', 'Ñ', 'ç', 'ș', 'ţ', 'ắ', 'ạ'] +const pairs: string[] = [] +for (const a of alphabet) for (const b of alphabet) pairs.push(a + b) +let ties = 0 +const sp = [...pairs].sort(cmp) +for (let i = 0; i + 1 < sp.length; i++) if (cmp(sp[i], sp[i + 1]) === 0) ties++ +out.alphabet = alphabet.join('') +out.pairs = [pairs.length, ties, hash(sp)] +const letterPairs: string[] = [] +const pool = [...'aAbBeEnNoOuUzZ', ...letters.filter((_, i) => i % 4 === 0)] +for (const a of pool) for (const b of pool) letterPairs.push(a + b) +let lties = 0 +const slp = [...letterPairs].sort(cmp) +for (let i = 0; i + 1 < slp.length; i++) if (cmp(slp[i], slp[i + 1]) === 0) lties++ +out.letterPairs = [letterPairs.length, lties, hash(slp)] +let x = 7 +const next = () => { x = (Math.imul(x, 1103515245) + 12345) >>> 0 & 0x7fffffff; return x } +const randomAlphabet = [...ascii, ...letters] +const randoms: string[] = [] +for (let i = 0; i < 6000; i++) { + const len = 1 + (next() % 8) + let s = '' + for (let k = 0; k < len; k++) s += randomAlphabet[next() % randomAlphabet.length] + randoms.push(s) +} +const uniq = [...new Set(randoms)] +const rs = [...uniq].sort(cmp) +let rties = 0 +for (let i = 0; i + 1 < rs.length; i++) if (cmp(rs[i], rs[i + 1]) === 0) rties++ +out.randoms = [randomAlphabet.length, uniq.length, rties, hash(rs), randoms.slice(0, 3)] + +// 4. Certificates signed by Certificate.sign with names whose localeCompare +// order differs from byte order: case, accents, underscores and digits. +const certifier = new PrivateKey(11) +const subject = new PrivateKey(7) +const names = [ + 'Zip', 'zip_code', 'zip-code', 'zip2', 'zip10', 'Zeta', 'email', 'eMail', 'Email', + '_id', 'id', 'ID', 'a1', 'a_1', 'a-1', 'aB', 'ab', 'cafe', 'café', 'Café', 'cafés', + 'émile', 'Émile', 'naïve', 'nausea', 'résumé', 'resume', 'zoë', 'Ångström', 'angle', +] +const sortedNames = [...names].sort(cmp) +out.certNames = names +out.certNamesSorted = sortedNames +const fields: Record = {} +names.forEach((n, i) => { fields[n] = Utils.toBase64([i + 1]) }) +const cert = new Certificate( + Utils.toBase64(new Array(32).fill(0x31)), + Utils.toBase64(new Array(32).fill(0x32)), + subject.toPublicKey().toString(), + certifier.toPublicKey().toString(), + '0000000000000000000000000000000000000000000000000000000000000000.0', + fields +) +await cert.sign(new ProtoWallet(certifier)) +out.certJSON = JSON.stringify({ + type: cert.type, serialNumber: cert.serialNumber, subject: cert.subject, certifier: cert.certifier, + revocationOutpoint: cert.revocationOutpoint, fields: cert.fields, signature: cert.signature +}) +out.certBinary = Utils.toHex(cert.toBinary(true)) +out.certPreimage = Utils.toHex(cert.toBinary(false)) +out.certVerifies = await cert.verify() + +// An ASCII-only certificate Swift can also sign, for an exact signature match. +const asciiNames = ['Zip', 'zip_code', 'zip-code', 'zip2', 'zip10', 'email', 'Email', '_id', 'ID', 'id', 'a_1', 'a1'] +const asciiFields: Record = {} +asciiNames.forEach((n, i) => { asciiFields[n] = Utils.toBase64([0x40 + i]) }) +const asciiCert = new Certificate( + Utils.toBase64(new Array(32).fill(0x33)), + Utils.toBase64(new Array(32).fill(0x34)), + subject.toPublicKey().toString(), + certifier.toPublicKey().toString(), + '0000000000000000000000000000000000000000000000000000000000000000.0', + asciiFields +) +await asciiCert.sign(new ProtoWallet(certifier)) +out.asciiCertBinary = Utils.toHex(asciiCert.toBinary(true)) +out.asciiCertPreimage = Utils.toHex(asciiCert.toBinary(false)) +out.asciiCertVerifies = await asciiCert.verify() +out.runtime = [process.versions.bun ?? null, process.versions.node, Intl.Collator().resolvedOptions().locale] +console.log(JSON.stringify(out, null, 1)) +``` + +## `certwire-vec.ts` + +```ts +// Certificates signed by @bsv/sdk 4.1.1 Certificate.sign whose field order +// Swift's localeCompare emulation does not reproduce: names outside printable +// ASCII and accented Latin (ß, Cyrillic, CJK), and plain ASCII names signed +// on a host whose default collation is Danish. +const { PrivateKey, ProtoWallet, Certificate, Utils } = await import(`${process.env.TS_SDK}/mod.ts`) + +const certifier = new PrivateKey(11) +const subject = new PrivateKey(7) +const outpoint = '0000000000000000000000000000000000000000000000000000000000000000.0' + +async function signed(typeByte: number, serialByte: number, names: string[]) { + const fields: Record = {} + names.forEach((n, i) => { fields[n] = Utils.toBase64([i + 1]) }) + const cert = new Certificate( + Utils.toBase64(new Array(32).fill(typeByte)), + Utils.toBase64(new Array(32).fill(serialByte)), + subject.toPublicKey().toString(), + certifier.toPublicKey().toString(), + outpoint, + fields + ) + await cert.sign(new ProtoWallet(certifier)) + return { + names, + sorted: [...names].sort((a, b) => a.localeCompare(b)), + json: JSON.stringify({ + type: cert.type, serialNumber: cert.serialNumber, subject: cert.subject, certifier: cert.certifier, + revocationOutpoint: cert.revocationOutpoint, fields: cert.fields, signature: cert.signature + }), + binary: Utils.toHex(cert.toBinary(true)), + verifies: await cert.verify() + } +} + +const out: Record = {} +out.exotic = await signed(0x35, 0x36, [ + 'straße', 'strasse', 'strat', 'stress', 'имя', 'Имя', 'ёлка', 'ель', '日本', '名前', 'name', 'Name' +]) + +// A Danish host: Node takes the default collation from LC_ALL/LANG, and under +// LC_ALL=da_DK.UTF-8 Node 22 resolves { locale: 'da-DK', caseFirst: 'upper' }. +// Bun always resolves en-US, so that collator is installed here as the host +// default; the order it gives is checked against Node's below. +const native = String.prototype.localeCompare +const danish = new Intl.Collator('da-DK', { caseFirst: 'upper' }) +String.prototype.localeCompare = function (that: string) { return danish.compare(String(this), that) } +out.danish = await signed(0x37, 0x38, ['email', 'Email', 'id', 'ID', 'aa', 'z']) +String.prototype.localeCompare = native +const nodeDanishOrder = ['Email', 'email', 'ID', 'id', 'z', 'aa'] +if ((out.danish as any).sorted.join() !== nodeDanishOrder.join()) throw new Error('not the Node da_DK order') +out.danishRootOrder = [...(out.danish as any).names].sort((a: string, b: string) => a.localeCompare(b)) +out.runtime = [process.versions.bun ?? null, process.versions.node, Intl.Collator().resolvedOptions().locale] +console.log(JSON.stringify(out, null, 1)) +``` diff --git a/Documentation/Compatibility/VectorInventory.md b/Documentation/Compatibility/VectorInventory.md index 5afb317..1d2c493 100644 --- a/Documentation/Compatibility/VectorInventory.md +++ b/Documentation/Compatibility/VectorInventory.md @@ -50,7 +50,8 @@ the dependency NOTICE information. | Family | Committed source | License | Notes | | --- | --- | --- | --- | | BRC-103/104 wire messages and BRC-104 payloads | Output of `@bsv/sdk` 4.1.1 at `ts-stack` `3b1abc5691c0848eb00eaf5e8f018e8a7a26d5f1`, recorded by the generator in [TypeScriptAuthVectors.md](TypeScriptAuthVectors.md) | Apache-2.0 (relicensed in `4760b26d0`, 2026-11-11) | `TypeScriptAuthVectors.swift`: handshake, certificate request and response, handshake certificates in initialResponse, empty-certifier request, mixed-case certificate signature and preimage, `AuthFetch` headers and serialized payloads, and an `AuthFetch` certificateResponse answering a Swift server's initialResponse policy. Live checks of Swift output in TypeScript run from the same scripts and are not committed. | -| `localeCompare` order | Output of `collate-vec.ts` under Bun 1.4.4 and Node 22.23.4 (ICU `en-US`) | Independently authored script; runtime output only | `LocaleCompareOrderTests.swift`: printable ASCII order, SHA-256 of all 9025 two-character strings, 1331 three-character strings and 4000 pseudo-random strings, and named examples. | +| `localeCompare` order | Output of `collate-vec.ts` and `certorder-vec.ts` under Bun 1.4.4 and Node 22.23.4 (ICU `en-US`) | Independently authored scripts; runtime output only | `LocaleCompareOrderTests.swift` (BSVCoreTests): printable ASCII order, SHA-256 of all 9025 two-character strings, 1331 three-character strings and 4000 pseudo-random strings; the 488 accented Latin letters with printable ASCII, 1024 and 18496 two-character strings and 6000 pseudo-random strings over them; and named examples. The accented-letter table in `LocaleCompareOrder.swift` is the same script's output. | +| BRC-52 certificates in `localeCompare` order | Output of `certorder-vec.ts` against `@bsv/sdk` 4.1.1 at `ts-stack` `3b1abc5691c0848eb00eaf5e8f018e8a7a26d5f1` | Apache-2.0 (relicensed in `4760b26d0`) | `CertificateFieldOrderVectorTests.swift` (BSVWalletTests) and `IdentityClientTests.swift`: a certificate with 30 mixed-case, accented, underscored and numbered field names as JSON and binary, and an ASCII-only certificate's binary. `certwire-vec.ts` adds a certificate with `ß`, Cyrillic and CJK names and one signed under the Node `da-DK` host collation, each as JSON and binary. | See [FixtureSources.md](FixtureSources.md#recorded-typescript-auth-vectors) for the provenance record. diff --git a/Package.swift b/Package.swift index 747435d..3e49e8e 100644 --- a/Package.swift +++ b/Package.swift @@ -171,7 +171,7 @@ let package = Package( ), .testTarget( name: "BSVCoreTests", - dependencies: ["BSVCore"], + dependencies: ["BSVCore", "BSVCrypto"], exclude: ["README.md"] ), .testTarget( diff --git a/README.md b/README.md index 693edab..276e43f 100644 --- a/README.md +++ b/README.md @@ -214,6 +214,17 @@ print(script.isPayToPublicKeyHash) - Redacts secret values from default descriptions and reflection. - Reports an ARC response failure after POST as uncertain delivery. - Compares specified wire formats with the pinned Go SDK v1.3.3. +- Logs the full cause of a failure it reports more briefly, to `os.Logger` on + Apple platforms (subsystem `dev.opl.swift-sdk`) and, on every platform, to a + handler you install. The text of an error thrown by your own code, such as + a wallet or an HTTP transport, is marked private and reaches the handler as + `` unless you opt in: + + ```swift + BSVLog.setHandler { entry in + print("[\(entry.category)] \(entry.message)") + } + ``` ## Modules diff --git a/Sources/BSVAuth/AuthLog.swift b/Sources/BSVAuth/AuthLog.swift index 7ca4cf2..7af608a 100644 --- a/Sources/BSVAuth/AuthLog.swift +++ b/Sources/BSVAuth/AuthLog.swift @@ -1,9 +1,9 @@ +import BSVCore import Foundation -#if canImport(os) -import os -#endif -/// The authentication log: subsystem `dev.opl.swift-sdk`, category `BSVAuth`. +/// The authentication log: `BSVLog` category `BSVAuth`, written to +/// `os.Logger` on Apple platforms and to the caller's `BSVLog` handler on +/// every platform. /// /// When a detailed error is reported to the caller as a shorter one, such as /// a `BRC104Error` reported as `BRC104HTTPFramingError.invalidFrame`, the @@ -17,9 +17,10 @@ import os /// known to carry a key or a certificate field value. Any other underlying /// error, such as one thrown by a caller's wallet, is public only by type: /// its description is marked private, so whatever that code put in it does -/// not reach a shared log in clear. +/// not reach a shared log in clear. A `BSVLog` handler receives it as +/// `` unless it was installed with `revealingPrivateDetails`. package enum AuthLog { - package static let subsystem = "dev.opl.swift-sdk" + package static let subsystem = BSVLog.subsystem package static let category = "BSVAuth" /// One line about an underlying error, split where the privacy marker @@ -32,21 +33,19 @@ package enum AuthLog { /// The line as a reader of the system log without private data sees it. package var publicText: String { - prefix + (detailIsPrivate ? "" : detail) + suffix + prefix + (detailIsPrivate ? BSVLog.privatePlaceholder : detail) + suffix } } /// Receives each line as well as the system log, for tests. @TaskLocal package static var observer: (@Sendable (String) -> Void)? - /// Receives each underlying-error entry as it is passed to `os.Logger`, for tests. + /// Receives each underlying-error entry as it is passed to `BSVLog`, for tests. @TaskLocal package static var entryObserver: (@Sendable (Entry) -> Void)? package static func error(_ message: String) { observer?(message) - #if canImport(os) - Logger(subsystem: subsystem, category: category).error("\(message, privacy: .public)") - #endif + BSVLog.error(category: category, message) } /// Records the detailed error behind a shorter one the caller receives. @@ -58,18 +57,12 @@ package enum AuthLog { observer?(line(operation, underlying, as: reported)) let entry = entry(operation, underlying, as: reported) entryObserver?(entry) - #if canImport(os) - let logger = Logger(subsystem: subsystem, category: category) - if entry.detailIsPrivate { - logger.error( - "\(entry.prefix, privacy: .public)\(entry.detail, privacy: .private)\(entry.suffix, privacy: .public)" - ) - } else { - logger.error( - "\(entry.prefix, privacy: .public)\(entry.detail, privacy: .public)\(entry.suffix, privacy: .public)" - ) - } - #endif + BSVLog.error( + category: category, + prefix: entry.prefix, + detail: entry.detail, + detailIsPrivate: entry.detailIsPrivate, + suffix: entry.suffix) } package static func entry( @@ -86,15 +79,9 @@ package enum AuthLog { /// Whether `error` is a type this SDK defines. package static func isSDKError(_ error: any Error) -> Bool { - let module = String(reflecting: type(of: error)).prefix { $0 != "." } - return sdkModules.contains(String(module)) + BSVLog.isSDKError(error) } - private static let sdkModules: Set = [ - "BSVAuth", "BSVCore", "BSVCrypto", "BSVKeys", "BSVMessage", "BSVScript", - "BSVTransaction", "BSVWallet", - ] - /// Records why a check failed when the caller receives only `reported`. package static func rejected( _ operation: String, diff --git a/Sources/BSVAuth/BRC103/AuthCertificateExchange.swift b/Sources/BSVAuth/BRC103/AuthCertificateExchange.swift index e1de3f1..d13dca6 100644 --- a/Sources/BSVAuth/BRC103/AuthCertificateExchange.swift +++ b/Sources/BSVAuth/BRC103/AuthCertificateExchange.swift @@ -44,7 +44,7 @@ public enum AuthCertificateExchange { else { continue } do { - guard try await certificate.verifySignatureInEitherFieldOrder(limits: limits.certificateLimits) else { + guard try await certificate.verifySignature(limits: limits.certificateLimits) else { throw AuthError.certificateValidationFailed } } catch is CancellationError { diff --git a/Sources/BSVAuth/Certificates/CertificateEngine.swift b/Sources/BSVAuth/Certificates/CertificateEngine.swift index 107fc78..db700df 100644 --- a/Sources/BSVAuth/Certificates/CertificateEngine.swift +++ b/Sources/BSVAuth/Certificates/CertificateEngine.swift @@ -12,10 +12,12 @@ public enum CertificateEngine { /// rejected rather than silently being treated as self, a stricter Swift /// deviation from the pinned Go helper's ambiguous fallback. /// - /// The certificate is signed with its fields in `localeCompare` order, as - /// `@bsv/sdk` signs them (`certificates/Certificate.ts:290`). Field names - /// must be ASCII; another name throws `CertificateFieldNameError.nonASCII` - /// (COMP-041). + /// The certificate is signed with its fields in `localeCompare` order on an + /// `en-US` host, as `@bsv/sdk` signs them + /// (`auth/certificates/Certificate.ts:290`). With two fields or more, field + /// names must use only printable ASCII and accented Latin letters; another + /// name throws `CertificateFieldNameError.unsupportedCharacter` before any + /// field is encrypted. A single field may have any name (COMP-041). public static func issue( type: CertificateTypeID, serialNumber suppliedSerialNumber: CertificateSerialNumber? = nil, @@ -27,7 +29,14 @@ public enum CertificateEngine { randomSource: any SecureRandomSource = SystemSecureRandomSource() ) async throws -> MasterCertificate { try validateFieldSet(plaintextFields, limits: limits) - try Certificate.requireASCIIFieldNames(plaintextFields.keys) + if let name = Certificate.fieldNameWithoutExactOrder(in: plaintextFields.keys) { + AuthLog.rejected( + "Certificate issue", + "a field name of \(name.utf8Bytes.count) bytes has a character whose " + + "localeCompare order is not reproduced", + as: CertificateFieldNameError.unsupportedCharacter) + throw CertificateFieldNameError.unsupportedCharacter + } let serialNumber: CertificateSerialNumber if let suppliedSerialNumber { serialNumber = suppliedSerialNumber @@ -62,7 +71,7 @@ public enum CertificateEngine { fields: encrypted.fields, limits: limits ) - let signed = try await unsigned.signedInLocaleOrder(using: certifierWallet, limits: limits) + let signed = try await unsigned.signed(using: certifierWallet, limits: limits) return try MasterCertificate(certificate: signed, masterKeyring: encrypted.keyring) } @@ -80,7 +89,7 @@ public enum CertificateEngine { if let certifier = requirements.certifier, certifier != certificate.certifier { throw CertificateError.requirementMismatch } if let outpoint = requirements.revocationOutpoint, outpoint != certificate.revocationOutpoint { throw CertificateError.requirementMismatch } try validateKeyringBounds(masterCertificate.masterKeyring, limits: limits) - guard try await certificate.verifySignatureInEitherFieldOrder(limits: limits) else { + guard try await certificate.verifySignature(limits: limits) else { throw CertificateError.signatureMismatch } let identity = try await subjectWallet.getPublicKey(.init(selection: .identity)).publicKey @@ -122,7 +131,7 @@ public enum CertificateEngine { throw CertificateError.fieldNotFound } try validateKeyringBounds(masterCertificate.masterKeyring, limits: limits) - guard try await certificate.verifySignatureInEitherFieldOrder(limits: limits) else { + guard try await certificate.verifySignature(limits: limits) else { throw CertificateError.signatureMismatch } let identity = try await subjectWallet.getPublicKey(.init(selection: .identity)).publicKey @@ -186,7 +195,7 @@ public enum CertificateEngine { ) async throws -> [CertificateFieldName: String] { let certificate = verifiableCertificate.certificate try validateKeyringBounds(verifiableCertificate.keyring, limits: limits) - guard try await certificate.verifySignatureInEitherFieldOrder(limits: limits) else { + guard try await certificate.verifySignature(limits: limits) else { throw CertificateError.signatureMismatch } return try await decryptAll( diff --git a/Sources/BSVAuth/Certificates/CertificateSigningOrder.swift b/Sources/BSVAuth/Certificates/CertificateSigningOrder.swift deleted file mode 100644 index 873a432..0000000 --- a/Sources/BSVAuth/Certificates/CertificateSigningOrder.swift +++ /dev/null @@ -1,127 +0,0 @@ -import BSVCore -import BSVCrypto -import BSVKeys -import BSVWallet -import Foundation - -/// BRC-52 certificate signatures with fields in `localeCompare` order. -/// -/// `@bsv/sdk` signs and verifies the certificate binary with its fields sorted -/// by `localeCompare` (`certificates/Certificate.ts:290`). The Go SDK and -/// `Certificate.binary` sort them by UTF-8 bytes. The two orders agree for -/// lowercase ASCII names and differ for mixed case and some punctuation, for -/// example `age, Zip` against `Zip, age`. This SDK signs in the TypeScript order -/// and accepts a signature over either order. -extension Certificate { - /// The unsigned BRC-52 binary with fields in `LocaleCompareOrder`. - package func localeOrderSigningPreimage(limits: CertificateLimits) throws -> [UInt8] { - let byteOrder = try binary(includingSignature: false, limits: limits) - var records: [CertificateFieldName: [UInt8]] = [:] - var recordBytes = 0 - for (name, value) in fields { - let record = - CompactSize.encodeVarBytes(name.utf8Bytes) - + CompactSize.encodeVarBytes(Array(value.base64.utf8)) - records[name] = record - recordBytes += record.count - } - // The field records end the byte-order binary, so they cannot be - // longer than it. - guard recordBytes <= byteOrder.count else { throw CertificateError.sizeOverflow } - var preimage = Array(byteOrder.prefix(byteOrder.count - recordBytes)) - let names = fields.keys.sorted { - LocaleCompareOrder.areInIncreasingOrder($0.value, $1.value) - } - for name in names { - guard let record = records[name] else { throw CertificateError.fieldNotFound } - preimage += record - } - return preimage - } - - /// Signs the `localeCompare`-ordered preimage with the certifier wallet, - /// as `Certificate.sign` does in `@bsv/sdk`. - /// - /// Field names must be ASCII, the range where `LocaleCompareOrder` is - /// exact. A name with another character could be signed in an order that - /// TypeScript does not reproduce. - package func signedInLocaleOrder( - using wallet: any CertificateSignatureWallet, - limits: CertificateLimits - ) async throws -> Certificate { - guard signature == nil else { throw CertificateError.alreadySigned } - try Self.requireASCIIFieldNames(fields.keys) - let preimage = try localeOrderSigningPreimage(limits: limits) - let identity = try await wallet.getPublicKey(.init(selection: .identity)).publicKey - guard identity == certifier else { throw CertificateError.walletIdentityMismatch } - let result = try await wallet.createSignature( - .init( - protocolID: try CertificateProtocols.signature, - keyID: try WalletKeyID(signatureKeyID), - counterparty: .anyone, - payload: .digest(BSVHashing.sha256(preimage)) - )) - let signed = try replacingSignature(result.signature, limits: limits) - _ = try signed.binary(includingSignature: true, limits: limits) - return signed - } - - /// Throws `CertificateFieldNameError.nonASCII` unless every name is - /// printable ASCII (0x20-0x7E). ICU ignores control characters, so names - /// that differ only by them compare equal and their signed order would - /// depend on how the signer inserted them. - package static func requireASCIIFieldNames( - _ names: some Sequence - ) throws { - for name in names where !name.utf8Bytes.allSatisfy({ (0x20...0x7E).contains($0) }) { - AuthLog.rejected( - "Certificate signing", - "a field name of \(name.utf8Bytes.count) bytes is not printable ASCII", - as: CertificateFieldNameError.nonASCII) - throw CertificateFieldNameError.nonASCII - } - } - - /// Verifies the certifier signature over the `localeCompare`-ordered - /// preimage, or over the UTF-8 byte-ordered preimage that the Go SDK and - /// earlier releases of this SDK sign. - package func verifySignatureInEitherFieldOrder(limits: CertificateLimits) async throws -> Bool { - guard let signature else { throw CertificateError.missingSignature } - _ = try binary(includingSignature: true, limits: limits) - let preimage = try localeOrderSigningPreimage(limits: limits) - let verifier = try ProtoWallet.anyone() - let valid = try await verifier.verifySignature( - .init( - protocolID: try CertificateProtocols.signature, - keyID: try WalletKeyID(signatureKeyID), - counterparty: .publicKey(certifier), - payload: .digest(BSVHashing.sha256(preimage)), - signature: signature - ) - ).valid - if valid { return true } - guard try preimage != binary(includingSignature: false, limits: limits) else { - return false - } - return try await verifySignature(limits: limits) - } -} - -/// A certificate field name this SDK will not sign. -/// -/// `@bsv/sdk` orders signed field names with `localeCompare`, the ICU root -/// collation. `LocaleCompareOrder` reproduces it exactly only for printable -/// ASCII, so `CertificateEngine.issue` refuses other names, including -/// control characters, rather than sign a -/// certificate TypeScript may not verify. Certificates with such names signed -/// elsewhere are still verified in both orders this SDK knows. -public enum CertificateFieldNameError: Error, Equatable, Sendable, LocalizedError { - case nonASCII - - public var errorDescription: String? { - switch self { - case .nonASCII: - "Certificate field names must use only plain ASCII letters, digits, spaces and symbols." - } - } -} diff --git a/Sources/BSVAuth/Certificates/LocaleCompareOrder.swift b/Sources/BSVAuth/Certificates/LocaleCompareOrder.swift deleted file mode 100644 index 70f0488..0000000 --- a/Sources/BSVAuth/Certificates/LocaleCompareOrder.swift +++ /dev/null @@ -1,99 +0,0 @@ -/// The order `@bsv/sdk` sorts signed names in: JavaScript -/// `String.prototype.localeCompare` with no arguments, which Node and Bun -/// implement with the ICU root collation (`en-US`, tertiary strength, -/// punctuation not ignored). -/// -/// TypeScript uses it for certificate field names in the BRC-52 signing -/// preimage (`certificates/Certificate.ts:290`) and for signed BRC-104 header -/// names (`clients/AuthFetch.ts:740`, -/// `transports/SimplifiedFetchTransport.ts:286`, -/// `auth-express-middleware/src/index.ts:2105`). -/// -/// The order is exact for ASCII. Strings compare by primary weight first: -/// whitespace, then punctuation and symbols in ICU order, then digits, then -/// letters with case ignored. Remaining ties are broken by case, lowercase -/// first. ICU ignores the C0 controls other than tab, line feed, vertical tab, -/// form feed and carriage return, and DEL; so does this order. -/// -/// Other characters are not collated as ICU collates them. C1 controls and the -/// default-ignorable format characters are ignored; every other non-ASCII -/// scalar sorts after all ASCII, in code point order. Names with such -/// characters can sort differently in TypeScript. Strings ICU treats as equal -/// are ordered by UTF-8 bytes, so the order is total; TypeScript keeps their -/// insertion order instead. -package enum LocaleCompareOrder { - /// `true` when `lhs` sorts before `rhs`. - package static func areInIncreasingOrder(_ lhs: String, _ rhs: String) -> Bool { - compare(lhs, rhs) < 0 - } - - /// A negative, zero or positive value, as `localeCompare` returns, with - /// collation ties broken by UTF-8 bytes. - package static func compare(_ lhs: String, _ rhs: String) -> Int { - let left = key(lhs) - let right = key(rhs) - if let order = compareSequences(left.primary, right.primary) { return order } - if let order = compareSequences(left.tertiary, right.tertiary) { return order } - return compareSequences(Array(lhs.utf8), Array(rhs.utf8)) ?? 0 - } - - /// The ASCII characters ICU does not ignore, in ICU root order, each - /// lowercase letter followed by its uppercase form. - package static let asciiOrder = - "\t\n\u{0B}\u{0C}\r _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$0123456789" - + "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ" - - /// The primary weight of each ASCII scalar, or `nil` when ICU ignores it. - /// An uppercase letter shares the weight of its lowercase form. - private static let asciiPrimary: [UInt32?] = { - var table = [UInt32?](repeating: nil, count: 128) - var weight: UInt32 = 0 - for scalar in asciiOrder.unicodeScalars { - let code = Int(scalar.value) - if (65...90).contains(code) { - table[code] = table[code + 32] - } else { - weight += 1 - table[code] = weight - } - } - return table - }() - - private struct Key { - var primary: [UInt32] = [] - var tertiary: [UInt8] = [] - } - - private static func key(_ value: String) -> Key { - var result = Key() - for scalar in value.unicodeScalars { - let code = scalar.value - if code < 128 { - guard let primary = asciiPrimary[Int(code)] else { continue } - result.primary.append(primary) - result.tertiary.append((65...90).contains(code) ? 1 : 0) - } else if !ignorable(code) { - result.primary.append(1_000 + code) - result.tertiary.append(0) - } - } - return result - } - - private static func ignorable(_ code: UInt32) -> Bool { - switch code { - case 0x80...0x9F, 0xAD, 0x200B...0x200F, 0x2060...0x2064, 0xFEFF: return true - default: return false - } - } - - private static func compareSequences( - _ lhs: [Element], _ rhs: [Element] - ) -> Int? { - for (left, right) in zip(lhs, rhs) where left != right { - return left < right ? -1 : 1 - } - return lhs.count == rhs.count ? nil : (lhs.count < rhs.count ? -1 : 1) - } -} diff --git a/Sources/BSVCore/Logging/BSVLog.swift b/Sources/BSVCore/Logging/BSVLog.swift new file mode 100644 index 0000000..32adc43 --- /dev/null +++ b/Sources/BSVCore/Logging/BSVLog.swift @@ -0,0 +1,217 @@ +#if canImport(os) +import os +#endif +#if canImport(Darwin) +import Darwin +#elseif canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#elseif canImport(Android) +import Android +#elseif os(Windows) +import WinSDK +#endif + +/// The SDK's diagnostic log, shared by every module. +/// +/// The SDK writes a line here when it reports a failure to the caller as a +/// shorter error, or leaves something out: a wire peer's unreadable frame, a +/// provider's failed response, an overlay host that failed, a certificate that +/// did not verify. Each line belongs to one category, the module that wrote +/// it: `BSVAuth`, `BSVNetwork`, `BSVOverlay` or `BSVWallet`. +/// +/// On Apple platforms every line goes to `os.Logger` with subsystem +/// `dev.opl.swift-sdk` and that category, at error level. On every platform, +/// Linux included, it also goes to the handler installed with +/// `setHandler(_:revealingPrivateDetails:)`, if any; with no handler, nothing +/// is written on platforms without `os`. +/// +/// Some lines hold a detail the system log marks private, such as the +/// description of an error thrown by a caller's wallet, which may carry +/// whatever that code put in it. The handler receives such a line with the +/// detail replaced by ``, as the system log shows it without private +/// data, unless the handler was installed with `revealingPrivateDetails`. +/// +/// ```swift +/// BSVLog.setHandler { entry in +/// logger.error("\(entry.category): \(entry.message)") +/// } +/// ``` +public enum BSVLog { + /// The `os.Logger` subsystem of every line. + public static let subsystem = "dev.opl.swift-sdk" + + /// One line of the log. + public struct Entry: Sendable, Equatable { + /// The module that wrote the line, such as `BSVWallet`. + public let category: String + /// The line. A private detail reads `` unless the handler + /// was installed with `revealingPrivateDetails`. + public let message: String + /// Whether the line holds a detail the system log marks private, + /// shown or replaced in `message`. + public let hasPrivateDetail: Bool + + public init(category: String, message: String, hasPrivateDetail: Bool) { + self.category = category + self.message = message + self.hasPrivateDetail = hasPrivateDetail + } + } + + /// Receives each line. It is called synchronously on the thread that + /// writes the line, from any thread and from several threads at once, so + /// it must be quick and thread-safe. + /// + /// The handler is called outside the SDK's lock, so it may call + /// `setHandler` or make SDK calls. A call that writes a line, such as a + /// failed signature check, calls the handler again from inside it, and a + /// handler that does so on every line recurses without end. A line + /// already being written when `setHandler` returns can still reach the + /// handler that was replaced or removed, with that handler's own + /// `revealingPrivateDetails` setting; every line written after it returns + /// goes to the new handler. + public typealias Handler = @Sendable (Entry) -> Void + + /// Installs `handler` for every line the SDK writes from now on, in place + /// of any handler installed before; `nil` removes it. + /// + /// With `revealingPrivateDetails`, lines carry their private details in + /// plain text. Set it only when the handler's output is as private as the + /// data the SDK handles, such as during local debugging. + public static func setHandler(_ handler: Handler?, revealingPrivateDetails: Bool = false) { + store.set(handler, revealingPrivateDetails: revealingPrivateDetails) + } + + /// Writes a line with no private part. + package static func error(category: String, _ message: String) { + #if canImport(os) + Logger(subsystem: subsystem, category: category).error("\(message, privacy: .public)") + #endif + let (handler, _) = store.get() + handler?(Entry(category: category, message: message, hasPrivateDetail: false)) + } + + /// Writes `prefix`, `detail` and `suffix` as one line. When + /// `detailIsPrivate` is set, the detail is private in the system log and + /// reaches the handler as `` unless it reveals private details. + package static func error( + category: String, + prefix: String, + detail: String, + detailIsPrivate: Bool, + suffix: String + ) { + guard detailIsPrivate else { + error(category: category, prefix + detail + suffix) + return + } + #if canImport(os) + Logger(subsystem: subsystem, category: category).error( + "\(prefix, privacy: .public)\(detail, privacy: .private)\(suffix, privacy: .public)" + ) + #endif + let (handler, reveals) = store.get() + handler?(Entry( + category: category, + message: prefix + (reveals ? detail : privatePlaceholder) + suffix, + hasPrivateDetail: true)) + } + + /// Writes `prefix`, the description of `error` and `suffix` as one line. + /// The description is public when the error's type is defined by this + /// SDK, whose errors carry counts, sizes, names it chose and redacted + /// provider text, and private otherwise, since an error thrown by caller + /// code, such as a custom transport or wallet, may hold whatever that + /// code put in it. + package static func error( + category: String, + prefix: String, + describing error: any Error, + suffix: String = "" + ) { + self.error( + category: category, + prefix: prefix, + detail: String(reflecting: error), + detailIsPrivate: !isSDKError(error), + suffix: suffix) + } + + /// Whether `error` is a type one of this SDK's modules defines. + package static func isSDKError(_ error: any Error) -> Bool { + let module = String(reflecting: type(of: error)).prefix { $0 != "." } + return sdkModules.contains(String(module)) + } + + private static let sdkModules: Set = [ + "BSV", "BSVAirGap", "BSVAuth", "BSVBigNum", "BSVCompat", "BSVCore", "BSVCrypto", + "BSVIdentity", "BSVInterpreter", "BSVKVStore", "BSVKeys", "BSVMessage", "BSVNetwork", + "BSVOverlay", "BSVRegistry", "BSVSPV", "BSVScript", "BSVStorage", "BSVTransaction", + "BSVWallet", + ] + + /// What a private detail reads as, as the system log shows it. + package static let privatePlaceholder = "" + + private static let store = HandlerStore() + + /// The installed handler, behind a lock so any thread can write lines + /// while a caller installs or removes one. The lock is held only to read + /// or replace the handler, never while it runs. + private final class HandlerStore: @unchecked Sendable { + private let lock = PlatformLock() + private var handler: Handler? + private var revealsPrivateDetails = false + + func set(_ handler: Handler?, revealingPrivateDetails: Bool) { + lock.withLock { + self.handler = handler + revealsPrivateDetails = handler != nil && revealingPrivateDetails + } + } + + func get() -> (Handler?, Bool) { + lock.withLock { (handler, revealsPrivateDetails) } + } + } +} + +/// A mutual-exclusion lock from the platform's C library, since BSVCore does +/// not import Foundation. +private final class PlatformLock: @unchecked Sendable { + #if os(Windows) + private let primitive: UnsafeMutablePointer + #else + private let primitive: UnsafeMutablePointer + #endif + + init() { + primitive = .allocate(capacity: 1) + #if os(Windows) + InitializeSRWLock(primitive) + #else + primitive.initialize(to: pthread_mutex_t()) + pthread_mutex_init(primitive, nil) + #endif + } + + deinit { + #if !os(Windows) + pthread_mutex_destroy(primitive) + #endif + primitive.deallocate() + } + + func withLock(_ body: () throws -> Result) rethrows -> Result { + #if os(Windows) + AcquireSRWLockExclusive(primitive) + defer { ReleaseSRWLockExclusive(primitive) } + #else + pthread_mutex_lock(primitive) + defer { pthread_mutex_unlock(primitive) } + #endif + return try body() + } +} diff --git a/Sources/BSVCore/Module.swift b/Sources/BSVCore/Module.swift index 77ee505..9e8bec1 100644 --- a/Sources/BSVCore/Module.swift +++ b/Sources/BSVCore/Module.swift @@ -1 +1 @@ -// BSVCore implementations are organized under Binary, Encoding, and Values. +// BSVCore implementations are organized under Binary, Encoding, Logging, Text, and Values. diff --git a/Sources/BSVCore/Text/LocaleCompareOrder.swift b/Sources/BSVCore/Text/LocaleCompareOrder.swift new file mode 100644 index 0000000..3d1e37c --- /dev/null +++ b/Sources/BSVCore/Text/LocaleCompareOrder.swift @@ -0,0 +1,239 @@ +/// The order `@bsv/sdk` sorts signed names in on an `en-US` host: JavaScript +/// `String.prototype.localeCompare` with no arguments, which Node and Bun +/// implement with ICU at tertiary strength, punctuation not ignored, in the +/// host's default locale. For `en-US`, and any other locale without a +/// collation tailoring, that is the ICU root collation, which this order +/// reproduces. +/// +/// The host locale matters. Bun always resolves `en-US`; Node takes the +/// default from `LC_ALL` or `LANG`, and `@bsv/sdk` itself calls the result a +/// host-locale order (`auth/certificates/Certificate.ts:287-290`). Under a +/// tailored locale, names sort differently even in plain ASCII: with +/// `LC_ALL=da_DK.UTF-8`, Node 22 sorts `email Email id ID aa z` as +/// `Email email ID id z aa` (capitals first, `aa` after `z`), and with +/// `cs_CZ`, `ch` sorts after `h`. Danish, Norwegian, Czech, Slovak, +/// Lithuanian, Estonian, Welsh and Azerbaijani tailor ASCII; Swedish, Polish, +/// Spanish, Turkish, Hungarian and Canadian French also tailor accented +/// letters. A name signed by TypeScript on such a host is in an order this +/// one does not give, and that another TypeScript host may not give either. +/// +/// TypeScript uses it for certificate field names in the BRC-52 binary form +/// and its signing preimage (`auth/certificates/Certificate.ts:290`) and for +/// signed BRC-104 header names (`auth/clients/AuthFetch.ts:740`, +/// `auth/transports/SimplifiedFetchTransport.ts:286`, +/// `auth-express-middleware/src/index.ts:2105`). +/// +/// Strings compare by primary weight first: whitespace, then punctuation and +/// symbols in ICU order, then digits, then letters with case and accents +/// ignored. Remaining ties are broken by accents (secondary weights), then by +/// case, lowercase first (tertiary weights). ICU ignores the C0 controls other +/// than tab, line feed, vertical tab, form feed and carriage return, and DEL; +/// so does this order. +/// +/// The order is exact for printable ASCII and for the 488 precomposed Latin +/// letters in U+00C0-U+024F and U+1E00-U+1EFF whose canonical decomposition is +/// an ASCII letter followed by combining diacritics, such as `é`, `Å`, `ñ`, +/// `ǖ` and `ự`; `isExact(_:)` tells whether a string uses only those. A +/// combining diacritic from that set written separately after a letter weighs +/// as it does inside a precomposed letter. +/// +/// Other characters are not collated as ICU collates them. C1 controls and the +/// default-ignorable format characters are ignored; every other scalar sorts +/// after all ASCII and Latin letters, in code point order. Names with such +/// characters can sort differently in TypeScript. Strings ICU treats as equal +/// are ordered by UTF-8 bytes, so the order is total; TypeScript keeps their +/// insertion order instead. +package enum LocaleCompareOrder { + /// `true` when `lhs` sorts before `rhs`. + package static func areInIncreasingOrder(_ lhs: String, _ rhs: String) -> Bool { + compare(lhs, rhs) < 0 + } + + /// A negative, zero or positive value, as `localeCompare` returns, with + /// collation ties broken by UTF-8 bytes. + package static func compare(_ lhs: String, _ rhs: String) -> Int { + let left = key(lhs) + let right = key(rhs) + if let order = compareSequences(left.primary, right.primary) { return order } + if let order = compareSequences(left.secondary, right.secondary) { return order } + if let order = compareSequences(left.tertiary, right.tertiary) { return order } + return compareSequences(Array(lhs.utf8), Array(rhs.utf8)) ?? 0 + } + + /// `true` when every scalar of `value` is printable ASCII (U+0020-U+007E) + /// or one of the precomposed Latin letters this order collates as ICU + /// does, so `localeCompare` sorts it exactly as this order does. + package static func isExact(_ value: String) -> Bool { + value.unicodeScalars.allSatisfy { scalar in + (0x20...0x7E).contains(scalar.value) || latinLetters[scalar.value] != nil + } + } + + /// The ASCII characters ICU does not ignore, in ICU root order, each + /// lowercase letter followed by its uppercase form. + package static let asciiOrder = + "\t\n\u{0B}\u{0C}\r _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$0123456789" + + "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ" + + /// The combining diacritics that occur in `latinLetters`, in ICU secondary + /// order: acute sorts first, macron below last. + private static let diacriticOrder: [UInt32] = [ + 0x0301, 0x0300, 0x0306, 0x0302, 0x030C, 0x030A, 0x0308, 0x030B, 0x0303, 0x0307, + 0x0327, 0x0328, 0x0304, 0x0309, 0x030F, 0x0311, 0x031B, 0x0323, 0x0324, 0x0325, + 0x0326, 0x032D, 0x032E, 0x0330, 0x0331, + ] + + /// The secondary weight of each diacritic, from 1; 0 is the weight of a + /// character with no diacritic. + private static let diacriticWeight: [UInt32: UInt8] = { + var table: [UInt32: UInt8] = [:] + for (index, scalar) in diacriticOrder.enumerated() { table[scalar] = UInt8(index + 1) } + return table + }() + + /// The primary weight of each ASCII scalar, or `nil` when ICU ignores it. + /// An uppercase letter shares the weight of its lowercase form. + private static let asciiPrimary: [UInt32?] = { + var table = [UInt32?](repeating: nil, count: 128) + var weight: UInt32 = 0 + for scalar in asciiOrder.unicodeScalars { + let code = Int(scalar.value) + if (65...90).contains(code) { + table[code] = table[code + 32] + } else { + weight += 1 + table[code] = weight + } + } + return table + }() + + /// A precomposed Latin letter: its ASCII base letter and the secondary + /// weights of its diacritics in canonical order. + private struct LatinLetter { + let base: UInt8 + let diacritics: [UInt8] + } + + /// Each entry is the code point in hex, the base letter, and one letter + /// per diacritic: `a` for the first in `diacriticOrder`, `b` for the + /// second, and so on. Generated from `String.prototype.normalize("NFD")` + /// and checked against `localeCompare` by `certorder-vec.ts` + /// (Documentation/Compatibility/TypeScriptAuthVectors.md). + private static let latinLetterTable = """ + 00C0Ab 00C1Aa 00C2Ad 00C3Ai 00C4Ag 00C5Af 00C7Ck 00C8Eb 00C9Ea 00CAEd + 00CBEg 00CCIb 00CDIa 00CEId 00CFIg 00D1Ni 00D2Ob 00D3Oa 00D4Od 00D5Oi + 00D6Og 00D9Ub 00DAUa 00DBUd 00DCUg 00DDYa 00E0ab 00E1aa 00E2ad 00E3ai + 00E4ag 00E5af 00E7ck 00E8eb 00E9ea 00EAed 00EBeg 00ECib 00EDia 00EEid + 00EFig 00F1ni 00F2ob 00F3oa 00F4od 00F5oi 00F6og 00F9ub 00FAua 00FBud + 00FCug 00FDya 00FFyg 0100Am 0101am 0102Ac 0103ac 0104Al 0105al 0106Ca + 0107ca 0108Cd 0109cd 010ACj 010Bcj 010CCe 010Dce 010EDe 010Fde 0112Em + 0113em 0114Ec 0115ec 0116Ej 0117ej 0118El 0119el 011AEe 011Bee 011CGd + 011Dgd 011EGc 011Fgc 0120Gj 0121gj 0122Gk 0123gk 0124Hd 0125hd 0128Ii + 0129ii 012AIm 012Bim 012CIc 012Dic 012EIl 012Fil 0130Ij 0134Jd 0135jd + 0136Kk 0137kk 0139La 013Ala 013BLk 013Clk 013DLe 013Ele 0143Na 0144na + 0145Nk 0146nk 0147Ne 0148ne 014COm 014Dom 014EOc 014Foc 0150Oh 0151oh + 0154Ra 0155ra 0156Rk 0157rk 0158Re 0159re 015ASa 015Bsa 015CSd 015Dsd + 015ESk 015Fsk 0160Se 0161se 0162Tk 0163tk 0164Te 0165te 0168Ui 0169ui + 016AUm 016Bum 016CUc 016Duc 016EUf 016Fuf 0170Uh 0171uh 0172Ul 0173ul + 0174Wd 0175wd 0176Yd 0177yd 0178Yg 0179Za 017Aza 017BZj 017Czj 017DZe + 017Eze 01A0Oq 01A1oq 01AFUq 01B0uq 01CDAe 01CEae 01CFIe 01D0ie 01D1Oe + 01D2oe 01D3Ue 01D4ue 01D5Ugm 01D6ugm 01D7Uga 01D8uga 01D9Uge 01DAuge 01DBUgb + 01DCugb 01DEAgm 01DFagm 01E0Ajm 01E1ajm 01E6Ge 01E7ge 01E8Ke 01E9ke 01EAOl + 01EBol 01ECOlm 01EDolm 01F0je 01F4Ga 01F5ga 01F8Nb 01F9nb 01FAAfa 01FBafa + 0200Ao 0201ao 0202Ap 0203ap 0204Eo 0205eo 0206Ep 0207ep 0208Io 0209io + 020AIp 020Bip 020COo 020Doo 020EOp 020Fop 0210Ro 0211ro 0212Rp 0213rp + 0214Uo 0215uo 0216Up 0217up 0218Su 0219su 021ATu 021Btu 021EHe 021Fhe + 0226Aj 0227aj 0228Ek 0229ek 022AOgm 022Bogm 022COim 022Doim 022EOj 022Foj + 0230Ojm 0231ojm 0232Ym 0233ym 1E00At 1E01at 1E02Bj 1E03bj 1E04Br 1E05br + 1E06By 1E07by 1E08Cka 1E09cka 1E0ADj 1E0Bdj 1E0CDr 1E0Ddr 1E0EDy 1E0Fdy + 1E10Dk 1E11dk 1E12Dv 1E13dv 1E14Emb 1E15emb 1E16Ema 1E17ema 1E18Ev 1E19ev + 1E1AEx 1E1Bex 1E1CEkc 1E1Dekc 1E1EFj 1E1Ffj 1E20Gm 1E21gm 1E22Hj 1E23hj + 1E24Hr 1E25hr 1E26Hg 1E27hg 1E28Hk 1E29hk 1E2AHw 1E2Bhw 1E2CIx 1E2Dix + 1E2EIga 1E2Figa 1E30Ka 1E31ka 1E32Kr 1E33kr 1E34Ky 1E35ky 1E36Lr 1E37lr + 1E38Lrm 1E39lrm 1E3ALy 1E3Bly 1E3CLv 1E3Dlv 1E3EMa 1E3Fma 1E40Mj 1E41mj + 1E42Mr 1E43mr 1E44Nj 1E45nj 1E46Nr 1E47nr 1E48Ny 1E49ny 1E4ANv 1E4Bnv + 1E4COia 1E4Doia 1E4EOig 1E4Foig 1E50Omb 1E51omb 1E52Oma 1E53oma 1E54Pa 1E55pa + 1E56Pj 1E57pj 1E58Rj 1E59rj 1E5ARr 1E5Brr 1E5CRrm 1E5Drrm 1E5ERy 1E5Fry + 1E60Sj 1E61sj 1E62Sr 1E63sr 1E64Saj 1E65saj 1E66Sej 1E67sej 1E68Srj 1E69srj + 1E6ATj 1E6Btj 1E6CTr 1E6Dtr 1E6ETy 1E6Fty 1E70Tv 1E71tv 1E72Us 1E73us + 1E74Ux 1E75ux 1E76Uv 1E77uv 1E78Uia 1E79uia 1E7AUmg 1E7Bumg 1E7CVi 1E7Dvi + 1E7EVr 1E7Fvr 1E80Wb 1E81wb 1E82Wa 1E83wa 1E84Wg 1E85wg 1E86Wj 1E87wj + 1E88Wr 1E89wr 1E8AXj 1E8Bxj 1E8CXg 1E8Dxg 1E8EYj 1E8Fyj 1E90Zd 1E91zd + 1E92Zr 1E93zr 1E94Zy 1E95zy 1E96hy 1E97tg 1E98wf 1E99yf 1EA0Ar 1EA1ar + 1EA2An 1EA3an 1EA4Ada 1EA5ada 1EA6Adb 1EA7adb 1EA8Adn 1EA9adn 1EAAAdi 1EABadi + 1EACArd 1EADard 1EAEAca 1EAFaca 1EB0Acb 1EB1acb 1EB2Acn 1EB3acn 1EB4Aci 1EB5aci + 1EB6Arc 1EB7arc 1EB8Er 1EB9er 1EBAEn 1EBBen 1EBCEi 1EBDei 1EBEEda 1EBFeda + 1EC0Edb 1EC1edb 1EC2Edn 1EC3edn 1EC4Edi 1EC5edi 1EC6Erd 1EC7erd 1EC8In 1EC9in + 1ECAIr 1ECBir 1ECCOr 1ECDor 1ECEOn 1ECFon 1ED0Oda 1ED1oda 1ED2Odb 1ED3odb + 1ED4Odn 1ED5odn 1ED6Odi 1ED7odi 1ED8Ord 1ED9ord 1EDAOqa 1EDBoqa 1EDCOqb 1EDDoqb + 1EDEOqn 1EDFoqn 1EE0Oqi 1EE1oqi 1EE2Oqr 1EE3oqr 1EE4Ur 1EE5ur 1EE6Un 1EE7un + 1EE8Uqa 1EE9uqa 1EEAUqb 1EEBuqb 1EECUqn 1EEDuqn 1EEEUqi 1EEFuqi 1EF0Uqr 1EF1uqr + 1EF2Yb 1EF3yb 1EF4Yr 1EF5yr 1EF6Yn 1EF7yn 1EF8Yi 1EF9yi + """ + + private static let latinLetters: [UInt32: LatinLetter] = { + var table: [UInt32: LatinLetter] = [:] + for entry in latinLetterTable.split(whereSeparator: { $0 == " " || $0 == "\n" }) { + let bytes = Array(entry.utf8) + guard bytes.count >= 6, + let code = UInt32(String(decoding: bytes[0..<4], as: UTF8.self), radix: 16) + else { preconditionFailure("malformed Latin letter table entry") } + table[code] = LatinLetter( + base: bytes[4], + diacritics: bytes[5...].map { $0 - UInt8(ascii: "a") + 1 } + ) + } + return table + }() + + private struct Key { + var primary: [UInt32] = [] + var secondary: [UInt8] = [] + var tertiary: [UInt8] = [] + + mutating func appendASCII(_ code: UInt32) { + guard let primary = asciiPrimary[Int(code)] else { return } + self.primary.append(primary) + secondary.append(0) + tertiary.append((65...90).contains(code) ? 1 : 0) + } + } + + private static func key(_ value: String) -> Key { + var result = Key() + for scalar in value.unicodeScalars { + let code = scalar.value + if code < 128 { + result.appendASCII(code) + } else if let letter = latinLetters[code] { + result.appendASCII(UInt32(letter.base)) + result.secondary += letter.diacritics + } else if let weight = diacriticWeight[code] { + // A diacritic has no primary weight; it only adds a secondary one. + result.secondary.append(weight) + } else if !ignorable(code) { + result.primary.append(1_000 + code) + result.secondary.append(0) + result.tertiary.append(0) + } + } + return result + } + + private static func ignorable(_ code: UInt32) -> Bool { + switch code { + case 0x80...0x9F, 0xAD, 0x200B...0x200F, 0x2060...0x2064, 0xFEFF: return true + default: return false + } + } + + private static func compareSequences( + _ lhs: [Element], _ rhs: [Element] + ) -> Int? { + for (left, right) in zip(lhs, rhs) where left != right { + return left < right ? -1 : 1 + } + return lhs.count == rhs.count ? nil : (lhs.count < rhs.count ? -1 : 1) + } +} diff --git a/Sources/BSVNetwork/HTTP/NetworkLog.swift b/Sources/BSVNetwork/HTTP/NetworkLog.swift index f6e9b82..22da79f 100644 --- a/Sources/BSVNetwork/HTTP/NetworkLog.swift +++ b/Sources/BSVNetwork/HTTP/NetworkLog.swift @@ -1,21 +1,20 @@ +import BSVCore import Foundation -#if canImport(os) -import os -#endif -/// The network log: subsystem `dev.opl.swift-sdk`, category `BSVNetwork`. +/// The network log: `BSVLog` category `BSVNetwork`, written to `os.Logger` on +/// Apple platforms and to the caller's `BSVLog` handler on every platform. /// /// A line names the call, the method, and the host and path. It never holds a query string, /// a request header or a request body, because those can carry API keys and callback tokens. /// Provider bodies go through `sanitizedProviderText` first, with the caller's secrets redacted. +/// The description of an error thrown by caller code, such as a custom `HTTPTransport`, is +/// private: `` to a `BSVLog` handler unless it reveals private details. package enum NetworkLog { - package static let subsystem = "dev.opl.swift-sdk" + package static let subsystem = BSVLog.subsystem package static let category = "BSVNetwork" package static func error(_ message: String) { - #if canImport(os) - Logger(subsystem: subsystem, category: category).error("\(message, privacy: .public)") - #endif + BSVLog.error(category: category, message) } /// A response that arrived but could not be used: its status, the reason and the body. @@ -38,15 +37,20 @@ package enum NetworkLog { } /// A request that got no usable response: the underlying error and its type. + /// + /// The error's description is private unless this SDK defines its type: + /// a caller's `HTTPTransport` may put a URL with its query, a header or a + /// body in its errors. package static func failure( _ operation: String, request: HTTPRequest, underlying: any Error ) { - error( - "\(operation): \(request.method.rawValue) \(location(request.url)) failed: " - + "\(type(of: underlying)): \(String(reflecting: underlying))" - ) + BSVLog.error( + category: category, + prefix: "\(operation): \(request.method.rawValue) \(location(request.url)) failed: " + + "\(type(of: underlying)): ", + describing: underlying) } package static func line( diff --git a/Sources/BSVOverlay/OverlayLog.swift b/Sources/BSVOverlay/OverlayLog.swift index e2f4c0c..49873d8 100644 --- a/Sources/BSVOverlay/OverlayLog.swift +++ b/Sources/BSVOverlay/OverlayLog.swift @@ -1,39 +1,40 @@ +import BSVCore import Foundation -#if canImport(os) -import os -#endif - -/// The overlay policy log: subsystem `dev.opl.swift-sdk`, category `BSVOverlay`. +/// The overlay policy log: `BSVLog` 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 +/// limit. Errors are logged with their type; the description of one this +/// SDK defines is public, and of any other, such as an error thrown by a +/// caller's facilitator, private, as in `AuthLog`. 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" +/// Like `NetworkLog`, it writes to `os.Logger` on Apple platforms and to the +/// caller's `BSVLog` handler on every platform, Linux included. +package enum OverlayLog { + package static let subsystem = BSVLog.subsystem + package 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))" - ) + package static func hostFailure(_ operation: String, _ failure: OverlayHostFailure) { + BSVLog.error( + category: category, + prefix: "\(operation): host \(location(failure.host)) failed: " + + "\(type(of: failure.error)): ", + describing: failure.error) } - static func rejectedOutput(_ operation: String, _ rejection: LookupOutputRejection) { - error( - "\(operation): output \(rejection.output.outputIndex) from host " + package static func rejectedOutput(_ operation: String, _ rejection: LookupOutputRejection) { + BSVLog.error( + category: category, + prefix: "\(operation): output \(rejection.output.outputIndex) from host " + "\(location(rejection.host)) left out: " - + "\(type(of: rejection.error)): \(String(reflecting: rejection.error))" - ) + + "\(type(of: rejection.error)): ", + describing: rejection.error) } static func skippedAdvertisement(_ operation: String, output: OutputListItem, reason: String) { @@ -58,9 +59,7 @@ enum OverlayLog { return "\(scheme)://\(name)\(port)" } - private static func error(_ message: String) { - #if canImport(os) - Logger(subsystem: subsystem, category: category).error("\(message, privacy: .public)") - #endif + package static func error(_ message: String) { + BSVLog.error(category: category, message) } } diff --git a/Sources/BSVWallet/ABI/WalletABI.swift b/Sources/BSVWallet/ABI/WalletABI.swift index b91ac57..e5ebbc1 100644 --- a/Sources/BSVWallet/ABI/WalletABI.swift +++ b/Sources/BSVWallet/ABI/WalletABI.swift @@ -7,13 +7,18 @@ public struct WalletABILimits: Hashable, Sendable { public static let maximumProtocolPageSize: UInt32 = 10_000 public static let defaultPageSize: UInt32 = 10 + /// The default bound on the bytes one ABI value carries in all its + /// payloads: `WalletWireLimits.defaultFrameByteCount`, so a value as large + /// as a wallet-wire frame can hold is accepted. + public static let defaultAggregatePayloadByteCount = WalletWireLimits.defaultFrameByteCount + public static let standard = WalletABILimits( validatedText: 2_000, collection: 10_000, tags: 1_000, labels: 1_000, payload: 8_388_608, - aggregate: 16_777_216 + aggregate: defaultAggregatePayloadByteCount ) public let maximumTextUTF8ByteCount: Int @@ -29,7 +34,7 @@ public struct WalletABILimits: Hashable, Sendable { maximumTagCount: Int = 1_000, maximumLabelCount: Int = 1_000, maximumBytePayloadCount: Int = 8_388_608, - maximumAggregatePayloadByteCount: Int = 16_777_216 + maximumAggregatePayloadByteCount: Int = WalletABILimits.defaultAggregatePayloadByteCount ) throws { let values = [ maximumTextUTF8ByteCount, maximumCollectionCount, maximumTagCount, diff --git a/Sources/BSVWallet/ABI/WalletActionABI.swift b/Sources/BSVWallet/ABI/WalletActionABI.swift index b885776..c3ad863 100644 --- a/Sources/BSVWallet/ABI/WalletActionABI.swift +++ b/Sources/BSVWallet/ABI/WalletActionABI.swift @@ -859,10 +859,49 @@ public struct WalletInternalizeActionResult: Equatable, Sendable { /// True for a BRC-112 balance basket, `balance ` or `p balance `. /// Its `listOutputs` total is a balance, not an output count, and has no records. +/// +/// The basket is tested after the normalisation `@bsv/sdk` 4.1.1 applies to +/// it, `validateIdentifier`'s `trim().toLowerCase()` +/// (`wallet/validationHelpers.ts:376-418`, `validateListOutputsArgs` at +/// `:1652`), against the pattern of `wallet/moduleBalanceQuery.ts:1`. The +/// wallet toolbox decides a balance query on that normalised basket +/// (`wallet-toolbox/src/Wallet.ts`, `validateListOutputsArgs`), so +/// `" Balance Tickets"` is a balance query there and here. The TypeScript +/// wire codecs test the raw basket instead (`WalletWireProcessor.ts:1296`, +/// `WalletWireTransceiver.ts:726`). +/// +/// The pattern is matched on UTF-8 bytes, as the JavaScript regular +/// expression matches code units, so a space followed by a combining mark is +/// still a space. public func walletIsBalanceBasket(_ basket: String) -> Bool { - if basket.hasPrefix("balance ") { return true } - guard basket.hasPrefix("p ") else { return false } - let rest = basket.dropFirst(2) - guard let space = rest.firstIndex(of: " "), space != rest.startIndex else { return false } - return rest[rest.index(after: space)...].hasPrefix("balance ") + let bytes = Array(walletNormalizedIdentifier(basket).utf8) + let balance = Array("balance ".utf8) + if bytes.starts(with: balance) { return true } + guard bytes.starts(with: Array("p ".utf8)) else { return false } + let rest = bytes.dropFirst(2) + // `[^ ]+`: UTF-8 never encodes another scalar with a 0x20 byte. + guard let space = rest.firstIndex(of: 0x20), space != rest.startIndex else { return false } + return rest[(space + 1)...].starts(with: balance) +} + +/// A basket, label or tag as `@bsv/sdk` `validateIdentifier` normalises it: +/// JavaScript `String.prototype.trim` (ECMAScript white space and line +/// terminators) and then Unicode lowercasing. +package func walletNormalizedIdentifier(_ value: String) -> String { + let scalars = value.unicodeScalars + guard let first = scalars.firstIndex(where: { !walletIsJavaScriptWhitespace($0) }), + let last = scalars.lastIndex(where: { !walletIsJavaScriptWhitespace($0) }) + else { return "" } + return String(scalars[first...last]).lowercased() +} + +/// ECMAScript `WhiteSpace` and `LineTerminator`, what `trim` removes. +private func walletIsJavaScriptWhitespace(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.value { + case 0x09...0x0D, 0x20, 0xA0, 0x1680, 0x2000...0x200A, 0x2028, 0x2029, 0x202F, 0x205F, + 0x3000, 0xFEFF: + return true + default: + return false + } } diff --git a/Sources/BSVWallet/Certificates/CertificateBinary.swift b/Sources/BSVWallet/Certificates/CertificateBinary.swift index bc40b93..faabc9e 100644 --- a/Sources/BSVWallet/Certificates/CertificateBinary.swift +++ b/Sources/BSVWallet/Certificates/CertificateBinary.swift @@ -2,18 +2,56 @@ import BSVCore import BSVKeys import BSVTransaction +/// The order of the field records in a BRC-52 certificate binary. +package enum CertificateFieldOrder: Sendable { + /// JavaScript `localeCompare` order, as `@bsv/sdk` writes and signs + /// (`auth/certificates/Certificate.ts:290`). + case localeCompare + /// Raw UTF-8 byte order, as the Go SDK and earlier releases of this SDK + /// write and sign. + case utf8Bytes + /// The order the records arrived in, for a certificate read with + /// `init(binary:)`; another certificate has none, and is refused. + case received +} + extension Certificate { - /// Canonical BRC-52 binary form. The revocation transaction ID is written in - /// human-display byte order, matching BRC-52 and the pinned Go v1.3.3 SDK. + /// The BRC-52 binary form, as `@bsv/sdk` 4.1.1 `Certificate.toBinary` + /// writes it. The revocation transaction ID is written in human-display + /// byte order, matching BRC-52, `@bsv/sdk` and the pinned Go v1.3.3 SDK. + /// + /// Fields are written in JavaScript `localeCompare` order of their names + /// (`auth/certificates/Certificate.ts:290`), the order TypeScript signs and + /// verifies. It differs from UTF-8 byte order when names differ in case, + /// accents, digits or punctuation: `_id, a_1, a1, email, Email, émile, id, + /// ID, Zip` against `Email, ID, Zip, _id, a1, a_1, email, id, émile`. The + /// order is exact for names of printable ASCII and accented Latin letters + /// (COMP-041). public func binary( includingSignature: Bool, limits: CertificateLimits = .standard + ) throws -> [UInt8] { + try binary(includingSignature: includingSignature, limits: limits, fieldOrder: .localeCompare) + } + + /// The BRC-52 binary form with the field records in `fieldOrder`. + package func binary( + includingSignature: Bool, + limits: CertificateLimits, + fieldOrder: CertificateFieldOrder ) throws -> [UInt8] { if includingSignature && signature == nil { throw CertificateError.missingSignature } guard fields.count <= limits.maximumFieldCount else { throw CertificateError.tooManyFields(actual: fields.count, maximum: limits.maximumFieldCount) } - let names = fields.keys.sorted() + let names = switch fieldOrder { + case .localeCompare: + fields.keys.sorted { LocaleCompareOrder.areInIncreasingOrder($0.value, $1.value) } + case .utf8Bytes: + fields.keys.sorted() + case .received: + try receivedNames() + } var total = 162 try certificateCheckedAdd(CompactSize.encodedLength(of: UInt64(revocationOutpoint.outputIndex)), to: &total) try certificateCheckedAdd(CompactSize.encodedLength(of: UInt64(names.count)), to: &total) @@ -61,12 +99,23 @@ extension Certificate { return writer.bytes } + /// `receivedFieldOrder`, checked to name each field exactly once. + private func receivedNames() throws -> [CertificateFieldName] { + guard let names = receivedFieldOrder, names.count == fields.count, + Set(names) == Set(fields.keys) + else { throw CertificateError.fieldNotFound } + return names + } + /// Parses one complete canonical BRC-52 binary certificate. /// /// Fields may arrive in any order: `@bsv/sdk` 4.1.1 writes them sorted with - /// `localeCompare` (auth/certificates/Certificate.ts:290), which differs from - /// raw byte order when names differ in case, digits or punctuation (for - /// example `cardholder` before `cardNumber`). Swift still writes byte order. + /// `localeCompare` (auth/certificates/Certificate.ts:290), as `binary` + /// does, and the Go SDK writes them in raw byte order. The two differ when + /// names differ in case, accents, digits or punctuation (for example + /// `cardholder` before `cardNumber`). The order they arrived in is kept for + /// `verifySignature`, which also checks the signature over it; `binary` + /// still writes `localeCompare` order. /// /// Unlike the pinned Go decoder, this rejects nonminimal CompactSize values, /// duplicate names, high-width vouts, noncanonical Base64, noncanonical DER, @@ -90,6 +139,7 @@ extension Certificate { throw CertificateError.tooManyFields(actual: Int(clamping: fieldCount), maximum: limits.maximumFieldCount) } var fields: [CertificateFieldName: CertificateCiphertext] = [:] + var order: [CertificateFieldName] = [] var seenNames = Set<[UInt8]>() for _ in 0.. Certificate { guard signature == nil else { throw CertificateError.alreadySigned } + if let name = Self.fieldNameWithoutExactOrder(in: fields.keys) { + WalletLog.error( + "Certificate signing: a field name of \(name.utf8Bytes.count) bytes has a character " + + "whose localeCompare order is not reproduced; reported as " + + String(reflecting: CertificateFieldNameError.unsupportedCharacter)) + throw CertificateFieldNameError.unsupportedCharacter + } let preimage = try binary(includingSignature: false, limits: limits) let identity = try await wallet.getPublicKey(.init(selection: .identity)).publicKey guard identity == certifier else { throw CertificateError.walletIdentityMismatch } @@ -56,12 +84,74 @@ extension Certificate { /// as counterparty. This does not establish trust or check revocation status; /// chain-aware callers must perform those policy checks separately. High-S /// signatures return `false` under Swift's strict non-malleability policy. + /// + /// The signature is checked over the fields in each order a signer may have + /// used, as long as the orders differ: + /// + /// 1. JavaScript `localeCompare` order on an `en-US` host, as `@bsv/sdk` + /// 4.1.1 `Certificate.verify` checks it + /// (`auth/certificates/Certificate.ts:437-458`); + /// 2. raw UTF-8 byte order, which the Go SDK and earlier releases of this + /// SDK sign; + /// 3. for a certificate read with `init(binary:)`, the order its fields + /// arrived in, which is the order its signer wrote and signed. + /// + /// The preimage is length-prefixed, so each order commits to the same + /// field names and values; only their order differs. The third covers + /// names this SDK cannot order as `localeCompare` does, such as `ß`, + /// Cyrillic or CJK, and TypeScript hosts with a tailored collation such as + /// Danish. A certificate with such names read from JSON has no received + /// order, so it verifies only when one of the first two orders matches. + /// + /// A match by the second or third order, and a failure where a name is + /// outside the characters `localeCompare` order is reproduced for, are + /// written to the `BSVWallet` log with the field count and name length, + /// never a field name or value. public func verifySignature( limits: CertificateLimits = .standard ) async throws -> Bool { - guard let signature else { throw CertificateError.missingSignature } + guard signature != nil else { throw CertificateError.missingSignature } _ = try binary(includingSignature: true, limits: limits) - let preimage = try binary(includingSignature: false, limits: limits) + let localeOrder = try binary(includingSignature: false, limits: limits) + if try await verifySignature(over: localeOrder) { return true } + var tried = [localeOrder] + + let byteOrder = try binary( + includingSignature: false, limits: limits, fieldOrder: .utf8Bytes) + if !tried.contains(byteOrder) { + if try await verifySignature(over: byteOrder) { + WalletLog.error( + "Certificate verification: the signature covers its \(fields.count) fields in " + + "UTF-8 byte order, as the Go SDK signs, not in localeCompare order") + return true + } + tried.append(byteOrder) + } + + if receivedFieldOrder != nil { + let received = try binary( + includingSignature: false, limits: limits, fieldOrder: .received) + if !tried.contains(received), try await verifySignature(over: received) { + WalletLog.error( + "Certificate verification: the signature covers its \(fields.count) fields in " + + "the order they were received, which is neither localeCompare order on an " + + "en-US host nor UTF-8 byte order") + return true + } + } + + if let name = Self.fieldNameWithoutExactOrder(in: fields.keys) { + WalletLog.error( + "Certificate verification: the signature did not verify; a field name of " + + "\(name.utf8Bytes.count) bytes has a character whose localeCompare order is not " + + "reproduced, so a certificate signed in TypeScript verifies only when read from " + + "its binary form") + } + return false + } + + private func verifySignature(over preimage: [UInt8]) async throws -> Bool { + guard let signature else { throw CertificateError.missingSignature } let verifier = try ProtoWallet.anyone() return try await verifier.verifySignature(.init( protocolID: try CertificateProtocols.signature, @@ -71,4 +161,38 @@ extension Certificate { signature: signature )).valid } + + /// The first name, if any, with a character whose `localeCompare` order + /// this SDK does not reproduce exactly: anything but printable ASCII and + /// the precomposed accented Latin letters `LocaleCompareOrder` covers. + /// With fewer than two names there is only one order, so none is returned. + package static func fieldNameWithoutExactOrder( + in names: some Collection + ) -> CertificateFieldName? { + guard names.count > 1 else { return nil } + return names.first { !LocaleCompareOrder.isExact($0.value) } + } +} + +/// A certificate field name this SDK will not sign. +/// +/// `@bsv/sdk` orders signed field names with `localeCompare`, which on an +/// `en-US` host is the ICU root collation. `LocaleCompareOrder` reproduces it +/// exactly for printable ASCII and precomposed accented Latin letters such as +/// `é` and `Å`, so when a certificate has two fields or more, +/// `Certificate.signed` and `CertificateEngine.issue` refuse other names, +/// including control characters, decomposed accents and other scripts, rather +/// than sign a certificate TypeScript may not verify. Certificates with such +/// names signed elsewhere still verify when read from their binary form +/// (COMP-041). +public enum CertificateFieldNameError: Error, Equatable, Sendable, LocalizedError { + case unsupportedCharacter + + public var errorDescription: String? { + switch self { + case .unsupportedCharacter: + "Certificate field names must use only plain ASCII letters, digits, spaces and " + + "symbols, and accented Latin letters." + } + } } diff --git a/Sources/BSVWallet/Certificates/CertificateValues.swift b/Sources/BSVWallet/Certificates/CertificateValues.swift index 5a3c1ac..1f445ca 100644 --- a/Sources/BSVWallet/Certificates/CertificateValues.swift +++ b/Sources/BSVWallet/Certificates/CertificateValues.swift @@ -210,6 +210,8 @@ public struct CertificateFieldName: Hashable, Codable, Sendable, Comparable { private static let maximumProtocolUTF8ByteCount = CertificateLimits.maximumProtocolFieldNameUTF8ByteCount + /// Raw UTF-8 byte order. This is not the order `Certificate.binary` + /// writes and signs fields in, which is JavaScript `localeCompare` order. public static func < (lhs: Self, rhs: Self) -> Bool { lhs.utf8Bytes.lexicographicallyPrecedes(rhs.utf8Bytes) } @@ -274,6 +276,11 @@ public struct Certificate: public let fields: [CertificateFieldName: CertificateCiphertext] public let signature: ECDSASignature? + /// The order the field records arrived in, for a certificate read with + /// `init(binary:)`: the order its signer wrote and signed. It is not part + /// of the certificate's value, so `==` ignores it. + package var receivedFieldOrder: [CertificateFieldName]? + public init( type: CertificateTypeID, serialNumber: CertificateSerialNumber, @@ -304,6 +311,16 @@ public struct Certificate: self.revocationOutpoint = revocationOutpoint self.fields = fields self.signature = signature + self.receivedFieldOrder = nil + } + + /// Equal when every member is equal; the order the fields arrived in is + /// not compared. + public static func == (lhs: Certificate, rhs: Certificate) -> Bool { + lhs.type == rhs.type && lhs.serialNumber == rhs.serialNumber + && lhs.subject == rhs.subject && lhs.certifier == rhs.certifier + && lhs.revocationOutpoint == rhs.revocationOutpoint && lhs.fields == rhs.fields + && lhs.signature == rhs.signature } public var signatureKeyID: String { type.base64 + " " + serialNumber.base64 } @@ -318,11 +335,13 @@ public struct Certificate: limits: CertificateLimits = .standard ) throws -> Certificate { guard self.signature == nil else { throw CertificateError.alreadySigned } - return try Certificate( + var signed = try Certificate( type: type, serialNumber: serialNumber, subject: subject, certifier: certifier, revocationOutpoint: revocationOutpoint, fields: fields, signature: signature, limits: limits ) + signed.receivedFieldOrder = receivedFieldOrder + return signed } private enum CodingKeys: String, CodingKey { diff --git a/Sources/BSVWallet/Substrates/WalletLog.swift b/Sources/BSVWallet/Substrates/WalletLog.swift index df30d2e..eb22b48 100644 --- a/Sources/BSVWallet/Substrates/WalletLog.swift +++ b/Sources/BSVWallet/Substrates/WalletLog.swift @@ -1,22 +1,19 @@ +import BSVCore import Foundation -#if canImport(os) -import os -#endif -/// The wallet log: subsystem `dev.opl.swift-sdk`, category `BSVWallet`. +/// The wallet log: `BSVLog` category `BSVWallet`, written to `os.Logger` on +/// Apple platforms and to the caller's `BSVLog` handler on every platform. /// /// A wire processor answers a peer with a short, fixed text. The full reason goes here, /// so the host app can see that a peer sent a frame it could not read, or that its own /// wallet returned a result the wire cannot carry. A line names the call and the error's /// type and value. It never holds frame bytes, because those can carry keys and payloads. package enum WalletLog { - package static let subsystem = "dev.opl.swift-sdk" + package static let subsystem = BSVLog.subsystem package static let category = "BSVWallet" package static func error(_ message: String) { - #if canImport(os) - Logger(subsystem: subsystem, category: category).error("\(message, privacy: .public)") - #endif + BSVLog.error(category: category, message) } /// A failure answered in-band: what was being done, the call, and the underlying error. diff --git a/Sources/BSVWallet/Wire/WalletWireTypes.swift b/Sources/BSVWallet/Wire/WalletWireTypes.swift index 9a9a0ab..b29b9c7 100644 --- a/Sources/BSVWallet/Wire/WalletWireTypes.swift +++ b/Sources/BSVWallet/Wire/WalletWireTypes.swift @@ -5,10 +5,25 @@ import BSVKeys public struct WalletWireLimits: Hashable, Sendable { public static let hardMaximumOriginatorUTF8ByteCount = 255 + /// Room a frame leaves beyond its largest payload, 64 KiB: the call byte, + /// the originator, protocol ID, key ID, counterparty, privileged reason, + /// CompactSize lengths, flags, a signature, and the 48 bytes an encrypt + /// result adds to its plaintext. Together they come to under 3 KiB. + public static let frameOverheadByteCount = 64 << 10 + + /// The default frame bound: `WalletCryptoLimits.defaultPayloadByteCount` + /// (16 MiB plus 512 KiB) plus `frameOverheadByteCount`, so a wallet + /// reached over the wire signs, verifies, HMACs, encrypts and decrypts + /// every payload its own cryptography and BSVAuth accept by default. + /// It is also the default bound on a frame's call parameters or result + /// payload, `maximumPayloadByteCount`. + public static let defaultFrameByteCount = + WalletCryptoLimits.defaultPayloadByteCount + frameOverheadByteCount + public static let standard = WalletWireLimits( - validatedFrame: 16_777_216, + validatedFrame: defaultFrameByteCount, originator: 255, - payload: 8_388_608, + payload: defaultFrameByteCount, text: 2_000, remoteMessage: 4_096, remoteStack: 8_192, @@ -26,9 +41,9 @@ public struct WalletWireLimits: Hashable, Sendable { public let cryptoLimits: WalletCryptoLimits public init( - maximumFrameByteCount: Int = 16_777_216, + maximumFrameByteCount: Int = WalletWireLimits.defaultFrameByteCount, maximumOriginatorUTF8ByteCount: Int = 255, - maximumPayloadByteCount: Int = 8_388_608, + maximumPayloadByteCount: Int = WalletWireLimits.defaultFrameByteCount, maximumTextUTF8ByteCount: Int = 2_000, maximumRemoteMessageUTF8ByteCount: Int = 4_096, maximumRemoteStackUTF8ByteCount: Int = 8_192, diff --git a/Tests/BSVAuthTests/BRC104/BRC104ErrorDescriptionTests.swift b/Tests/BSVAuthTests/BRC104/BRC104ErrorDescriptionTests.swift index d4f262a..86456c9 100644 --- a/Tests/BSVAuthTests/BRC104/BRC104ErrorDescriptionTests.swift +++ b/Tests/BSVAuthTests/BRC104/BRC104ErrorDescriptionTests.swift @@ -1,4 +1,5 @@ import BSVAuth +import BSVWallet import Foundation import Testing @@ -61,7 +62,8 @@ struct BRC104ErrorDescriptionTests { AuthError.notAuthenticated.localizedDescription == "The connection has not been authenticated yet.") #expect( - CertificateFieldNameError.nonASCII.localizedDescription - == "Certificate field names must use only plain ASCII letters, digits, spaces and symbols.") + CertificateFieldNameError.unsupportedCharacter.localizedDescription + == "Certificate field names must use only plain ASCII letters, digits, spaces and " + + "symbols, and accented Latin letters.") } } diff --git a/Tests/BSVAuthTests/Certificates/CertificateFieldOrderTests.swift b/Tests/BSVAuthTests/Certificates/CertificateFieldOrderTests.swift new file mode 100644 index 0000000..6da7614 --- /dev/null +++ b/Tests/BSVAuthTests/Certificates/CertificateFieldOrderTests.swift @@ -0,0 +1,147 @@ +import BSVAuth +import BSVCore +import BSVCrypto +import BSVKeys +import BSVWallet +import Foundation +import Testing + +@Suite("BRC-52 certificate field order") +struct CertificateFieldOrderTests { + @Test("a TS-signed certificate with mixed-case fields verifies") + func typeScriptMixedCaseCertificate() async throws { + let certificate = try Certificate(json: Array(TypeScriptAuthVectors.mixedCaseCertificate.utf8)) + #expect( + Hex.encode(try certificate.binary(includingSignature: false)) + == TypeScriptAuthVectors.mixedCaseCertificatePreimage) + #expect(try await certificate.verifySignature()) + #expect(try await verifies(certificate, over: certificate.binary(includingSignature: false))) + + // Signing the same unsigned certificate gives TypeScript's RFC 6979 signature. + let unsigned = try unsignedCopy(of: certificate) + let resigned = try await unsigned.signed(using: ProtoWallet(rootKey: try key(11))) + #expect(resigned.signature == certificate.signature) + } + + @Test("issued certificates are signed in localeCompare order") + func issuedMixedCaseCertificate() async throws { + let master = try await CertificateEngine.issue( + type: try CertificateTypeID([UInt8](repeating: 0x21, count: 32)), + subject: .publicKey(try key(7).publicKey), + plaintextFields: [ + try CertificateFieldName("Zip"): "90210", try CertificateFieldName("age"): "30", + try CertificateFieldName("a_b"): "1", try CertificateFieldName("a-b"): "2", + try CertificateFieldName("été"): "summer", try CertificateFieldName("Ete"): "x", + ], + using: ProtoWallet(rootKey: try key(11))) + let certificate = master.certificate + let localeOrder = try certificate.binary(includingSignature: false) + let byteOrder = try certificate.binary( + includingSignature: false, limits: .standard, fieldOrder: .utf8Bytes) + #expect(localeOrder != byteOrder) + #expect(try await verifies(certificate, over: localeOrder)) + #expect(try await verifies(certificate, over: byteOrder) == false) + #expect(try await certificate.verifySignature()) + } + + @Test("names whose localeCompare order is not reproduced are refused at issue") + func unreproducibleFieldNames() async throws { + // ICU root collation is emulated for ASCII and accented Latin letters + // only (COMP-041), so a certificate whose TS signature order could not + // be predicted is not issued. + let fields = [ + try CertificateFieldName("øre"): "krone", try CertificateFieldName("age"): "30", + ] + let log = AuthLogLines() + let error = await log.record { + await #expect(throws: CertificateFieldNameError.unsupportedCharacter) { + try await CertificateEngine.issue( + type: try CertificateTypeID([UInt8](repeating: 0x24, count: 32)), + subject: .publicKey(try key(7).publicKey), + plaintextFields: fields, + using: ProtoWallet(rootKey: try key(11))) + } + } + #expect( + error?.localizedDescription + == "Certificate field names must use only plain ASCII letters, digits, spaces and " + + "symbols, and accented Latin letters.") + #expect(log.lines.contains { $0.contains("Certificate issue: a field name of 4 bytes") }) + } + + @Test("a single field is issued whatever its name") + func singleFieldIssue() async throws { + let master = try await CertificateEngine.issue( + type: try CertificateTypeID([UInt8](repeating: 0x25, count: 32)), + subject: .publicKey(try key(7).publicKey), + plaintextFields: [try CertificateFieldName("øre"): "krone"], + using: ProtoWallet(rootKey: try key(11))) + #expect(master.certificate.fields.keys.map(\.value) == ["øre"]) + #expect(try await master.certificate.verifySignature()) + } + + @Test("certificates signed in byte order still verify through the engine") + func byteOrderSignatureStillVerifies() async throws { + let unsigned = try Certificate( + type: try CertificateTypeID([UInt8](repeating: 0x22, count: 32)), + serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x23, count: 32)), + subject: try key(7).publicKey, + certifier: try key(11).publicKey, + revocationOutpoint: CertificateEngine.disabledRevocationOutpoint, + fields: [ + try CertificateFieldName("Zip"): try CertificateCiphertext([1]), + try CertificateFieldName("age"): try CertificateCiphertext([2]), + ]) + // The Go SDK and earlier releases of this SDK sign UTF-8 byte order. + let byteOrder = try unsigned.binary( + includingSignature: false, limits: .standard, fieldOrder: .utf8Bytes) + let signature = try await ProtoWallet(rootKey: try key(11)).createSignature( + .init( + protocolID: try CertificateProtocols.signature, + keyID: try WalletKeyID(unsigned.signatureKeyID), + counterparty: .anyone, + payload: .digest(BSVHashing.sha256(byteOrder)) + ) + ).signature + let goSigned = try unsigned.replacingSignature(signature) + #expect(try await goSigned.verifySignature()) + let localeOrder = try await unsigned.signed(using: ProtoWallet(rootKey: try key(11))) + #expect(goSigned.signature != localeOrder.signature) + #expect(try await localeOrder.verifySignature()) + #expect(try await verifies(localeOrder, over: byteOrder) == false) + + let tampered = try Certificate( + type: unsigned.type, serialNumber: unsigned.serialNumber, subject: unsigned.subject, + certifier: unsigned.certifier, revocationOutpoint: unsigned.revocationOutpoint, + fields: [ + try CertificateFieldName("Zip"): try CertificateCiphertext([9]), + try CertificateFieldName("age"): try CertificateCiphertext([2]), + ], + signature: signature) + #expect(try await tampered.verifySignature() == false) + } + + private func verifies(_ certificate: Certificate, over preimage: [UInt8]) async throws -> Bool { + try await ProtoWallet.anyone().verifySignature( + .init( + protocolID: try CertificateProtocols.signature, + keyID: try WalletKeyID(certificate.signatureKeyID), + counterparty: .publicKey(certificate.certifier), + payload: .digest(BSVHashing.sha256(preimage)), + signature: try #require(certificate.signature)) + ).valid + } + + private func unsignedCopy(of certificate: Certificate) throws -> Certificate { + try Certificate( + type: certificate.type, serialNumber: certificate.serialNumber, + subject: certificate.subject, certifier: certificate.certifier, + revocationOutpoint: certificate.revocationOutpoint, fields: certificate.fields) + } + + private func key(_ scalar: UInt8) throws -> PrivateKey { + var bytes = [UInt8](repeating: 0, count: 32) + bytes[31] = scalar + return try PrivateKey(bytes) + } +} diff --git a/Tests/BSVAuthTests/Certificates/LocaleCompareOrderTests.swift b/Tests/BSVAuthTests/Certificates/LocaleCompareOrderTests.swift deleted file mode 100644 index 15d87e6..0000000 --- a/Tests/BSVAuthTests/Certificates/LocaleCompareOrderTests.swift +++ /dev/null @@ -1,241 +0,0 @@ -import BSVAuth -import BSVCore -import BSVCrypto -import BSVKeys -import BSVWallet -import Foundation -import Testing - -/// `LocaleCompareOrder` against JavaScript `localeCompare`, and BRC-52 -/// certificate signatures over fields in that order. -/// -/// The expected values were produced by Bun 1.4.4 and Node 22.23.4 (both ICU, -/// locale `en-US`) running `collate-vec.ts` in -/// Documentation/Compatibility/TypeScriptAuthVectors.md; both printed the same -/// results. -@Suite("localeCompare order") -struct LocaleCompareOrderTests { - @Test("printable ASCII sorts as localeCompare does") - func printableASCII() { - let printable = (0x20...0x7E).map { String(UnicodeScalar(UInt8($0))) } - let sorted = printable.sorted(by: LocaleCompareOrder.areInIncreasingOrder) - #expect( - sorted.joined() - == " _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$0123456789" - + "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ") - #expect(LocaleCompareOrder.asciiOrder.hasSuffix(sorted.joined())) - } - - @Test("every pair of printable ASCII characters sorts as localeCompare does") - func printableASCIIPairs() { - let printable = (0x20...0x7E).map { String(UnicodeScalar(UInt8($0))) } - var pairs: [String] = [] - for first in printable { for second in printable { pairs.append(first + second) } } - #expect(pairs.count == 9_025) - // localeCompare reports no ties among these 9025 strings, so the order is total. - #expect( - sortedDigest(pairs) - == "486638e314651e755e158382de74daec1be1e94d392ff87e70f48006b14bc4f8") - } - - @Test("three-character strings over spaces, punctuation, digits and both cases") - func triples() { - let alphabet = Array(" !-._09aAzZ").map(String.init) - var triples: [String] = [] - for a in alphabet { for b in alphabet { for c in alphabet { triples.append(a + b + c) } } } - #expect(triples.count == 1_331) - #expect( - sortedDigest(triples) - == "a7264e62b832c8d1682eb3222b5dadff4d39138b5c05a7fd517bbc32941eb25f") - } - - @Test("random printable ASCII strings of one to eight characters") - func randomStrings() { - // x = (1103515245 x + 12345) mod 2^31 from x = 1, as in `collate-vec.ts`. - var state: UInt32 = 1 - func next() -> Int { - state = (state &* 1_103_515_245 &+ 12_345) & 0x7FFF_FFFF - return Int(state) - } - var strings: [String] = [] - for _ in 0..<4_000 { - let length = 1 + next() % 8 - var value = "" - for _ in 0..^0"]) - #expect(Set(strings).count == 4_000) - #expect( - sortedDigest(strings) - == "1c2fb4ded5031dfa2cf5cf764b119dcb5477b331e17dd8ce43dc71234585957a") - } - - @Test("field and header names sort as localeCompare does") - func names() { - let names = [ - "Zip", "age", "a_b", "a-b", "ab", "a b", "A", "a", "aB", "Ab", "a1", "a10", "a2", - "x-bsv-a_b", "x-bsv-ab", "x-bsv-a-b", "x-bsv-Z", "x-bsv-z", "email", "Email", - "first_name", "firstName", "first-name", - ] - #expect( - names.sorted(by: LocaleCompareOrder.areInIncreasingOrder) == [ - "a", "A", "a b", "a_b", "a-b", "a1", "a10", "a2", "ab", "aB", "Ab", "age", "email", - "Email", "first_name", "first-name", "firstName", "x-bsv-a_b", "x-bsv-a-b", - "x-bsv-ab", "x-bsv-z", "x-bsv-Z", "Zip", - ]) - #expect(LocaleCompareOrder.compare("age", "Zip") < 0) - #expect(Array("age".utf8).lexicographicallyPrecedes(Array("Zip".utf8)) == false) - } - - @Test("non-ASCII and ignorable characters have a documented total order") - func nonASCII() { - // ICU ignores most C0 controls: `'a\u0001b'.localeCompare('ab') === 0`. - // Such ties fall back to UTF-8 byte order, so the order stays total. - #expect(LocaleCompareOrder.compare("a\u{01}b", "ab") < 0) - #expect(LocaleCompareOrder.compare("ab", "a\u{01}b") > 0) - #expect(LocaleCompareOrder.compare("a\u{AD}b", "abc") < 0) - // Other non-ASCII sorts after ASCII in code point order. ICU puts - // `é` between `e` and `f`; this order does not. - #expect(LocaleCompareOrder.compare("é", "z") > 0) - #expect(LocaleCompareOrder.compare("日本", "é") > 0) - #expect(LocaleCompareOrder.compare("same", "same") == 0) - } - - private func sortedDigest(_ strings: [String]) -> String { - let sorted = strings.sorted(by: LocaleCompareOrder.areInIncreasingOrder) - return Hex.encode(BSVHashing.sha256(Array(sorted.joined(separator: "\n").utf8)).bytes) - } -} - -@Suite("BRC-52 certificate field order") -struct CertificateFieldOrderTests { - @Test("a TS-signed certificate with mixed-case fields verifies") - func typeScriptMixedCaseCertificate() async throws { - let certificate = try Certificate(json: Array(TypeScriptAuthVectors.mixedCaseCertificate.utf8)) - #expect( - Hex.encode(try certificate.localeOrderSigningPreimage(limits: .standard)) - == TypeScriptAuthVectors.mixedCaseCertificatePreimage) - #expect(try await certificate.verifySignatureInEitherFieldOrder(limits: .standard)) - #expect(try await verifies(certificate, over: certificate.localeOrderSigningPreimage(limits: .standard))) - - // Signing the same unsigned certificate gives TypeScript's RFC 6979 signature. - let unsigned = try unsignedCopy(of: certificate) - let resigned = try await unsigned.signedInLocaleOrder( - using: ProtoWallet(rootKey: try key(11)), limits: .standard) - #expect(resigned.signature == certificate.signature) - } - - @Test("issued certificates are signed in localeCompare order") - func issuedMixedCaseCertificate() async throws { - let master = try await CertificateEngine.issue( - type: try CertificateTypeID([UInt8](repeating: 0x21, count: 32)), - subject: .publicKey(try key(7).publicKey), - plaintextFields: [ - try CertificateFieldName("Zip"): "90210", try CertificateFieldName("age"): "30", - try CertificateFieldName("a_b"): "1", try CertificateFieldName("a-b"): "2", - ], - using: ProtoWallet(rootKey: try key(11))) - let certificate = master.certificate - let localeOrder = try certificate.localeOrderSigningPreimage(limits: .standard) - #expect(localeOrder != (try certificate.binary(includingSignature: false))) - #expect(try await verifies(certificate, over: localeOrder)) - #expect(try await certificate.verifySignatureInEitherFieldOrder(limits: .standard)) - } - - @Test("non-ASCII field names are refused at issue and still verify in byte order") - func nonASCIIFieldNames() async throws { - // ICU root collation is not emulated past ASCII (COMP-041), so a - // certificate whose TS signature order could not be predicted is not issued. - let fields = [ - try CertificateFieldName("été"): "summer", try CertificateFieldName("age"): "30", - ] - let log = AuthLogLines() - let error = await log.record { - await #expect(throws: (any Error).self) { - try await CertificateEngine.issue( - type: try CertificateTypeID([UInt8](repeating: 0x24, count: 32)), - subject: .publicKey(try key(7).publicKey), - plaintextFields: fields, - using: ProtoWallet(rootKey: try key(11))) - } - } - #expect( - error?.localizedDescription - == "Certificate field names must use only plain ASCII letters, digits, spaces and symbols.") - #expect(log.lines.contains { $0.contains("field name") }) - - let unsigned = try Certificate( - type: try CertificateTypeID([UInt8](repeating: 0x25, count: 32)), - serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x26, count: 32)), - subject: try key(7).publicKey, - certifier: try key(11).publicKey, - revocationOutpoint: CertificateEngine.disabledRevocationOutpoint, - fields: [ - try CertificateFieldName("été"): try CertificateCiphertext([1]), - try CertificateFieldName("age"): try CertificateCiphertext([2]), - ]) - await #expect(throws: (any Error).self) { - try await unsigned.signedInLocaleOrder( - using: ProtoWallet(rootKey: try key(11)), limits: .standard) - } - // A Go-style byte-order signature over such names is still accepted. - let byteOrder = try await unsigned.signed(using: ProtoWallet(rootKey: try key(11))) - #expect(try await byteOrder.verifySignatureInEitherFieldOrder(limits: .standard)) - } - - @Test("certificates signed in byte order still verify") - func byteOrderSignatureStillVerifies() async throws { - let unsigned = try Certificate( - type: try CertificateTypeID([UInt8](repeating: 0x22, count: 32)), - serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x23, count: 32)), - subject: try key(7).publicKey, - certifier: try key(11).publicKey, - revocationOutpoint: CertificateEngine.disabledRevocationOutpoint, - fields: [ - try CertificateFieldName("Zip"): try CertificateCiphertext([1]), - try CertificateFieldName("age"): try CertificateCiphertext([2]), - ]) - // `Certificate.signed` signs the UTF-8 byte order, as the Go SDK does. - let byteOrder = try await unsigned.signed(using: ProtoWallet(rootKey: try key(11))) - #expect(try await byteOrder.verifySignatureInEitherFieldOrder(limits: .standard)) - let localeOrder = try await unsigned.signedInLocaleOrder( - using: ProtoWallet(rootKey: try key(11)), limits: .standard) - #expect(byteOrder.signature != localeOrder.signature) - #expect(try await localeOrder.verifySignatureInEitherFieldOrder(limits: .standard)) - - let tampered = try Certificate( - type: unsigned.type, serialNumber: unsigned.serialNumber, subject: unsigned.subject, - certifier: unsigned.certifier, revocationOutpoint: unsigned.revocationOutpoint, - fields: [ - try CertificateFieldName("Zip"): try CertificateCiphertext([9]), - try CertificateFieldName("age"): try CertificateCiphertext([2]), - ], - signature: byteOrder.signature) - #expect(try await tampered.verifySignatureInEitherFieldOrder(limits: .standard) == false) - } - - private func verifies(_ certificate: Certificate, over preimage: [UInt8]) async throws -> Bool { - try await ProtoWallet.anyone().verifySignature( - .init( - protocolID: try CertificateProtocols.signature, - keyID: try WalletKeyID(certificate.signatureKeyID), - counterparty: .publicKey(certificate.certifier), - payload: .digest(BSVHashing.sha256(preimage)), - signature: try #require(certificate.signature)) - ).valid - } - - private func unsignedCopy(of certificate: Certificate) throws -> Certificate { - try Certificate( - type: certificate.type, serialNumber: certificate.serialNumber, - subject: certificate.subject, certifier: certificate.certifier, - revocationOutpoint: certificate.revocationOutpoint, fields: certificate.fields) - } - - private func key(_ scalar: UInt8) throws -> PrivateKey { - var bytes = [UInt8](repeating: 0, count: 32) - bytes[31] = scalar - return try PrivateKey(bytes) - } -} diff --git a/Tests/BSVConformanceTests/BSVLogSinkTests.swift b/Tests/BSVConformanceTests/BSVLogSinkTests.swift new file mode 100644 index 0000000..82bb57b --- /dev/null +++ b/Tests/BSVConformanceTests/BSVLogSinkTests.swift @@ -0,0 +1,292 @@ +import BSVAuth +import BSVCore +import BSVCrypto +import BSVKeys +import BSVNetwork +import BSVOverlay +import BSVTransaction +import BSVWallet +import Foundation +import Testing + +/// The `BSVLog` handler, which receives every module's lines on every +/// platform. The handler is process-wide, so these tests run one at a time +/// and keep only lines carrying their own marker; other suites may write +/// lines while they run. +@Suite("BSVLog handler", .serialized) +struct BSVLogSinkTests { + @Test("every module's log reaches the handler with its category") + func everyModuleReachesHandler() { + let marker = UUID().uuidString + let lines = LogLines(marker: marker) + BSVLog.setHandler(lines.record) + defer { BSVLog.setHandler(nil) } + + NetworkLog.error("network \(marker)") + WalletLog.error("wallet \(marker)") + OverlayLog.error("overlay \(marker)") + AuthLog.error("auth \(marker)") + + #expect(lines.entries == [ + BSVLog.Entry(category: "BSVNetwork", message: "network \(marker)", hasPrivateDetail: false), + BSVLog.Entry(category: "BSVWallet", message: "wallet \(marker)", hasPrivateDetail: false), + BSVLog.Entry(category: "BSVOverlay", message: "overlay \(marker)", hasPrivateDetail: false), + BSVLog.Entry(category: "BSVAuth", message: "auth \(marker)", hasPrivateDetail: false), + ]) + #expect(BSVLog.subsystem == "dev.opl.swift-sdk") + } + + @Test("a private detail is redacted unless the caller opts in") + func privateDetails() { + let marker = UUID().uuidString + let lines = LogLines(marker: marker) + let callerError = CallerWalletError.failed("secret-\(marker)") + + BSVLog.setHandler(lines.record) + AuthLog.reported("Redacted \(marker)", callerError, as: AuthError.certificateValidationFailed) + // An error this SDK defines is public, as in the system log. + AuthLog.reported("Public \(marker)", CertificateError.invalidJSON, as: AuthError.certificateValidationFailed) + BSVLog.setHandler(lines.record, revealingPrivateDetails: true) + AuthLog.reported("Revealed \(marker)", callerError, as: AuthError.certificateValidationFailed) + BSVLog.setHandler(nil) + AuthLog.reported("Removed \(marker)", callerError, as: AuthError.certificateValidationFailed) + + let entries = lines.entries + #expect(entries.count == 3) + #expect(entries.allSatisfy { $0.category == "BSVAuth" }) + let redacted = entries[0] + #expect(redacted.hasPrivateDetail) + #expect(redacted.message.hasPrefix("Redacted \(marker): CallerWalletError: ; reported as ")) + #expect(!redacted.message.contains("secret-")) + #expect(!entries[1].hasPrivateDetail) + #expect(entries[1].message.contains("CertificateError.invalidJSON")) + #expect(entries[2].hasPrivateDetail) + #expect(entries[2].message.contains("secret-\(marker)")) + } + + @Test("an SDK failure is logged through the handler") + func sdkFailureReachesHandler() async throws { + let lines = LogLines(marker: "Certificate signing") + BSVLog.setHandler(lines.record) + defer { BSVLog.setHandler(nil) } + var key = [UInt8](repeating: 0, count: 32) + key[31] = 11 + let certifier = try PrivateKey(key) + let unsigned = try Certificate( + type: try CertificateTypeID([UInt8](repeating: 0x41, count: 32)), + serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x42, count: 32)), + subject: certifier.publicKey, + certifier: certifier.publicKey, + revocationOutpoint: Outpoint( + transactionID: TransactionID(exactDigestBytesGuaranteed: [UInt8](repeating: 0, count: 32)), + outputIndex: 0), + fields: [ + try CertificateFieldName("日本"): try CertificateCiphertext([1]), + try CertificateFieldName("a"): try CertificateCiphertext([2]), + ]) + await #expect(throws: CertificateFieldNameError.unsupportedCharacter) { + try await unsigned.signed(using: ProtoWallet(rootKey: certifier)) + } + #expect(lines.entries.contains { + $0.category == "BSVWallet" + && $0.message.hasPrefix("Certificate signing: a field name of 6 bytes") + }) + } + + @Test("a caller's transport or facilitator error text is private; an SDK error is public") + func callerErrorTextIsPrivate() throws { + let marker = UUID().uuidString + let lines = LogLines(marker: marker) + BSVLog.setHandler(lines.record) + defer { BSVLog.setHandler(nil) } + let request = HTTPRequest( + method: .get, url: try #require(URL(string: "https://api.example/v1/tx?key=k"))) + let callerError = CallerWalletError.failed("https://api.example/v1/tx?key=secret-\(marker)") + + NetworkLog.failure("Caller \(marker)", request: request, underlying: callerError) + NetworkLog.failure("SDK \(marker)", request: request, underlying: NetworkServiceError.timedOut) + let host = try OverlayHost(rawValue: "https://overlay.example") + OverlayLog.hostFailure("Caller \(marker)", OverlayHostFailure(host: host, error: callerError)) + OverlayLog.hostFailure( + "SDK \(marker)", + OverlayHostFailure(host: host, error: OverlayHTTPError.rejected(statusCode: 503))) + + let entries = lines.entries + #expect(entries.map(\.category) == ["BSVNetwork", "BSVNetwork", "BSVOverlay", "BSVOverlay"]) + #expect(entries.map(\.hasPrivateDetail) == [true, false, true, false]) + #expect(entries.allSatisfy { !$0.message.contains("secret-") }) + #expect(entries[0].message == "Caller \(marker): GET api.example/v1/tx failed: CallerWalletError: ") + #expect(entries[1].message.hasSuffix("failed: NetworkServiceError: BSVNetwork.NetworkServiceError.timedOut")) + #expect(entries[2].message == "Caller \(marker): host https://overlay.example failed: CallerWalletError: ") + #expect(entries[3].message.contains("OverlayHTTPError.rejected(statusCode: 503")) + + BSVLog.setHandler(lines.record, revealingPrivateDetails: true) + NetworkLog.failure("Revealed \(marker)", request: request, underlying: callerError) + #expect(lines.entries.last?.message.contains("secret-\(marker)") == true) + #expect(BSVLog.isSDKError(OverlayPolicyError.invalidSteak)) + #expect(!BSVLog.isSDKError(callerError)) + } + + @Test("certificate verification logs a match by byte or received order and an unexplained failure") + func certificateVerificationLines() async throws { + let lines = LogLines(marker: "Certificate verification:") + BSVLog.setHandler(lines.record) + defer { BSVLog.setHandler(nil) } + let wallet = try ProtoWallet(rootKey: certifierKey()) + + // Signed over UTF-8 byte order, as the Go SDK signs. + let goOrder = try unsignedCertificate(names: ["Zip", "age"], serial: 0x50) + let goSigned = try goOrder.replacingSignature(try await sign( + goOrder.binary(includingSignature: false, limits: .standard, fieldOrder: .utf8Bytes), + for: goOrder, with: wallet)) + #expect(try await goSigned.verifySignature()) + + // Signed over the order the fields arrived in, which is neither. + var received = try unsignedCertificate(names: ["Zip", "age", "_x"], serial: 0x51) + received.receivedFieldOrder = try ["age", "_x", "Zip"].map { try CertificateFieldName($0) } + let receivedSigned = try received.replacingSignature(try await sign( + received.binary(includingSignature: false, limits: .standard, fieldOrder: .received), + for: received, with: wallet)) + #expect(try await receivedSigned.verifySignature()) + + // A name outside the reproduced order, and a signature no order matches. + let exotic = try unsignedCertificate(names: ["日本", "a"], serial: 0x52) + let wrong = try exotic.replacingSignature(try await sign([1, 2, 3], for: exotic, with: wallet)) + #expect(try await wrong.verifySignature() == false) + + let messages = lines.entries.map(\.message) + #expect(messages.contains( + "Certificate verification: the signature covers its 2 fields in UTF-8 byte order, " + + "as the Go SDK signs, not in localeCompare order")) + #expect(messages.contains( + "Certificate verification: the signature covers its 3 fields in the order they were " + + "received, which is neither localeCompare order on an en-US host nor UTF-8 byte order")) + #expect(messages.contains { $0.hasPrefix( + "Certificate verification: the signature did not verify; a field name of 6 bytes") }) + #expect(lines.entries.allSatisfy { $0.category == "BSVWallet" && !$0.hasPrivateDetail }) + } + + @Test("a handler may log and replace the handler from inside itself") + func reentrantHandler() { + let marker = UUID().uuidString + let outer = LogLines(marker: marker) + let replacement = LogLines(marker: marker) + let reentrant: BSVLog.Handler = { entry in + outer.record(entry) + guard entry.message == "first \(marker)" else { return } + // Writing a line from inside the handler calls it again. + WalletLog.error("nested \(marker)") + BSVLog.setHandler(replacement.record) + } + BSVLog.setHandler(reentrant) + defer { BSVLog.setHandler(nil) } + + WalletLog.error("first \(marker)") + WalletLog.error("after \(marker)") + + #expect(outer.entries.map(\.message) == ["first \(marker)", "nested \(marker)"]) + #expect(replacement.entries.map(\.message) == ["after \(marker)"]) + } + + @Test("lines written from many tasks while the handler is swapped each reach one handler") + func concurrentLinesAndSwaps() async { + let marker = UUID().uuidString + let first = LogLines(marker: marker) + let second = LogLines(marker: marker) + BSVLog.setHandler(first.record) + defer { BSVLog.setHandler(nil) } + let writers = 16 + let linesPerWriter = 200 + + await withTaskGroup(of: Void.self) { group in + for writer in 0..") }) + #expect(second.entries.allSatisfy { $0.message.contains("CallerWalletError.failed(\"secret\")") }) + } + + private func certifierKey() throws -> PrivateKey { + var key = [UInt8](repeating: 0, count: 32) + key[31] = 11 + return try PrivateKey(key) + } + + private func unsignedCertificate(names: [String], serial: UInt8) throws -> Certificate { + let certifier = try certifierKey().publicKey + var fields: [CertificateFieldName: CertificateCiphertext] = [:] + for (index, name) in names.enumerated() { + fields[try CertificateFieldName(name)] = try CertificateCiphertext([UInt8(index + 1)]) + } + return try Certificate( + type: try CertificateTypeID([UInt8](repeating: 0x4F, count: 32)), + serialNumber: try CertificateSerialNumber([UInt8](repeating: serial, count: 32)), + subject: certifier, + certifier: certifier, + revocationOutpoint: Outpoint( + transactionID: TransactionID(exactDigestBytesGuaranteed: [UInt8](repeating: 0, count: 32)), + outputIndex: 0), + fields: fields) + } + + private func sign( + _ preimage: [UInt8], for certificate: Certificate, with wallet: ProtoWallet + ) async throws -> ECDSASignature { + try await wallet.createSignature(.init( + protocolID: try CertificateProtocols.signature, + keyID: try WalletKeyID(certificate.signatureKeyID), + counterparty: .anyone, + payload: .digest(BSVHashing.sha256(preimage)) + )).signature + } +} + +private enum CallerWalletError: Error { + case failed(String) +} + +/// Collects the lines that contain `marker`. +private final class LogLines: @unchecked Sendable { + private let marker: String + private let lock = NSLock() + private var recorded: [BSVLog.Entry] = [] + + init(marker: String) { self.marker = marker } + + var record: BSVLog.Handler { + { [self] entry in + guard entry.message.contains(marker) else { return } + lock.lock() + recorded.append(entry) + lock.unlock() + } + } + + var entries: [BSVLog.Entry] { + lock.lock() + defer { lock.unlock() } + return recorded + } +} diff --git a/Tests/BSVCoreTests/Text/LocaleCompareOrderTests.swift b/Tests/BSVCoreTests/Text/LocaleCompareOrderTests.swift new file mode 100644 index 0000000..7ab00ac --- /dev/null +++ b/Tests/BSVCoreTests/Text/LocaleCompareOrderTests.swift @@ -0,0 +1,190 @@ +import BSVCore +import BSVCrypto +import Testing + +/// `LocaleCompareOrder` against JavaScript `localeCompare`. +/// +/// The expected values were produced by Bun 1.4.4 and Node 22.23.4 (both ICU, +/// locale `en-US`) running `collate-vec.ts` and `certorder-vec.ts` in +/// Documentation/Compatibility/TypeScriptAuthVectors.md; both printed the same +/// results. +@Suite("localeCompare order") +struct LocaleCompareOrderTests { + @Test("printable ASCII sorts as localeCompare does") + func printableASCII() { + let printable = (0x20...0x7E).map { String(UnicodeScalar(UInt8($0))) } + let sorted = printable.sorted(by: LocaleCompareOrder.areInIncreasingOrder) + #expect( + sorted.joined() + == " _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$0123456789" + + "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ") + #expect(LocaleCompareOrder.asciiOrder.hasSuffix(sorted.joined())) + } + + @Test("every pair of printable ASCII characters sorts as localeCompare does") + func printableASCIIPairs() { + let printable = (0x20...0x7E).map { String(UnicodeScalar(UInt8($0))) } + var pairs: [String] = [] + for first in printable { for second in printable { pairs.append(first + second) } } + #expect(pairs.count == 9_025) + // localeCompare reports no ties among these 9025 strings, so the order is total. + #expect( + sortedDigest(pairs) + == "486638e314651e755e158382de74daec1be1e94d392ff87e70f48006b14bc4f8") + } + + @Test("three-character strings over spaces, punctuation, digits and both cases") + func triples() { + let alphabet = Array(" !-._09aAzZ").map(String.init) + var triples: [String] = [] + for a in alphabet { for b in alphabet { for c in alphabet { triples.append(a + b + c) } } } + #expect(triples.count == 1_331) + #expect( + sortedDigest(triples) + == "a7264e62b832c8d1682eb3222b5dadff4d39138b5c05a7fd517bbc32941eb25f") + } + + @Test("random printable ASCII strings of one to eight characters") + func randomStrings() { + // x = (1103515245 x + 12345) mod 2^31 from x = 1, as in `collate-vec.ts`. + var state: UInt32 = 1 + func next() -> Int { + state = (state &* 1_103_515_245 &+ 12_345) & 0x7FFF_FFFF + return Int(state) + } + var strings: [String] = [] + for _ in 0..<4_000 { + let length = 1 + next() % 8 + var value = "" + for _ in 0..^0"]) + #expect(Set(strings).count == 4_000) + #expect( + sortedDigest(strings) + == "1c2fb4ded5031dfa2cf5cf764b119dcb5477b331e17dd8ce43dc71234585957a") + } + + @Test("field and header names sort as localeCompare does") + func names() { + let names = [ + "Zip", "age", "a_b", "a-b", "ab", "a b", "A", "a", "aB", "Ab", "a1", "a10", "a2", + "x-bsv-a_b", "x-bsv-ab", "x-bsv-a-b", "x-bsv-Z", "x-bsv-z", "email", "Email", + "first_name", "firstName", "first-name", + ] + #expect( + names.sorted(by: LocaleCompareOrder.areInIncreasingOrder) == [ + "a", "A", "a b", "a_b", "a-b", "a1", "a10", "a2", "ab", "aB", "Ab", "age", "email", + "Email", "first_name", "first-name", "firstName", "x-bsv-a_b", "x-bsv-a-b", + "x-bsv-ab", "x-bsv-z", "x-bsv-Z", "Zip", + ]) + #expect(LocaleCompareOrder.compare("age", "Zip") < 0) + #expect(Array("age".utf8).lexicographicallyPrecedes(Array("Zip".utf8)) == false) + } + + @Test("non-Latin and ignorable characters have a documented total order") + func nonLatin() { + // ICU ignores most C0 controls: `'a\u0001b'.localeCompare('ab') === 0`. + // Such ties fall back to UTF-8 byte order, so the order stays total. + #expect(LocaleCompareOrder.compare("a\u{01}b", "ab") < 0) + #expect(LocaleCompareOrder.compare("ab", "a\u{01}b") > 0) + #expect(LocaleCompareOrder.compare("a\u{AD}b", "abc") < 0) + // Characters past the Latin letters sort after them in code point + // order. ICU puts `ø` among the `o`s; this order does not. + #expect(LocaleCompareOrder.compare("ø", "z") > 0) + #expect(LocaleCompareOrder.compare("日本", "ø") > 0) + #expect(LocaleCompareOrder.compare("same", "same") == 0) + #expect(!LocaleCompareOrder.isExact("ø")) + #expect(!LocaleCompareOrder.isExact("e\u{301}")) + #expect(!LocaleCompareOrder.isExact("a\u{01}")) + #expect(LocaleCompareOrder.isExact("Ångström résumé_2")) + } + + @Test("accented Latin letters sort among the ASCII letters, as localeCompare puts them") + func accentedLetters() { + let letters = Self.latinLetters + #expect(letters.count == 488) + #expect(letters.first == "À" && letters.last == "ỹ") + let printable = (0x20...0x7E).map { String(UnicodeScalar(UInt8($0))) } + #expect( + sortedDigest(printable + letters) + == "07b7a5435f649f665bee10c149883c140afb2fd1063cbdbce1a699417158cf36") + + let alphabet = Array("aAeEzZ_-1 .áÁàâäåéÉèêëǖüűñÑçșţắạ").map(String.init) + var pairs: [String] = [] + for first in alphabet { for second in alphabet { pairs.append(first + second) } } + #expect(pairs.count == 1_024) + #expect( + sortedDigest(pairs) + == "57181742c00e7739f0c68888ec3318e869ee62652f93f9851c4ea2f380e2b2cb") + + // Every fourth letter, so the base letter, accents and case all vary. + let pool = Array("aAbBeEnNoOuUzZ").map(String.init) + + letters.enumerated().filter { $0.offset % 4 == 0 }.map(\.element) + var letterPairs: [String] = [] + for first in pool { for second in pool { letterPairs.append(first + second) } } + #expect(letterPairs.count == 18_496) + #expect( + sortedDigest(letterPairs) + == "715437241639b28e026b8aa2878e19c5ba18803f7ee8383ec90d938f90a1c48f") + // A decomposed accent weighs as the precomposed letter does. + #expect(LocaleCompareOrder.compare("e\u{301}", "é") < 0) + #expect(LocaleCompareOrder.compare("e\u{301}x", "éx") < 0) + #expect(LocaleCompareOrder.compare("e\u{301}", "ê") < 0) + #expect(LocaleCompareOrder.compare("e\u{301}", "è") < 0) + #expect(LocaleCompareOrder.compare("e\u{301}", "e") > 0) + } + + @Test("random strings of ASCII and accented Latin letters") + func randomLatinStrings() { + let printable = (0x20...0x7E).map { String(UnicodeScalar(UInt8($0))) } + let alphabet = printable + Self.latinLetters + #expect(alphabet.count == 583) + // x = (1103515245 x + 12345) mod 2^31 from x = 7, as in `certorder-vec.ts`. + var state: UInt32 = 7 + func next() -> Int { + state = (state &* 1_103_515_245 &+ 12_345) & 0x7FFF_FFFF + return Int(state) + } + var strings: [String] = [] + for _ in 0..<6_000 { + let length = 1 + next() % 8 + var value = "" + for _ in 0.. String { + let sorted = strings.sorted(by: LocaleCompareOrder.areInIncreasingOrder) + return Hex.encode(BSVHashing.sha256(Array(sorted.joined(separator: "\n").utf8)).bytes) + } +} diff --git a/Tests/BSVIdentityTests/IdentityClientTests.swift b/Tests/BSVIdentityTests/IdentityClientTests.swift index 1e9782b..76d27b7 100644 --- a/Tests/BSVIdentityTests/IdentityClientTests.swift +++ b/Tests/BSVIdentityTests/IdentityClientTests.swift @@ -202,6 +202,40 @@ struct IdentityClientTests { #expect(!String(reflecting: client).contains("IdentityTestWallet")) } + /// A certificate signed by `@bsv/sdk` 4.1.1 `Certificate.sign`, whose + /// fields TypeScript orders with `localeCompare` + /// (`auth/certificates/Certificate.ts:290`): names differ from byte order + /// in case, accents, underscores and digits. TypeScript + /// `IdentityClient.publiclyRevealAttributes` verifies it + /// (`identity/IdentityClient.ts:461`); so must this client. From + /// `certorder-vec.ts` (Documentation/Compatibility/TypeScriptAuthVectors.md). + @Test("public disclosure accepts a certificate TypeScript signed in localeCompare order") + func revealsTypeScriptCertificate() async throws { + let fixture = try await identityFixture() + let certificate = try Certificate(json: Array(Self.typeScriptCertificateJSON.utf8)) + let field = try CertificateFieldName("résumé") + let subject = try PrivateKey(Array(repeating: 0, count: 31) + [7]) + #expect(certificate.subject == subject.publicKey) + let state = IdentityWalletState( + proofKeyring: [field: try CertificateCiphertext([7, 8, 9])], + completedTransaction: fixture.atomic + ) + let client = try IdentityClient( + wallet: IdentityTestWallet(root: subject, state: state), + limits: fixture.limits + ) + let result = try await client.publiclyRevealAttributes( + certificate: certificate, + fieldsToReveal: [field], + using: RecordingBroadcaster(expected: fixture.transactionID) + ) + #expect(result.transactionID == fixture.transactionID) + #expect(await state.snapshot().action != nil) + } + + private static let typeScriptCertificateJSON = + #"{"type":"MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE=","serialNumber":"MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI=","subject":"025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","certifier":"03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","revocationOutpoint":"0000000000000000000000000000000000000000000000000000000000000000.0","fields":{"Zip":"AQ==","zip_code":"Ag==","zip-code":"Aw==","zip2":"BA==","zip10":"BQ==","Zeta":"Bg==","email":"Bw==","eMail":"CA==","Email":"CQ==","_id":"Cg==","id":"Cw==","ID":"DA==","a1":"DQ==","a_1":"Dg==","a-1":"Dw==","aB":"EA==","ab":"EQ==","cafe":"Eg==","café":"Ew==","Café":"FA==","cafés":"FQ==","émile":"Fg==","Émile":"Fw==","naïve":"GA==","nausea":"GQ==","résumé":"Gg==","resume":"Gw==","zoë":"HA==","Ångström":"HQ==","angle":"Hg=="},"signature":"30440220414ba43586646efbbb901e48680c419bb5de91ec1730ef99f7602bda95c1711b02204aa129d5d7bb3d1d2c5865243d48a9f84a34dbeab5b58f8ce06c6d9d0e607969"}"# + /// The token must pass the TypeScript tm_identity topic manager /// (packages/overlays/topics/src/identity/identityTokenValidation.ts): /// exactly two fields in a five-chunk script, locked to the anyone key's diff --git a/Tests/BSVWalletTests/Certificates/BRC52CertificateBinaryTests.swift b/Tests/BSVWalletTests/Certificates/BRC52CertificateBinaryTests.swift index 96e46c3..eb4da32 100644 --- a/Tests/BSVWalletTests/Certificates/BRC52CertificateBinaryTests.swift +++ b/Tests/BSVWalletTests/Certificates/BRC52CertificateBinaryTests.swift @@ -7,7 +7,7 @@ import BSVTransaction @testable import BSVWallet final class BRC52CertificateBinaryTests: XCTestCase { - func testExactIDsDisplayTxidCompactVoutAndRawUTF8FieldOrder() throws { + func testExactIDsDisplayTxidCompactVoutAndLocaleCompareFieldOrder() throws { let type = try CertificateTypeID(Array(0..<32).map(UInt8.init)) let serial = try CertificateSerialNumber(Array(32..<64).map(UInt8.init)) let subject = try key(7).publicKey @@ -39,9 +39,14 @@ final class BRC52CertificateBinaryTests: XCTestCase { XCTAssertEqual(Array(binary[130..<162]), displayBytes) XCTAssertEqual(Array(binary[162..<165]), [0xfd, 0xfd, 0x00]) XCTAssertEqual(binary[165], 2) - XCTAssertEqual(binary[166], 1) - XCTAssertEqual(binary[167], Character("z").asciiValue) + // `localeCompare` ignores the C1 control U+0080, so it sorts before + // `z`; UTF-8 byte order puts it after. + XCTAssertEqual(Array(binary[166..<169]), [2, 0xC2, 0x80]) XCTAssertEqual(try Certificate(binary: binary), certificate) + let byteOrder = try certificate.binary( + includingSignature: false, limits: .standard, fieldOrder: .utf8Bytes) + XCTAssertEqual(Array(byteOrder[166..<168]), [1, Character("z").asciiValue!]) + XCTAssertEqual(try Certificate(binary: byteOrder), certificate) } func testStrictCanonicalBase64JSONAndExactIdentifierWidths() throws { diff --git a/Tests/BSVWalletTests/Certificates/CertificateFieldOrderVectorTests.swift b/Tests/BSVWalletTests/Certificates/CertificateFieldOrderVectorTests.swift new file mode 100644 index 0000000..f8d5b03 --- /dev/null +++ b/Tests/BSVWalletTests/Certificates/CertificateFieldOrderVectorTests.swift @@ -0,0 +1,268 @@ +import BSVCore +import BSVCrypto +import BSVKeys +import BSVTransaction +import BSVWallet +import Foundation +import Testing + +/// BRC-52 certificates written and signed by `@bsv/sdk` 4.1.1 +/// `Certificate.sign` and `Certificate.toBinary`, whose fields are in +/// `localeCompare` order (`auth/certificates/Certificate.ts:290`, `:473`). +/// The field names differ from UTF-8 byte order in case, accents, underscores +/// and digits. Produced by `certorder-vec.ts` in +/// Documentation/Compatibility/TypeScriptAuthVectors.md (certifier key 11, +/// subject key 7). +@Suite("BRC-52 certificates in TypeScript field order") +struct CertificateFieldOrderVectorTests { + static let accentedCertificateJSON = + #"{"type":"MTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE=","serialNumber":"MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjI=","subject":"025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","certifier":"03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","revocationOutpoint":"0000000000000000000000000000000000000000000000000000000000000000.0","fields":{"Zip":"AQ==","zip_code":"Ag==","zip-code":"Aw==","zip2":"BA==","zip10":"BQ==","Zeta":"Bg==","email":"Bw==","eMail":"CA==","Email":"CQ==","_id":"Cg==","id":"Cw==","ID":"DA==","a1":"DQ==","a_1":"Dg==","a-1":"Dw==","aB":"EA==","ab":"EQ==","cafe":"Eg==","café":"Ew==","Café":"FA==","cafés":"FQ==","émile":"Fg==","Émile":"Fw==","naïve":"GA==","nausea":"GQ==","résumé":"Gg==","resume":"Gw==","zoë":"HA==","Ångström":"HQ==","angle":"Hg=="},"signature":"30440220414ba43586646efbbb901e48680c419bb5de91ec1730ef99f7602bda95c1711b02204aa129d5d7bb3d1d2c5865243d48a9f84a34dbeab5b58f8ce06c6d9d0e607969"}"# + + static let accentedCertificateBinary = + "313131313131313131313131313131313131313131313131313131313131313132323232323232323232323232323232" + + "32323232323232323232323232323232025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9" + + "bc03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb0000000000000000000000000000" + + "000000000000000000000000000000000000001e035f69640443673d3d03615f310444673d3d03612d310444773d3d02" + + "61310444513d3d0261620445513d3d0261420445413d3d05616e676c650448673d3d0ac3856e67737472c3b66d044851" + + "3d3d04636166650445673d3d05636166c3a90445773d3d05436166c3a90446413d3d06636166c3a9730446513d3d0565" + + "6d61696c0442773d3d05654d61696c0443413d3d05456d61696c0443513d3d06c3a96d696c650446673d3d06c3896d69" + + "6c650446773d3d0269640443773d3d0249440444413d3d066e61c3af76650447413d3d066e61757365610447513d3d06" + + "726573756d650447773d3d0872c3a973756dc3a90447673d3d045a6574610442673d3d035a69700441513d3d087a6970" + + "5f636f64650441673d3d087a69702d636f64650441773d3d057a697031300442513d3d047a6970320442413d3d047a6f" + + "c3ab0448413d3d30440220414ba43586646efbbb901e48680c419bb5de91ec1730ef99f7602bda95c1711b02204aa129" + + "d5d7bb3d1d2c5865243d48a9f84a34dbeab5b58f8ce06c6d9d0e607969" + + static let accentedCertificatePreimageByteCount = 487 + + static let asciiCertificateBinary = + "333333333333333333333333333333333333333333333333333333333333333334343434343434343434343434343434" + + "34343434343434343434343434343434025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9" + + "bc03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb0000000000000000000000000000" + + "000000000000000000000000000000000000000c035f69640452773d3d03615f310453673d3d0261310453773d3d0565" + + "6d61696c0452513d3d05456d61696c0452673d3d0269640453513d3d0249440453413d3d035a69700451413d3d087a69" + + "705f636f64650451513d3d087a69702d636f64650451673d3d057a697031300452413d3d047a6970320451773d3d3044" + + "022011b40e97ca13fac44274ed40d543546a40ff1be101ae6f0e8b3d29d15150b69d022037020a2aea15e7e11e54a51f" + + "838dc029010b6e42e620425fe93a66cc8edaf8fc" + + static let asciiCertificatePreimageByteCount = 286 + + /// Signed by `Certificate.sign` with names whose `localeCompare` order + /// this SDK does not reproduce: `ß`, which ICU sorts as `ss`, Cyrillic + /// with `ё` and case pairs, and CJK. TypeScript order: + /// `name Name strasse straße strat stress ёлка ель имя Имя 名前 日本`. + /// Produced by `certwire-vec.ts` (TypeScriptAuthVectors.md). + static let exoticCertificateJSON = + #"{"type":"NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU1NTU=","serialNumber":"NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY=","subject":"025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","certifier":"03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","revocationOutpoint":"0000000000000000000000000000000000000000000000000000000000000000.0","fields":{"straße":"AQ==","strasse":"Ag==","strat":"Aw==","stress":"BA==","имя":"BQ==","Имя":"Bg==","ёлка":"Bw==","ель":"CA==","日本":"CQ==","名前":"Cg==","name":"Cw==","Name":"DA=="},"signature":"30440220334e585ca445bbfef97538a8a2a8c7b7ef7618e6cc248df7473704cd54b26b820220196f71271a0830f0762ec7385fb2cabde5127b1592d14af46149e3460223a6fc"}"# + + static let exoticCertificateBinary = + "353535353535353535353535353535353535353535353535353535353535353536363636363636363636363636363636" + + "36363636363636363636363636363636025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9" + + "bc03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb0000000000000000000000000000" + + "000000000000000000000000000000000000000c046e616d650443773d3d044e616d650444413d3d0773747261737365" + + "0441673d3d0773747261c39f650441513d3d0573747261740441773d3d067374726573730442413d3d08d191d0bbd0ba" + + "d0b00442773d3d06d0b5d0bbd18c0443413d3d06d0b8d0bcd18f0442513d3d06d098d0bcd18f0442673d3d06e5908de5" + + "898d0443673d3d06e697a5e69cac0443513d3d30440220334e585ca445bbfef97538a8a2a8c7b7ef7618e6cc248df747" + + "3704cd54b26b820220196f71271a0830f0762ec7385fb2cabde5127b1592d14af46149e3460223a6fc" + + /// Signed by `Certificate.sign` with the host collation Node 22 resolves + /// under `LC_ALL=da_DK.UTF-8` (`da-DK`, capitals first), which sorts + /// `email Email id ID aa z` as `Email email ID id z aa`. Produced by + /// `certwire-vec.ts`. + static let danishCertificateJSON = + #"{"type":"Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc3Nzc=","serialNumber":"ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg4ODg=","subject":"025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc","certifier":"03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb","revocationOutpoint":"0000000000000000000000000000000000000000000000000000000000000000.0","fields":{"email":"AQ==","Email":"Ag==","id":"Aw==","ID":"BA==","aa":"BQ==","z":"Bg=="},"signature":"3045022100e2642ed325b09615e6a8a0839625d21ba1a2fafaeff16391478e0c2b70c2824902201ad32b894373467af183e6000955e1eadd6ef7fb38a5f04117292054a8e8e03c"}"# + + static let danishCertificateBinary = + "373737373737373737373737373737373737373737373737373737373737373738383838383838383838383838383838" + + "38383838383838383838383838383838025cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9" + + "bc03774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb0000000000000000000000000000" + + "000000000000000000000000000000000000000605456d61696c0441673d3d05656d61696c0441513d3d024944044241" + + "3d3d0269640441773d3d017a0442673d3d0261610442513d3d3045022100e2642ed325b09615e6a8a0839625d21ba1a2" + + "fafaeff16391478e0c2b70c2824902201ad32b894373467af183e6000955e1eadd6ef7fb38a5f04117292054a8e8e03c" + + @Test("a TS certificate with names outside the reproduced order verifies from binary by received order") + func exoticTypeScriptCertificate() async throws { + let decoded = try Certificate(binary: try hex(Self.exoticCertificateBinary)) + #expect(decoded.receivedFieldOrder?.map(\.value) == [ + "name", "Name", "strasse", "straße", "strat", "stress", "ёлка", "ель", "имя", "Имя", + "名前", "日本", + ]) + // Neither order this SDK computes is the one TypeScript signed. + let unsigned = try decoded.binary(includingSignature: false, limits: .standard, fieldOrder: .received) + #expect(unsigned != (try decoded.binary(includingSignature: false))) + #expect(unsigned != (try decoded.binary( + includingSignature: false, limits: .standard, fieldOrder: .utf8Bytes))) + #expect(Hex.encode(unsigned + decoded.signature!.derBytes) == Self.exoticCertificateBinary) + #expect(try await decoded.verifySignature()) + + // Read from JSON, the certificate is equal but has no received order. + let fromJSON = try Certificate(json: Array(Self.exoticCertificateJSON.utf8)) + #expect(fromJSON == decoded) + #expect(fromJSON.receivedFieldOrder == nil) + #expect(try await fromJSON.verifySignature() == false) + + // The received order carries through a signature replacement, and + // binds the values: a changed value fails in every order. + let resignable = try decoded.withoutSignature() + #expect(try await resignable.replacingSignature(decoded.signature!).verifySignature()) + var fields = decoded.fields + fields[try CertificateFieldName("straße")] = try CertificateCiphertext([0xFF]) + var tampered = try Certificate( + type: decoded.type, serialNumber: decoded.serialNumber, subject: decoded.subject, + certifier: decoded.certifier, revocationOutpoint: decoded.revocationOutpoint, + fields: fields, signature: decoded.signature) + tampered.receivedFieldOrder = decoded.receivedFieldOrder + #expect(try await tampered.verifySignature() == false) + } + + @Test("a TS certificate signed under a Danish host collation verifies from binary") + func danishTypeScriptCertificate() async throws { + let decoded = try Certificate(binary: try hex(Self.danishCertificateBinary)) + #expect(decoded.receivedFieldOrder?.map(\.value) == ["Email", "email", "ID", "id", "z", "aa"]) + #expect(try await decoded.verifySignature()) + let fromJSON = try Certificate(json: Array(Self.danishCertificateJSON.utf8)) + #expect(fromJSON == decoded) + #expect(try await fromJSON.verifySignature() == false) + } + + @Test("a certificate with no field or one is signed whatever the name") + func singleFieldAnyName() async throws { + for fields in [ + [:], + [try CertificateFieldName("日本"): try CertificateCiphertext([1])], + [try CertificateFieldName("tab\tname"): try CertificateCiphertext([2])], + ] as [[CertificateFieldName: CertificateCiphertext]] { + let unsigned = try Certificate( + type: try CertificateTypeID([UInt8](repeating: 0x39, count: 32)), + serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x3A, count: 32)), + subject: try key(7).publicKey, + certifier: try key(11).publicKey, + revocationOutpoint: Outpoint( + transactionID: TransactionID( + exactDigestBytesGuaranteed: [UInt8](repeating: 0, count: 32)), + outputIndex: 0), + fields: fields) + let signed = try await unsigned.signed(using: ProtoWallet(rootKey: key(11))) + #expect(try await signed.verifySignature()) + let decoded = try Certificate(binary: try signed.binary(includingSignature: true)) + #expect(decoded == signed) + #expect(try await decoded.verifySignature()) + } + } + + @Test("a TS certificate with accented and mixed-case names round-trips byte for byte and verifies") + func accentedTypeScriptCertificate() async throws { + let certificate = try Certificate(json: Array(Self.accentedCertificateJSON.utf8)) + let binary = try certificate.binary(includingSignature: true) + #expect(Hex.encode(binary) == Self.accentedCertificateBinary) + #expect( + try certificate.binary(includingSignature: false) + == Array(binary.prefix(Self.accentedCertificatePreimageByteCount))) + #expect(try await certificate.verifySignature()) + + let decoded = try Certificate(binary: try hex(Self.accentedCertificateBinary)) + #expect(decoded == certificate) + #expect(try await decoded.verifySignature()) + + // Signing the same fields gives TypeScript's RFC 6979 signature. + let resigned = try await unsignedCopy(of: certificate).signed(using: ProtoWallet(rootKey: key(11))) + #expect(resigned.signature == certificate.signature) + #expect(try resigned.binary(includingSignature: true) == binary) + } + + @Test("Swift signs an ASCII certificate exactly as TypeScript does") + func asciiTypeScriptCertificate() async throws { + let certificate = try Certificate(binary: try hex(Self.asciiCertificateBinary)) + #expect(Hex.encode(try certificate.binary(includingSignature: true)) == Self.asciiCertificateBinary) + #expect(try await certificate.verifySignature()) + #expect( + try certificate.binary(includingSignature: false).count + == Self.asciiCertificatePreimageByteCount) + let resigned = try await unsignedCopy(of: certificate).signed(using: ProtoWallet(rootKey: key(11))) + #expect(Hex.encode(try resigned.binary(includingSignature: true)) == Self.asciiCertificateBinary) + } + + @Test("a signature over UTF-8 byte order, as the Go SDK signs, still verifies") + func byteOrderSignature() async throws { + let typeScript = try Certificate(binary: try hex(Self.asciiCertificateBinary)) + let unsigned = try unsignedCopy(of: typeScript) + let byteOrder = try unsigned.binary( + includingSignature: false, limits: .standard, fieldOrder: .utf8Bytes) + #expect(byteOrder != (try unsigned.binary(includingSignature: false))) + let signature = try await ProtoWallet(rootKey: key(11)).createSignature( + .init( + protocolID: try CertificateProtocols.signature, + keyID: try WalletKeyID(unsigned.signatureKeyID), + counterparty: .anyone, + payload: .digest(BSVHashing.sha256(byteOrder)) + ) + ).signature + let goSigned = try unsigned.replacingSignature(signature) + #expect(goSigned.signature != typeScript.signature) + #expect(try await goSigned.verifySignature()) + + var fields = unsigned.fields + fields[try CertificateFieldName("zip2")] = try CertificateCiphertext([0xFF]) + let tampered = try Certificate( + type: unsigned.type, serialNumber: unsigned.serialNumber, subject: unsigned.subject, + certifier: unsigned.certifier, revocationOutpoint: unsigned.revocationOutpoint, + fields: fields, signature: signature) + #expect(try await tampered.verifySignature() == false) + let tamperedTypeScript = try Certificate( + type: unsigned.type, serialNumber: unsigned.serialNumber, subject: unsigned.subject, + certifier: unsigned.certifier, revocationOutpoint: unsigned.revocationOutpoint, + fields: fields, signature: typeScript.signature) + #expect(try await tamperedTypeScript.verifySignature() == false) + } + + @Test("names whose localeCompare order is not reproduced are not signed") + func refusesUnreproducibleNames() async throws { + for name in ["øre", "e\u{301}t\u{E9}", "\u{80}", "日本", "tab\tname"] { + let unsigned = try Certificate( + type: try CertificateTypeID([UInt8](repeating: 0x35, count: 32)), + serialNumber: try CertificateSerialNumber([UInt8](repeating: 0x36, count: 32)), + subject: try key(7).publicKey, + certifier: try key(11).publicKey, + revocationOutpoint: Outpoint( + transactionID: TransactionID( + exactDigestBytesGuaranteed: [UInt8](repeating: 0, count: 32)), + outputIndex: 0), + fields: [ + try CertificateFieldName(name): try CertificateCiphertext([1]), + try CertificateFieldName("age"): try CertificateCiphertext([2]), + ]) + await #expect(throws: CertificateFieldNameError.unsupportedCharacter) { + try await unsigned.signed(using: ProtoWallet(rootKey: key(11))) + } + } + #expect( + CertificateFieldNameError.unsupportedCharacter.localizedDescription + == "Certificate field names must use only plain ASCII letters, digits, spaces and " + + "symbols, and accented Latin letters.") + } + + private func unsignedCopy(of certificate: Certificate) throws -> Certificate { + try certificate.withoutSignature(keepingReceivedOrder: false) + } + + private func hex(_ text: String) throws -> [UInt8] { + try Hex.decode(text, maximumDecodedByteCount: text.utf8.count / 2) + } + + private func key(_ scalar: UInt8) throws -> PrivateKey { + var bytes = [UInt8](repeating: 0, count: 32) + bytes[31] = scalar + return try PrivateKey(bytes) + } +} + +extension Certificate { + /// The same certificate with no signature, with or without the order + /// its fields arrived in. + fileprivate func withoutSignature(keepingReceivedOrder: Bool = true) throws -> Certificate { + var copy = try Certificate( + type: type, serialNumber: serialNumber, subject: subject, certifier: certifier, + revocationOutpoint: revocationOutpoint, fields: fields) + if keepingReceivedOrder { copy.receivedFieldOrder = receivedFieldOrder } + return copy + } +} diff --git a/Tests/BSVWalletTests/Substrates/WalletWireSubstrateTests.swift b/Tests/BSVWalletTests/Substrates/WalletWireSubstrateTests.swift index d6f3979..43d1d11 100644 --- a/Tests/BSVWalletTests/Substrates/WalletWireSubstrateTests.swift +++ b/Tests/BSVWalletTests/Substrates/WalletWireSubstrateTests.swift @@ -1,5 +1,6 @@ import BSVCore import BSVCrypto +import BSVKeys import BSVTransaction import BSVWallet import Testing @@ -52,6 +53,104 @@ struct WalletWireSubstrateTests { #expect(WalletCall.allCases.count == 28) } + /// The wallet wire carries the largest payload the wallet's own + /// cryptography accepts, `WalletCryptoLimits.defaultPayloadByteCount` + /// (16 MiB plus 512 KiB, the BRC-103 general-message bound), with the + /// longest originator, protocol name and key ID, in a request and in an + /// encrypt result 48 bytes longer. Frames were capped at 16 MiB before. + @Test("a maximum-size payload is signed, encrypted and HMACed over the wire, and one byte more is not") + func maximumPayloadOverWire() async throws { + let limits = WalletWireLimits.standard + #expect( + limits.maximumFrameByteCount + == WalletCryptoLimits.defaultPayloadByteCount + WalletWireLimits.frameOverheadByteCount) + #expect(limits.maximumPayloadByteCount == limits.maximumFrameByteCount) + #expect(limits.abiLimits.maximumAggregatePayloadByteCount == limits.maximumFrameByteCount) + let key = try PrivateKey(Array(repeating: 0, count: 31) + [9]) + let processor = WalletWireProcessor( + wallet: CryptoWallet(crypto: ProtoWallet(rootKey: key)), + authorizer: OriginatorRecorder(), + failureMapper: try WalletWireRedactingFailureMapper(limits: limits), + beefLimits: try substrateBEEFLimits(), + certificateLimits: .standard, + wireLimits: limits + ) + let client = try WalletWireTransceiver( + transport: processor, + originator: String(repeating: "o", count: WalletWireLimits.hardMaximumOriginatorUTF8ByteCount), + beefLimits: try substrateBEEFLimits(), + certificateLimits: .standard, + wireLimits: limits + ) + let protocolID = try WalletProtocolID( + securityLevel: .everyAppAndCounterparty, + name: String(repeating: "p", count: WalletProtocolID.maximumNameUTF8ByteCount)) + let keyID = try WalletKeyID(String(repeating: "k", count: WalletKeyID.maximumUTF8ByteCount)) + var payload = [UInt8](repeating: 0x5A, count: WalletCryptoLimits.defaultPayloadByteCount) + payload[0] = 1 + payload[payload.count - 1] = 2 + + let signed = try await client.createSignature(WalletCreateSignatureRequest( + protocolID: protocolID, keyID: keyID, counterparty: .anyone, payload: .data(payload))) + let verified = try await client.verifySignature(WalletVerifySignatureRequest( + protocolID: protocolID, keyID: keyID, counterparty: .anyone, payload: .data(payload), + signature: signed.signature, forSelf: true)) + #expect(verified.valid) + + let encrypted = try await client.encrypt(WalletEncryptRequest( + protocolID: protocolID, keyID: keyID, plaintext: payload)) + #expect(encrypted.ciphertext.count == payload.count + 48) + let decrypted = try await client.decrypt(WalletDecryptRequest( + protocolID: protocolID, keyID: keyID, ciphertext: encrypted.ciphertext)) + #expect(decrypted.plaintext == payload) + + let hmac = try await client.createHMAC(WalletCreateHMACRequest( + protocolID: protocolID, keyID: keyID, counterparty: .anyone, data: payload)) + let hmacVerified = try await client.verifyHMAC(WalletVerifyHMACRequest( + protocolID: protocolID, keyID: keyID, counterparty: .anyone, data: payload, + hmac: hmac.hmac)) + #expect(hmacVerified.valid) + + // One payload byte more is refused by the transceiver before anything is sent. + let over = WalletCryptoLimits.defaultPayloadByteCount + 1 + await #expect(throws: WalletWireError.byteLimitExceeded( + kind: "signature data", actual: over, maximum: WalletCryptoLimits.defaultPayloadByteCount) + ) { + try await client.createSignature(WalletCreateSignatureRequest( + protocolID: protocolID, keyID: keyID, counterparty: .anyone, + payload: .data(payload + [0]))) + } + await #expect(throws: WalletWireError.byteLimitExceeded( + kind: "HMAC data", actual: over, maximum: WalletCryptoLimits.defaultPayloadByteCount) + ) { + try await client.createHMAC(WalletCreateHMACRequest( + protocolID: protocolID, keyID: keyID, counterparty: .anyone, data: payload + [0])) + } + + // The frame bound itself: a frame of exactly the limit is read, one + // byte more is refused as a request frame and answered in band. + let frameMaximum = limits.maximumFrameByteCount + var frame = [WalletCall.getHeight.rawValue, 0] + frame += [UInt8](repeating: 0, count: frameMaximum - frame.count) + #expect(try WalletWireCodec.decodeRequestFrame(frame, limits: limits).parameters.count + == frameMaximum - 2) + #expect(throws: WalletWireError.byteLimitExceeded( + kind: "request frame", actual: frameMaximum + 1, maximum: frameMaximum) + ) { + try WalletWireCodec.decodeRequestFrame(frame + [0], limits: limits) + } + let answer = try WalletWireCodec.decodeResultFrame( + try await processor.transmit(frame + [0], maximumResponseByteCount: frameMaximum), + limits: limits) + guard case .failure(let remote) = answer else { + Issue.record("an oversized frame was not answered with an error frame") + return + } + #expect(remote.code == 1) + #expect(remote.message.contains( + "request frame is \(frameMaximum + 1) bytes, above the limit of \(frameMaximum)")) + } + @Test("strict parameter decoding happens before originator authorization") func rejectsMalformedParametersBeforeAuthorization() async throws { let recorder = OriginatorRecorder() @@ -550,6 +649,33 @@ private actor OversizedTransport: WalletWireTransport { func requestedMaximum() -> Int? { maximum } } +/// A wallet whose key operations are a `ProtoWallet`'s. +private struct CryptoWallet: WalletInterface { + let crypto: ProtoWallet + + func getPublicKey(_ request: WalletGetPublicKeyRequest) async throws -> WalletGetPublicKeyResult { + try await crypto.getPublicKey(request) + } + func encrypt(_ request: WalletEncryptRequest) async throws -> WalletEncryptResult { + try await crypto.encrypt(request) + } + func decrypt(_ request: WalletDecryptRequest) async throws -> WalletDecryptResult { + try await crypto.decrypt(request) + } + func createSignature(_ request: WalletCreateSignatureRequest) async throws -> WalletCreateSignatureResult { + try await crypto.createSignature(request) + } + func verifySignature(_ request: WalletVerifySignatureRequest) async throws -> WalletVerifySignatureResult { + try await crypto.verifySignature(request) + } + func createHMAC(_ request: WalletCreateHMACRequest) async throws -> WalletCreateHMACResult { + try await crypto.createHMAC(request) + } + func verifyHMAC(_ request: WalletVerifyHMACRequest) async throws -> WalletVerifyHMACResult { + try await crypto.verifyHMAC(request) + } +} + private enum TestFailure: Error { case unexpectedCall case secret(String) diff --git a/Tests/BSVWalletTests/Wire/WalletWireTypeScript41VectorTests.swift b/Tests/BSVWalletTests/Wire/WalletWireTypeScript41VectorTests.swift index 65a6e9f..4b28fb9 100644 --- a/Tests/BSVWalletTests/Wire/WalletWireTypeScript41VectorTests.swift +++ b/Tests/BSVWalletTests/Wire/WalletWireTypeScript41VectorTests.swift @@ -69,6 +69,20 @@ struct WalletWireTypeScript41VectorTests { #expect(walletIsBalanceBasket("p btms balance tokens")) #expect(!walletIsBalanceBasket("balance")) #expect(!walletIsBalanceBasket("p btms tokens")) + // Matched after `validateIdentifier`'s trim().toLowerCase() + // (wallet/validationHelpers.ts:376-418), as the wallet toolbox does. + #expect(walletIsBalanceBasket(" Balance Tickets")) + #expect(walletIsBalanceBasket("\u{A0}\u{FEFF}BALANCE default\t\n")) + #expect(walletIsBalanceBasket("\u{3000}P BTMS Balance tokens")) + #expect(!walletIsBalanceBasket(" balance")) + #expect(!walletIsBalanceBasket("\u{85}balance default")) + #expect(!walletIsBalanceBasket("p balance tokens")) + // The pattern matches code units: a space followed by a combining + // mark is still a space, and `[^ ]+` admits a tab. + #expect(walletIsBalanceBasket("balance \u{301}x")) + #expect(walletIsBalanceBasket("p \u{301}m balance x")) + #expect(walletIsBalanceBasket("p a\tb balance x")) + #expect(!walletIsBalanceBasket("p m \u{301}balance x")) let request = WalletWireActionRequest.listOutputs( try WalletListOutputsRequest(basket: "balance default") @@ -97,6 +111,19 @@ struct WalletWireTypeScript41VectorTests { } #expect(jsonBalance.totalOutputs == 5_000_000_000) #expect(String(decoding: try codec.encodeResult(jsonResult), as: UTF8.self) == json) + + // A basket the wallet normalises to a balance query reads the full balance. + let spaced = WalletWireActionRequest.listOutputs( + try WalletListOutputsRequest(basket: " Balance Tickets") + ) + let spacedResult = try WalletWireCodec.decodeActionResult( + frame, expectedCall: .listOutputs, request: spaced, beefLimits: actionBEEFLimits() + ) + guard case .listOutputs(let spacedBalance) = spacedResult else { + Issue.record("expected listOutputs") + return + } + #expect(spacedBalance.totalOutputs == 5_000_000_000) } // MARK: W4 and G5 in-band processor errors